Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How To Access REST API Using JavaScript fetch API

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.

The post How To Access REST API Using JavaScript fetch API appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

How To Access REST API Using JavaScript fetch API

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×