Using fetch() to import data

Reading Time: 4 minutes 🕑

Last updated: October 7, 2021.

Building a good-looking frontend is a common goal for early-stage frontend developers. But how do you take your builds to the next level by moving from static to dynamic content?

Javascript’s fetch() method helps you achieve this by retrieving information from servers (APIs) external to your frontend environment.

For demonstration purposes, this article will show you how to retrieve travel information from Travelbriefing.org. But the same technique may be used to retrieve almost any type of data (to get started, you may want to check out this list of free APIs provided by public-apis.io to see what is possible!).

Making a GET request to an API endpoint

To retrieve data from an API, you must make a GET request to an API endpoint. Available API endpoints are usually provided on the website of the API provider.

In this article, we will request data from the travel information API provided by Travelbriefing.org. The following are listed by the publisher as available API endpoints:

As the list of countries is in .json format it is viewable in a regular browser. We need to check this first as the API endpoint requires entry of a country name.

We could try and guess a country name, but the API expects this in a certain format or the GET request will fail (e.g. should that be UnitedKingdom, GreatBritain or England?).

The list not only provides us with the expected country names, but also the full url for each endpoint. Let’s now use fetch() to request data about for the Netherlands. Of course, feel free to substitute this for a different country of interest!

Retrieving data with fetch()

fetch() allows us to easily retrieve data from a country endpoint by simply adding it as a parameter in a fetch request:

Running this code retrieves the data so we may now use it for our purposes. Simple, right?

But how do we access it? And what if something goes wrong with the request? (e.g. the request is mistyped, or the API server is down).

Making the data accessible

After…well, fetching, a fetch() request returns something called a promise. The contents of a returned promise can be accessed using a special method: .then(). This method must be included directly after fetch() — i.e. no semi-colon after the fetch() line, or it will not work!

Notice there is now a parameter included in the .then() method called res (short for ‘result’). It is convention to name this parameter res but it is entirely arbitrary (we could call it something else and it would make no difference to the functionality).

Whatever the .then() parameter is named, it now becomes the object containing the retrieved data. Let’s work with it to access that data now!

If we use console.log() to inspect the res object, we see that the body of the object (where the main data should appear) is something called a ReadableStream.

We can access the readable stream and convert its contained JSON data to the format of a Javascript object by applying the .json() method to the res object.

As a slight aside, be aware that it is possible to access the result of a promise using .then(), do something to the result and then access the result of the first .then() in a second .then(). This passing down of the promise result can be continued indefinitely!

We only need to this once here, passing down the result of applying the .json() method and receiving the result in a second .then(). The result is again received in the parameter (whatever we choose to call it). We use res again:

Making the data available in a new function

For working with the (now modified) result of our request, it is useful to make it available to us outside the fetch() request and subsequent handling through the .then() methods.

To do this, let us create a separate function inside which we can program what we want to do with the result. Entirely arbitrarily, we call this dataHandler() and add the parameter inputData. We also add a console.log() call to display the contents of the passed in inputData parameter as a check that it is working.

With this, we have written a function capable of receiving the result from our fetch request. But we still need to modify the request itself to send its result to the function.

To do this, we need to modify the final .then to send its result to the dataHandler function. We do this by calling the function and passing the res as the parameter — so now, when the function runs, the data parameter will be taken by the modified res object.

If we now view the data parameter in the console log, we can see the data previously in res outputted from within the dataHandler function.

We are now in a position to extract the parts of the data we wish to use. We can do this by calling data and adding dot notation to reach our properties of interest nested within the data object. For example:

In a follow-up blog on July 19, I will show you how to use this data to build a full-fledged travel information app! We will cover the typical issues you may encounter along the way, such as how to build an app around a single country endpoint.

What is the request doesn’t work?

For a variety of reasons, a fetch request may fail. Perhaps the endpoint url was mistyped. Or the API server is down.

To deal with a potential error, we can add the .catch() to the end of our .then() chain. This will ‘catch’ any errors that occur in our .then() chain (and not catch anything if it is succesful). .catch only runs if an error is encountered somewhere in the chain.

Let’s trigger an alert for the user if our fetch request fails so they are not left in suspense. In this example, I have misspelled “Netherlands” as “Nethlands” so the alert will show when the code is run.

For our own trouble-shooting purposes, we can also log the error in the console.

When adding .catch(), its parameter, like then, can be called anything. It is only convention to name the parameter err. It can be handled in exactly the same way as a result inside of a .then() method.

It is optional to deal with errors. However, it is good practice, as otherwise you may leave your users hanging!

Happy fetch() -ing

This article showed you how to make a fetch() request to an external API, make the data available in a new function and how to deal with an error.

Have an itch to fetch now? Check out this list of free APIs from public-apis.io to start making using of fetch() in your project.