What is Fetch API in JavaScript?

Maybe you’re moving to the next level in your programming journey or you want to refresh your memory.

In this article I’ll be writing about Fetch APIs and how to use them.

You should have knowledge of JavaScript Promises and Asynchronous JavaScript before using the fetch API.

A fetch API (Application Programming Interface) is used to make HTTP requests.

This is when a client requests data from the URL and it processes the data and sends it back to the client based on their request.

It is more powerful and flexible than the older XMLHttpRequest.

It is akin to waiters in a restaurant, the customer (your pc) requests for a particular meal (data) then the waiters (fetch API) depart to get that meal for the customer.

How to use Fetch API

You can make a request to the URL by using fetch(). The fetch() method takes one compulsory argument— the path to the resource you want to use. After the request has been sent, the fetch() runs the processes and returns a response.

Optionally, you can also pass in an object as a second argument to specify some information, and configure your fetch request like setting the methods, adding the headers and body content.

This is the syntax for fetching data with the Fetch API:

fetch(url) //If you don't need the options.
fetch(url, options) // If you want to add the options.

Here is an example of fetch() without options:

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data)
.catch(error => console.error('Error:', error));

In the syntax above, the fetch() method contains the resource you want to fetch from the server.

There are two .then() methods. The first one receives the response (this object represents the data) from the server (like receiving a package from an online store).

Then it parses that response as a JSON using the .json() method so that JavaScript will be able to read, and understand the data (like when you use a translator to understand a different language).

The second .then() object now takes that response that has been converted, represented by the data object and logs it out to the console.

After these steps, the .catch() block handles the errors.

What are HTTP Methods?

HTTP methods allow you to interact with the resources over the network. Each method has its own specific operation on the resource.

We will focus on just two of those methods, the GET method and the POST method.

What is the GET Method?

You can’t fetch an API without getting the data, this is where the GET method comes in. The GET request is used to retrieve data from a server. It is the default method for fetch requests, it doesn’t send a request body.

I will walk you through an example of how to use the GET request. The GET request is the same thing as my second code example, but I will be showing you how to add an if statement to check for errors.

const url = 'https://api.example.com/data'; // The resource to be fetched
fetch(url)
.then(response => {
    if(!response.ok){
        throw new Error('network not reachable' + response.statusText);
        }
        return response.json();
    })
.then(data => console.log(data))
.catch(error => console.error('Error:', error))

So, you will notice that the if statement throws an error while the .catch() also handles errors.

They both have different functions but they also work together.

Let’s start with the if statement. When the fetch() request has gone through (reached the destination), the if statement checks if there are any errors (if any problem occurred) that will hinder the return of the response.

If there are any errors, it throws an error message or the status of the error to help the client figure out what went wrong. When the error is thrown, it stops the other .then() method.

The .catch() block catches this error that was thrown by the if statement, and handles the error depending on what you defined (logging it out in the console or showing a message to the user).

However, if there is an obstruction in the process, and the fetch request doesn’t go through (e.g., no internet connection, DNS issues). The .catch() block still catches these errors and handles them.

This works according to JavaScript’s Promise.

What is the POST Method?

Sometimes you might want to send data like uploading a file or submitting a form. That is where the POST request comes in handy.

We’ll dive into how to make POST requests with Fetch API now.

The POST request has the same syntax as the GET request, but unlike the later, you will need to add the configuration object to the .fetch() method.

In the POST request configuration, you need to specify the method (which is POST). Also you will add a header to tell the browser what kind of file you’re sending. then you add a body that contains the file that you want to send.

This is the syntax for a POST request:

const url = 'https://api.example.com/users'; 

// The data to be posted
const userData = {
    username: 'Jane_Doe',
    age: '42',
    gender: 'female',
};

fetch(url, {
    method: 'POST', // The HTTP method
    headers: {
        'Content-Type': application/json // The set content for identification
    },
    body: JSON.stringify(userData), // changes the data to string using JSON 
})
.then(response => {
    if(!response.ok){
        throw new Error('Network response error!'); 
    }
    return response.json();
})
.then(newData => alert(newData))
.catch(error => console.error('Error:', error));

As seen in the above example, the method has been set to POST, the header Content-Type has been set to application/json to notify the server that this is a .json file.

The body contains the data we sent to the server. Since the body can only contain strings, it is converted to a string using the JSON.stringify() method.

Just like in the GET request, the .then() method receives the response, checks for error, and parses the response . while the second .then() method handles the data.

The .catch() method handles the error as always.

Conclusion

In this article, we explored the Fetch API and its capabilities for making HTTP requests in JavaScript. We learnt how Fetch is more powerful than XMLHttpRequest. We covered the basics of using fetch() for GET and POST requests, handling responses and errors, and configuring requests with methods, headers, and body content. Examples demonstrates how to fetch and send data, providing a comprehensive guide to effectively using the Fetch API in your programming journey.

0
Subscribe to my newsletter

Read articles from Anyata Eugene Chigozie directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anyata Eugene Chigozie
Anyata Eugene Chigozie