Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Get JSON data from an API using fetch

    Trevor MillerTrevor Miller

    We will use fetch to get JSON data from an API. fetch is available globally on the window object in the browser or via libraries in other JS environments.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    First let's type const.URL. Let's set that equal to the GitHub API, so that api.github.com/users. Then we need some sort of user here. Let's type const user equals some GitHub username. If we used mine, that's Trevor D. Miller.

    Now we can use the global fetch function by saying fetch, and then passing it our URL. This function will return a promise. We can say .then. When this promise resolves, it will contain our response. It will say response.

    Inside of this function, we can say response.JSON to covert our response into JSON. Now let's type .then, and we'll have our JSON data. Let's console log out the type of the GitHub account. We see have the type of user because the Trevor D. Miller GitHub account is of type user.

    If we go back up to our user string here and use Facebook, we now see that Facebook is of type organization.

    Let's go down and type .catch. This will be used if we get an error. We will get our error, and we can use that error. Let's log out the error in this case. Let me turn off my network connection. Now we get this type error fail to fetch.