Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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.

    javascriptJavaScript
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:19 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.

    00:34 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.

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

    01:02 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.

    Discuss

    Discuss