Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 833 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Get JSON data from an API using fetch

1:19 JavaScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?