Javascript Fetch API Rest Web Service Example

This article will introduce the Javascript Fetch API, and use it in some code samples to consume Web Services.

The Javascript Fetch API

The Javascript new Fetch API provides an interface for fetching resources. It will seem familiar to anyone who has already used XMLHttpRequest or other Json requests APIs.

Furthermore, it provides a definition for related concepts like CORS and Http Origin header.

For this tutorial, we will use a free online Rest API, loading fake data.

GET Request

Calling a Rest Endpoint and returning the result in JSON

See Example @ JSFiddle

POST Request with Data

View Code in Action

Headers

Of course, you can easily supply your custom request headers, via a Map or the Headers interface. Then pass this map with the Request options on fetch.

Useful headers when using Rest APIs are Content-type or Origin.

View Code

Handle Response

As seen on the examples above, the response is returned when the fetch promise is resolved. This response contains Response status and code.

We can access the request body data with other methods, depending on the expected result (text, JSON, blob…).

Compatibility

Fetch API is a recent feature and is only implemented on recent browser versions. The feature can easily be detected with the presence/absence of the fetch method.

Useful Links

Mozilla Documentation

Browser Compatibility

You may also like...

1 Response

  1. March 4, 2018

    […] See : Call a Rest Web Service in Javascript […]

Leave a Reply

Your email address will not be published. Required fields are marked *