Everything You Need To Know About JavaScript Fetch API

Posted by TotalDC

When you are creating a web application, more than often you have to work with external data. For example your database or third-party API. Let’s learn what is JavaScript fetch API and how to use it.

AJAX appeared in 1999 and it was a better way to create web applications. Before AJAX, you had to re-render an entire web page even for minor updates. But AJAX gave a way to fetch content from the backend and update selected user interface elements.

In this article you will learn:

learn what javascript fetch api is and how to use it

JavaScript REST APIs

Simply put, a REST API lets you push and pull data from a datastore. This might either be your database or a third party’s server like the weather station API.

There are a few different types of REST APIs:

  • GET — Get data from the API. For example, get a Twitter user based on their username.
  • POST — Push data to the API. For example, create a new user record with name, age, and email address.
  • PUT — Update an existing record with new data. For example, update a user’s email address.
  • DELETE — Remove a record. For example, delete a user from the database.

There are three elements in every REST API. The request, response, and headers.

Request — This is the data you send to the API, like an order id to fetch the order details.

Response — Any data you get back from the server after a successful / failed request.

Headers — Additional metadata passed to the API to help the server understand what type of request it is dealing with, for example, “content-type”.

By using REST API you can build a single API layer for multiple applications to work with.

JavaScript Fetch API

Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more.

Fetch works with promises, not callbacks. JavaScript developers have been moving away from callbacks after the introduction of promises.

Here is what a simple fetch function looks like:

// GET Request.
fetch('someSortOfURL')
    // Handle success
    .then(response => response.json())  // convert to json
    .then(json => console.log(json))    //print data to console
    .catch(err => console.log('Request Failed', err)); // Catch errors

The first parameter of the Fetch function should always be the URL. Fetch then takes a second JSON object with options like method, headers, request body, etc.

Worth noticing that Fetch does not return the data as a response. Instead, Fetch contains information about the response object itself. This includes headers, status code, etc. We call the res.json() function to get the data we need from the response object. Another important difference is that the Fetch API will not throw an error if the request returns a 400 or 500 status code. It will still be marked as a successful response and passed to the then function.

Fetch only throws an error if the request itself is interrupted. To handle 400 and 500 responses, you can write custom logic using response.status. The status property will give you the status code of the returned response.

Working With JavaScript Headers

You can pass headers using the headers property. You can also use the headers constructor to better structure your code.

fetch('someSortOfURL', {
  method: "GET",
  headers: {"Content-type": "application/json;charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json)); 
.catch(err => console.log(err));

Passing Data To a POST Request In JavaScript

For a POST request, you can use the body property to pass a JSON string as input. Do note that the request body should be a JSON string while the headers should be a JSON object.

// data to be sent to the POST request
let _data = {
  title: "foo",
  body: "bar", 
  userId:1
}

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: "POST",
  body: JSON.stringify(_data),
  headers: {"Content-type": "application/json; charset=UTF-8"}
})
.then(response => response.json()) 
.then(json => console.log(json));
.catch(err => console.log(err))