Retrieving Data using the Fetch API

Published May 27, 2019 in api , fetch , JavaScript - 1 Comment

Whether you are programming for something work-related or you are just hacking something together as a side project, eventually the situation comes up when you want to retrieve some data from a source and display the information on your web page. If the information isn’t coming from a database you own, most likely that information is being retrieved from an API. In this post, I am going to show you how to retrieve data from an API using the browsers Fetch API.

What is an API

To make sure we’re starting off on the right page together let’s talk about what an API is.  API stands for Application Programming Interface and it dictates how one computer talks to another. There is a wide range of API’s available to practice with and lots of them are free.   The only requirement in most cases is you need to get an API key.  Your API key is typically a unique string that allows the API owner to determine where requests are coming from.  Think of it as a longer PIN number.  Here is a GitHub page that has a good list of some free API’s to play around with.

The Fetch API

The Fetch API is aptly named because it is used to fetch data from a source that you can parse and use.  It is built into the browser, the same as setTimeout and setInterval.  The Fetch API is promise based.  If you are not familiar with promises a quick definition is that a promise represents an object that will eventually return a value from an asynchronous action whether the action was successful or not.

      fetch(url)
        .then(response => response.json())
        .then(data => {
          //implementation
        });

This is the basic outline of a request using fetch.

  • First, we invoke fetch and pass in the URL to the API that we want to retrieve data from
  • Next, we chain .then (which is part of promises) with the raw data that comes back from our request
  • Inside of our .then we convert the raw response to a JSON object with .json() (which itself returns a promise) in order to format the data in a way that it is easily usable in our app.
  • Our second .then is where we take the formatted data and implement our logic using the data we retrieved.

In this example, we are only passing in url to fetch, but there is a second optional Request parameter that you can pass into Post data for example and then use the data that comes back in the same way.  I haven’t used fetch that way personally, but you can read more about it here.

The structure for a basic fetch request doesn’t take too many lines of code, but it is still a very powerful tool.  Let’s look at a more concrete example.

Using Data From Fetch

I’m going to use the OMDb API, which is a free API that pulls in information from the Open Movie Database website.  I’ve replaced my actual API key because it’s generally not recommended to display your own personal API key online, so keep it protected.

      const url = `https://www.omdbapi.com/?apikey=<YOUR API KEY>&s=Avengers`;
      fetch(url)
        .then(response => response.json())
        .then(data => {
          console.log("data", data);
        });

This follows the same structure as before, but with a real url.  I’ve put the above code into an empty JS script file and we’re going to trigger our fetch on page load, but you can tie this to almost any JavaScript event for control over when you try and retrieve your data.  We’re going to trigger a fetch for all movie titles that contain the term Avengers.  Running this, we get the following output to our console:

OMDB Fetch Results

We get a JSON object with three properties: Response, Search, and totalResults.  The Search property contains what we really care about, our Movie data.  Search comes back as an array with the first 10 elements that were found by our search.  You can see That our totalResults property states there are 92 total results.  By default, the API returns the top 10, and extra parameters need to be passed in to retrieve additional results.  Let’s look at the details of the result at index 0 of our Search array.

Each Result is an object itself and has a Poster, Title, Type, Year, and imdbID as properties.   Using this, you could for example store these results in your own array, grab elements from your webpage and then programmatically display all these individual property values to your users.  You have lots of options to style and display your data once you have it.  The hardest part is just getting it into a ready to use state.

Takeaways

That’s pretty much all it takes to get started using the Fetch API and use it to create dynamic apps that use real-world data.

  • Find an API
  • Get an API Key
  • Fetch Your Data
  • Profit

See you in the next article.

More Posts
No related posts

1 comment