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
1 2 3 4 5 6 7 8 9 10 |
// The Endpoint URL let url = 'https://jsonplaceholder.typicode.com/posts/1'; fetch(url) .then(function(response) { // Parse the body as JSON return response.json(); }) .then(function(json) { // Use our JSON Object }) |
See Example @ JSFiddle
POST Request with Data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// The Endpoint URL let url = 'https://jsonplaceholder.typicode.com/posts'; // Data to Post let data = { title: 'foo', body: 'bar', userId: 1 }; // Request options let options = { method: 'POST', body: JSON.stringify(data) }; fetch(url, options) .then(function(response) { // The Post Result }) |
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.
1 2 3 |
let headers = { "Content-type": "application/json; charset=UTF-8" }; |
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.
1 2 3 4 5 |
if (self.fetch) { // run my fetch request here } else { // do something else } |
Useful Links
Xavier is a Freelance Innovation Solutions Architect and Technical Advisor. He has been working for 10 years in software development (Java, JEE, JavaScript, Angular, Node JS, React), and has solid experience as a Tech Lead and Technical Architect in different company sizes (Startup, SME, Large Enterprise), and in different sectors (Insurance, Risk Insurance, Transportation, Energy Management, Mobile Operator)
1 Response
[…] See : Call a Rest Web Service in Javascript […]