REST API Tutorial

How To Access REST API Using JavaScript fetch API

Summary of learning

This tutorial helps to access Rest API Using fetch API. I am using Vanila JavaScript to create a method to fetch data. You can use GET/POST/PUT and DELETE methods to consume the rest API using JavaScript.

This tutorial helps to access Rest API Using fetch API. I am using Vanila JavaScript to create a method to fetch data. You can use GET/POST/PUT and DELETE methods to consume the rest API using JavaScript.

You have used the jQuery ajax method to get data from the rest API, But JavaScript introduced the Fetch API to get data from the rest API.

The fetch API allows to creation XMLHttpRequest (XHR) requests and handles callback using Promises. The callback is a legacy approach to handling the rest api requests.

The Fetch API uses Promises to avoid callback. The ES7 introduced async-await to avoid promise. The promise is to help send the request and receive a response.

You can also use fetch API with nodejs , if you want to create rest api using nodejs. You can learn nodejs API from CRUD operations using Nodejs,MySQL and Restify

What’s JavaScript Fetch API

The Fetch API provides a fetch() method defined on window Object. The Fetch API default uses GET method to consume rest api. The fetch method has only one mandatory parameter is URL. The simple GET call using fetch() method.

fetch(url)
.then(function() {
    // success response data
})
.catch(function() {
    //server returns any errors
});

The Simple Example –

fetch('http://dummy.restapiexample.com/api/v1/employees')
.then(response => response.json())
.then(data => {
  console.log(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))

The response is not JSON but an object with a series of following methods –

  • clone() – This method implies this method creates a clone of the response.
  • json() – This method resolves the promise with JSON.
  • redirect() – This method creates a new response but with a different URL.
  • text() – In this case, it resolves with a string.
  • arrayBuffer() – In here we return a promise that resolves with an ArrayBuffer.
  • blob() – This is one determined with a Blob.
  • formData() – It also returns a promise but one that is determined with FormData object.
If you have requirements that needs our attentioN

Please feel free to contact us

We would love to hear from you

Share with your network

Facebook
Twitter
LinkedIn
WhatsApp
Email

This tutorial is intended to cover all the essentials steps and insights to understand How To Access REST API Using JavaScript fetch API

Genislab Technologies

Learn further