How to use the JavaScript Fetch API to Retrieve Data from an API

There comes a time in a developer’s journey when they want to build something more complex than the typical to-do list or calculator application. Not saying those aren’t great beginner applications but their very limited in what they can do. Now imagine having access to third party data, for example, the weather of any city in the world or all the HD images from unsplash.com. What would you build? A weather application or a wallpaper downloading website would be good choices.

Unsplash API demo application

All this is entirely possible through the use of an Application Program Interface (API). Indeed, we can use a variety of API’s to access data and create a wide range of applications with it. The best part is that most API’s are free to use and there’s one for nearly anything you can think of. Don’t believe me? Check out this list of 100 API’s. If you want to use an API, all you have to do is go to the API’s website and create an account. In return, they’ll give you a secret API key which you can use to access the API.

That sounds great but how do we retrieve data from the API? One quick and simple way is to use the fetch API that’s built into JavaScript. Fetch is basically a function used for making server requests and loading the information as needed.

A quick note before we dive into the tutorial, it’s imperative that you keep your API key’s a secret but I’ll be sharing mine with you for educational purposes. Also, we’ll be working with the Unsplash API for this example. Unsplash gives us access to thousands of HD images which we can display on the browser or even download. In this case, we’ll let the user choose what type of image they want the API to return through the use of an input field. You can get your free Unsplash API key here if your interested.

Alright, let’s dive into this. For the HTML markup, we’ll need the following code.

   <p>Search for a random image</p>   <input type="text" id="user_input">   <button id="search">Search</button>   <br><br>   <span id="isValid"></span>   <div id="random_image"></div>

The most important things here are the input field for enabling user input, the button for submission, the span for validation, and the div for displaying the image. Notice that I’ve given each one of these elements their own respective id with a name that’s directly related to their purpose. For instance, the input field has an id of user_input and the button has an id of search.

Below is our CSS file. I kept the CSS properties to a minimum for simplicity.

#random_image{   width: 500px;   height: 281px;   background-position: center;   background-size: cover;}

As you can see we gave our random_image div a width and height otherwise we won’t be able to see the image and a background-position and background-size to center and fit the image perfectly inside the div. Of course, we haven’t added the image yet, we’ll do that dynamically with JavaScript once we receive it from the API.

Now the fun part, the JavaScript file.

document.querySelector("#search").addEventListener("click", () => {   const user_input = document.querySelector("#user_input");   request(user_input);})

Let’s start off by adding a click event listener to the button we created. When the button is clicked, let’s grab the user input and send it over as a parameter in the request function. The request function is the one responsible for making the fetch request to the API. Hence, why we called it request.

Let’s break the request function down into pieces.

request = (user_input) => {   let url = `https://api.unsplash.com/search/photos?query=${user_input.value}&per_page=1&client_id=SouHY7Uul-OxoMl3LL3c0NkxUtjIrKwf3tsGk1JaiVo`;

First, we create a variable and initialize it to the URL we’re making a request to. This URL is also known as the API endpoint. The endpoint is going to be different from API to API so you’ll have to read the documentation of the API your working with before creating it. Notice that we’re using the user_input value within this endpoint. That’s because we want this API to search for and return the type of image the user searched for. Please note that I didn’t include a closing tag because we’re going to keep adding to this function.

Next, we simply make a request to the endpoint using the built in fetch function. Pretty easy right?

fetch(url)

Once we make the request, the API will send back a response, the response will either be the data we requested or an error. By convention, we handle the response with promises, which are basically a chain-link of functions.

In our first promise below, we have an if statement that checks if we received an error from the API, if we did, it throws an error, otherwise it returns the data or response as a JSON object.

.then(response => {   if (!response.ok) throw Error(response.statusText);      return response.json();})

Our second promise grabs the object. In the second line we query select #isValid and set the text content to an empty string since the request was successful. Then we query select #random_image and set it equal to data.results[0].urls.raw, this is where the image is stored within the object. I highly recommend you console log data.results within this promise to view all the data in the object. This way you can learn to access and display the data that you want to display.

.then(data => {document.querySelector("#isValid").textContent = "";document.querySelector("#random_image").style.backgroundImage = `url(${data.results[0].urls.raw})`;})

The third and final promise simply catches the error that was thrown by the first promise and displays it on the screen.

.catch(error => document.querySelector("#isValid").textContent = error);}

Here’s the entire request function.

request = (user_input) => {   let url = `https://api.unsplash.com/search/photos?query=${user_input.value}&per_page=1&client_id=SouHY7Uul-OxoMl3LL3c0NkxUtjIrKwf3tsGk1JaiVo`;   fetch(url)   .then(response => {      if (!response.ok) throw Error(response.statusText);         return response.json();   })   .then(data => {      document.querySelector("#isValid").textContent = "";      document.querySelector("#random_image").style.backgroundImage = `url(${data.results[0].urls.raw})`;   })   .catch(error => document.querySelector("#isValid").textContent = error);}

You can use this code as a template for making API requests. Like I said earlier, the only thing you’ll need to change is the endpoint and how you retrieve data from the JSON object, since that’s different for every API . Now go out there and build some cool stuff!

Can’t get it to work? Check out my codepen.

--

--

--

Passionate software developer with an eye for design and detail. Contact me: https://miguelznunez.com/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript ES6 Basic QNA

Very simple REST API using Express.js

A short GIF showing an example of how an API can be used in a real world project

Rejolut - Top React Development Company

React development company

JavaScript News and Updates (September 2018)

Core Concept of React JS

React vs Angular: Which framework is right for you?

React VS angular

Your Guide To State In React - A UI Example

//platform.twitter.com/widgets.js from Twitter https://twitter.com/thepoolsideceo

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Miguel Nunez

Miguel Nunez

Passionate software developer with an eye for design and detail. Contact me: https://miguelznunez.com/

More from Medium

Coding Bootcamp 8/13: The DOM and ReactJS + Holiday Break!

The Need for TypeScript-first Beginner Learning Content

How Much Does a Game Developer Make?

A few valuable things from my journey in a web development boot camp.