The Basics of Fetch API

A Guide for Beginners

Brenden Thornton
Aug 25 · 3 min read

Requesting resources from an API is a pretty common and almost vital feature needed for building modern applications. Whether you’ve built your own API or you’re using a third-party API, you need a way to make your requests without slowing down your application. This is where the Fetch API comes into play and it’s one of the most popular tools to get the job done.

Let’s Talk About Ajax

Before we get into Fetch, we need to briefly cover what it solves from a conceptual standpoint. Ajax stands for Asynchronous, JavaScript, XML, and it’s a technique for requesting data and updating the DOM dynamically without refreshing the entire page. The request you make takes place in the background of your application and if successful, it updates your page without forcing the user to wait.

The Fetch API

There are a handful of ways to handle Ajax requests but one of the most popular ways is using the Fetch API. In this API you are provided a fetch() method which returns a Promise that lets you retrieve the response of the request. On top of this basic functionality, you’re able to add more details as to what you want to do with the response data and this is one of the great parts of using Fetch. Let’s stop talking and start building a basic fetch request!

Creating a Request

Building a basic request is pretty straightforward. Fetch provides us the fetch() method that I mentioned earlier and it only requires one argument which is url or endpoint from the desired API. For my example, I’m going to be using the ever so popular PokeAPI which is a great resource for all things Pokemon!

fetch(`https://pokeapi.co/api/v2/pokemon/pikachu/')

Here’s our basic setup of the fetch() method. We pop in the desired API endpoint and now when this runs, it will perform an HTTP GET request, or will it? There’s another basic step after this that is needed to see our response.

fetch(`https://pokeapi.co/api/v2/pokemon/pikachu/')
.then(response => response.json() )
.then(pokemon => console.log(pokemon) )

In this next step you can see we’re using .then which correlates with the fact that fetch is based on using Promises. When making our request, we don’t want our user interface to stop and wait for the request to finish so we use .then to wait for the servers response where we can then console.log the data returned.

Let us breakdown what’s happening in each .then . When we launch our request with fetch() a Promise is initiated and we must wait for the Response object. This is handled with our first .then which doesn’t return the data but gives us the Response object.

{
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://pokeapi.co/api/v2/pokemon/pikachu/"
}

Here we can see our response which is information about the request we made. From here we have the ability to call a .json() method on our response which will trigger another Promise that returns our response body as json data.

Error Handling

The last piece to the puzzle is handling errors when requests go wrong. This functionality is needed when ask for non-existent resources or when a resource needs authorization. To do this we use .catch to “catch” our errors.

fetch(`https://pokeapi.co/api/v2/pokemon/pikachu/')
.then(response => response.json() )
.then(pokemon => console.log(pokemon) )
.catch( error => console.error('error:', error) );

Conclusion

You’ve officially built a basic fetch request to retrieve data on Pikachu! As you can see, this tool makes the process of consuming api data pretty simple while also allowing plenty of flexibility. Within your .then ‘s you can create functions to manipulate your data before it updates the DOM or you can use Redux actions to help maintain state within a React application. Another feature I didn’t cover is the ability to customize Headers which I could create a whole separate article about.

I highly recommend exploring deeper into the Fetch API and I’ll make sure to leave you further resources at the end of this article. If you enjoy consuming API’s like I do, then do yourself a favor and learn the Fetch API!

Happy Coding!

The Startup

Medium's largest active publication, followed by +504K people. Follow to join our community.

Brenden Thornton

Written by

Full-Stack Developer. @FlatironSchool. UCF. Loving Father & Husband.

The Startup

Medium's largest active publication, followed by +504K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade