This tutorial help to access Rest API Using fetch API.I am using vanila JavaScript to create method fetch data.You can use GET/POST/PUT and DELETE method to consume rest api using JavaScript.

You have used jquery ajax method to get data from rest api, But JavaScript introduced Fetch API to get data from rest api. You can get more information about AJAX from JQuery Ajax Add, Edit And Delete Example with Demo.

The fetch API allows to create XMLHttpRequest (XHR) request and handle callback using Promises.The callback is legacy approaches to handle rest api request.The Fetch API uses Promises to avoid callback.The ES7 introduced async-await to avoid promise.The promise is help to send the request and receive a response.

You can also use fetch api with nodejs , if you want 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 is using 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 determines with a Blob.
  • formData() – Also returns a promise but one that determines with FormData object.

Genislab Technologies

NexGeneration complete end-2-end software testing & modern development operations tooling & solutions

Do you want to discuss your testing requirements with us? please don’t hesitate to hit the contact us button below, and we will get back to you at our earliest..