A dog is trying to catch a flying disk

Your Guide to Fetch API in JavaScript

· 7 min read

Introduction

The Fetch API represents a modern, powerful way to interact with Application Programming Interfaces (APIs) in web development. At its core, the Fetch API is a method used for making requests to APIs, enabling seamless communication and data exchange with various online services. By leveraging the Fetch API, developers can efficiently request, retrieve, and utilize data from APIs, helping in the process of building dynamic, data-driven web applications.

This guide simplifies the Fetch API concept, making it accessible for developers at all levels who aim to enhance their web development skills with efficient API interactions.

What is the fetch API in JavaScript?

In easy words, fetch is nothing but a request to an API or Application Programming Interface. We use fetch to interact with an API. Or, in more technical words,

Fetch is an interface through which JavaScript can make HTTP requests.

Why use Fetch?

The XmlHttpRequest or XHR can also be used to make asynchronous HTTP requests. But XHR is quite complicated to use. The fetch API is cleaner and more flexible as it uses promises. All modern browsers now support Fetch.

Image

However, one thing to keep in mind is that the promise returned by fetch will resolve even if the server responds with some error code.

How to use Fetch?

As I've mentioned before, the fetch request will return a promise. A promise is resolved if the request is successful. If you are not familiar with promises, you can check some articles from this link.

Fetch Syntax

fetch('API Url')
    .then(response => {
    //Do something with the response
	}).catch(err => {
    // Handle the Errors
});

But in most of the cases, the first response from the server is pretty ugly. So, we parse it using the json() method that makes it easier to work with. But the json() method also returns a promise. So, we have to add another then to start working with the data. The catch() method is used to handle any error.

By default, the fetch api uses the GET method. Let's GET some data from the Covid API.

fetch(`https://coronavirus-19-api.herokuapp.com/all`)
  .then((res) => {
    return res.json();
  })
  .then((data) => {
    console.log(data);
  });

Image

The const fetch = require("node-fetch"); is used to import a node.js package called node-fetch because fetch API is not implemented in NodeJS. But you don't need it to run your fetch API code into the browser.

This was pretty easy, right? Now, let's try to POST some data using fetch API.

Post Data Using Fetch

We'll use the reqres API to post data using the fetch API. We can use all the HTTP methods with the reqres website.

To post data, we add another parameter to the fetch method which will be an object. We pass the method, body and header in the second parameter. Because, by default, fetch uses GET request, we have to explicitly declare the method, which is something other than GET. The body will contain the data we are passing. This header will tell the application about the type of data we're sending and the type of data we'll accept in return.

We will send a post request to create a user in the reqres server. Let's see how we can do it.

First of all, we'll need a user object.

const user = {
    name: 'Captain Nemo',
    occupation: 'Pirate',
    email: 'captain@nemo.com'
}

Now, we'll create another object to define the method, body and type of headers.

const config = {
    method: 'POST',
    body: json.stringify(user),
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json" 
    }
}

We're almost done. The only thing left now is to use fetch to send the data. Our fetch method will look like this,

fetch('https://reqres.in/api/users', config).then(
  response => {
    return response.json()
  }
).then(data => {
  console.log(data);
})

Let's see what we get as an output.

Image

First, we are sending our data to the server. Our method, body and headers are defined in the config object. Then, the response is passed through the first then method, which returns the data. And finally, we are using the data console.log with the last then method.

The API sends us back the data with an ID and a timestamp.

Error Handling

There can be multiple reasons that a fetch request fails. Some can be,

  • The website we are requesting cannot be found.
  • We are not authorized to fetch
  • Server error

An unhandled error can be a nightmare. The catch method is the rescue officer in such cases. The catch method can catch any error during the execution of the request.

We can use the ok response property to check whether the response was successful.

fetch(`https://coronavirus-19-api.herokuapp.com/not-found`)
  .then((res) => {
    if (res.ok) {
      return res.json();
    } else {
      return Promise.reject(res.status);
    }
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => console.log('Error with message:', error));

So, we are trying to get data from a route that doesn't exist. We are implementing the ok method here to check if it resolves. Because the route is not available, the catch method catches the error and displays it using the console.log.

Conclusion

So, this is all about the JavaScript Fetch API for now. We've covered the essentials, showing you how it streamlines fetching resources in web development. It’s a great choice for interacting with APIs, making your coding journey smoother and more efficient. As you dive deeper into your projects, remember that the Fetch API is your ally, to help you handle data retrieval with ease.

Subha Chanda

About Subha Chanda

Logo
Copyright © 2024. All rights reserved.