Fetch Api Usage in Javascript

The Fetch API interface allows web browser to make HTTP requests to web servers. It works asynchronously.

JQuery.ajax() and XMLHttpRequest can be used instead of the Fetch API. But fetch api is both easier to use and comes with window object. If we print the window object in console, you can see the fetch method under this window object.

// It is a method inside the window object.
console.log(this);

BASIC Usage

To use the FETCH API, it is necessary to give the url parameter to fetch() method.

fetch(url)

Then, we chain the then() promise method to the end of the method:

.then(function() {

})

EXAMPLE:

Make Get request to “https://jsonplaceholder.typicode.com/todos” address.

//// GET request
fetch("https://jsonplaceholder.typicode.com/todos")
  .then(response => response.json())//parse json data
  .then(function(todos){
    todos.forEach(todo => {
        console.log(todo.title);//print titles in console
    });
})

POST Request

Let’s make a Post request to the rest service.

// Let's send our data to the server with POST request  
let payload = {
    title: "Blog Title",
    body: "lorem ipsum", 
    userId:1
  }
  
  fetch('https://jsonplaceholder.typicode.com/posts', {
    method: "POST",
    body: JSON.stringify(payload),
    headers: {"Content-type": "application/json; charset=UTF-8"}
  })
  .then(response => response.json()) 
  .then(json => console.log(json))
  .catch(err => console.log(err));

META Data Usage

When we make a request with the Fetch API, the address from which the request is made sends META data to browser. We can print these META data to the console as follows.

//META DATAS
fetch('https://jsonplaceholder.typicode.com/posts/1').then(function(response) {  
    console.log(response.headers.get('Content-Type'));  
    console.log(response.headers.get('Date'));
    console.log(response.status);  
    console.log(response.statusText);  
    console.log(response.type);  
    console.log(response.url);  
});

You can make REST requests to https://jsonplaceholder.typicode.com/ using the Fetch API.