JavaScript

How to use the Fetch API in JavaScript

In web development you will often need to connect/communicate with other web servers to get information/data. For example, when signing up for a new account on some websites you will often see an option to sign up using your Gmail or other third party accounts. This enables you to sign up for a new account with just a single click instead of manually filling out the whole form. When you select the “sign up using a third party account” option then the application communicates with the third party application’s server and sends a request to access your information that is stored there. This request is sent through API which is a set of rules that govern how different applications or systems communicate with each other. In this article we will learn to use JavaScript to send such requests.

What is the Fetch API

Fetch API provides a simple fetch() method in JavaScript which is used for fetching, accessing and manipulating resources across the network. The fetch() method allows you to make asynchronous JavaScript and XML (AJAX) calls with JavaScript which were previously made using XMLHttpRequest. The asynchronous requests run parallel to the main program and do not stop the execution of the code below them. The code below the Fetch API request will keep running even if the API has not sent any response back. When the API responds to the AJAX call then the fetch() method is resumed.

Fetch API uses promises and provides powerful features which makes it much easier to handle web requests and their responses; it is a great way to avoid callback hells which were created when using XMLHttpRequest.

Note: The browser console is used for the demonstration of examples in this article.

The Syntax of Fetch API in JavaScript

We need to call the fetch() method in order to use the Fetch API in our JavaScript code. The fetch() method takes the URL of the API as an argument.

fetch(URL)

We need to define the then() method after the fetch() method:

.then(function() {

})

The returning value of the fetch() method is a promise. If that promise is resolved, the code present within the body of the then() method is executed. The body of the then() method should contain the code which can handle the data sent by the API.

We then need to define the catch() method; the catch() method only executes in case the promise is rejected:

.catch(function() {
});

All in all the fetch() method should look something like this:

fetch(url)
.then(function() {

})
.catch(function() {

});

Now that we have an understanding of the syntax of Fetch API, we can now move on to the real world examples of using the fetch() method on a real API.

How to use Fetch method to get Data from an API

In this example we will use a GitHub user’s API to get the user info data and display it on the console using only vanilla JavaScript; so let’s get started:

First, we will create a variable called url; This variable will hold the URL of the API that will return the repos of a user named fabpot:

const url = 'https://api.github.com/users/fabpot/repos';

Now we will use the fetch() method to call the GitHub User API;

fetch(URL)

The fetch() method takes the URL as an argument:

fetch(url)
.then(function(data) {

})
})
.catch(function(error) {

});

In the code given above we have called the Fetch API to get the repositories of a user named fabpot from GitHub. We have passed the URL to the GitHub User API as an argument to Fetch API. The API then sends back a response which is an object with a series of methods; these methods can be used to perform different functions on the received information. If we want to convert the object into JSON then we can use the json() method.

To convert the object into JSON we need to add the then() method. The then() method will contain a function; the function will take an argument called response:

fetch(url)
.then((response) => )

The response parameter is used to store the object which is returned from the API. this object is converted into JSON data using the json() method:

fetch(url)
.then((response) => response.json())

Now we can output the data in the form of JSON by adding another then() statement; this statement contains a function that takes a variable named data as an argument:

.then(function(data) {

})
})

We then use the console.log() method inside the function’s body to output the data onto the console.

.then(function(data) {
console.log(data);
})

Now we will add the catch() function to log the potential error to the console in case the promise is unfulfilled:

.catch(err {
console.error(err);
});

All in all the request to get a list of user’s repositories from GitHub should look something like this:

fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch(err {
console.error(err);
});

In the screenshot given above the promise was resolved and the body of the .then() method was executed. If the promise had remained unresolved due to some reason then the body of the .catch() method would have been executed which would do all the error handling. We have just used the .catch() method to print an error message in case the promise is unfulfilled.

Conclusion

Communicating and Fetching data from third party sources is an essential part of web development. It was achieved by using a complex tool named XMLHttpRequest which caused callback hells; Now a much simpler tool called Fetch API is used to send AJAX calls in Vanilla JavaScript as it is much better at handling the AJAX requests. In this post we have learned to use the Fetch API method to make  AJAX calls in vanilla JavaScript.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.