Yashvant's Blog

Yashvant's Blog

Fetch API in Javascript

everything you need to know about fetch api in javascript

Yashvant Vala's photo
Yashvant Vala

Published on Aug 28, 2021

3 min read

Subscribe to my newsletter and never miss my upcoming articles

So before starting let's first understand what is fetch api in javascript,

Using fetch api we can make http calls over network, most of browser have fetch api at global levels.

It is similar like jquery ajax request but some minor difference are there which is:

  • The fetch() returns promise which won’t reject on HTTP error status even if the response code is an HTTP 404 or 500. So when the server respond with headers, it promise will be resolved with ok property and it will fail if status code range isn't in 200-299. Also it can be reject on network failures or if anything prevented the request from completing.

  • fetch() won’t send cross-origin cookies unless you set the credentials init option.

A simple fetch request set up is way easier than ajax call, here is the demo

fetch('http://dummybooks.com/books.json')
  .then(response => response.json())
  .then(data => console.log(data));

Here we are fetching books data with fetch , The first argument of fetch will be the url of the resource you want to fetch.

The response object does not directly contain actual JSON reponse body but it is the representation of entire HTTP response, So using json() method we extract json data and in the second promise we will get the data we want.

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:

The fetch() method can also accept some extra argument which is totally optional or we can say it depends on the method of the request.

Here are POST method representation using fetch() API.

fetch('http://dummybooks.com/books.json', {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify({bookname:'xyz','bookprice':'$100'}) // body data type must match "Content-Type" header
  }).then(data => {
    console.log(data);

We also can send the request with credentials like following code

fetch('https://example.com', {
  credentials: 'include'
});

To cause browsers to send a request with credentials included on both same-origin and cross-origin calls, add credentials: 'include' to the init object you pass to the fetch() method.

So far we are using simple fetch api structure with then and catch block , Since it return promise we can also use async and await to make api calls and it will look much cleaner then before.

It will look like this

async function getBookData(){
  const response = await fetch('http://dummybooks.com/books.json')
  const data =  await response.json();
}

From above code you can see that we have async function where we are getting book data and we are again awaiting to the response.

This was the basic idea about fetch API, I will again come up with new fetch api part 2,

Thanks you :)

 
Share this