A Beginner's Guide to the JavaScript Fetch API ๐Ÿฆ€

A Beginner's Guide to the JavaScript Fetch API ๐Ÿฆ€

ยท

5 min read

โ“ What is the fetch API?

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.

Here in this article, we'll use fetch to interact with some free APIs. We'll also use the COVID API by javieraviles to fetch total cases of Covid19.

โœจ 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 flexible as it uses promises. Fetch is now supported by all modern browsers also. Though, 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?

Gif Source: [Giphy](https://giphy.com/gifs/xlYKItjhiDsY)

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 which 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);
  });

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 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. The 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 the 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.

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 to 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 is not 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 property of response to check whether the response was successful or not.

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 which 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.


So, this is it about the JavaScript Fetch API for now. If you liked the article, please leave โค and write a comment. I'd love to here from you. โ˜บ

Did you find this article valuable?

Support Subha Chanda by becoming a sponsor. Any amount is appreciated!