//

FETCH API

The Fetch API is a Promise-based standard for performing AJAX requests. It provides a fetch method which returns a Promise on the window object, which we can use to perform requests from remote resources.

Why Fetch API?

The XHR or the XMLHttpRequest has been around for over 10 years, and it has a nice API built around it, but many things has changed since XHR was introduced. We have HTML5, CSS3, also close to start using ES6. From jQuery Deferred, $q and Native JavaScript Promises people became familiar and like promises in JS, its's time for a new API to do AJAX-requests and interact with them.

A Quick Look at XMLHttpRequest

Let's look at how we can use XMLHttpRequest to retrieve JSON.

We start by creating a index.html file and adding the following code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>GitHub Info</title>
  </head>
  <body>
    <div>
     <img alt="Avatar" id="avatar" style="height:100px"/>
     <p id="name">
    </div>
  </body>
</html>

The JavaScript code for our XMLHttpRequest will look as follows:

function request(params) {
  var xhr = new XMLHttpRequest();

  xhr.open('GET', params.url, true);
  xhr.onreadystatechange = function () {
    var result = JSON.parse(xhr.responseText);

    if(xhr.status === 200) {
      document.querySelector('#avatar').src = result.avatar_url;
      document.querySelector('#name').innerText =
          result.name.split(' ')[0];
    } else {
      console.log(JSON.parse(xhr.responseText));
    }
  };
  xhr.send();
}

request({
  url: 'https://api.github.com/users/szaranger'
});

Here we are using event handlers instead of Promise. These event handlers already leads into spaghetti code and mess.

Using Fetch

Let's look at how we can do the same thing with Fetch. The Ftech function is available from the global window object and the first parameter is the URL. We are using the same index.html file for the next example, but for our JavaScript code, we are using fetch instead of XHR.

fetch('https://api.github.com/users/szaranger', {
    method: 'GET'
}).then(function(response) {
  if(response.status === 200) {
    response.json().then(function(result) {
      document.querySelector('#avatar').src = result.avatar_url;
      document.querySelector('#name').innerText =
          result.name.split(' ')[0];
    });
  } else {
    console.log('Request returned ' + response.status);
  }
}).catch(function(error) {
   console.log(error)
});

As you can see, fetch API uses Promises heavily to handle results. This is going to be the future of communicating with remote APIs.

Handling the JSON Response

In our second example, using fetch, the result has a json method, which we call int turn to convert the response into a JSON object.

if(response.status === 200) {
  response.json().then(function(result) {
    ...
  });
}

This json method is a shortcut for JSON.parse(string) method.

Polyfill

There's a Polyfill available for fetch as well - https://github.com/github/fetch.

Response

To customize our fetch call, we can create a Request object with advanced options:

var request = new Request('https://api.github.com/users/szaranger', {
    method: 'GET',
    mode: 'cors',
    redirect: 'follow',
    headers: new Headers({
        'Content-Type': 'text/json'
    })
});

Now we can use this in place of the fetch call as follows:

fetch(request).then(function(response) {
  if(response.status === 200) {
    response.json().then(function(result) {
      document.querySelector('#avatar').src = result.avatar_url;
      document.querySelector('#name').innerText =
          result.name.split(' ')[0];
    });
  } else {
    console.log('Request returned ' + response.status);
  }
}).catch(function(error) {
   console.log(error)
});

The only mandatory property is the first parameter, which is the URL for the Request instance.

The response object also provides the following methods:

  • arrayBuffer - An ArrayBuffer will resolve the returned promise
  • blob - A Blob will resolve the returned promise
  • json - A JSON object will resolve the returned promise
  • text - A text string will resolve the returned promise

JSON

If you want your results formatted in JSON - you do so with the json method, which converts the raw data to a JavaScript object.

fetch(request).then(function(response) {
  if(response.status === 200) {
    response.json().then(function(result) {
      ...
    });
  }
});

Blob

Ideal for handling results like loading an image. The blob method does so by taking a Response stream and reading it.

fetch('https://avatars3.githubusercontent.com/u/658820').then(
   function(response) {
     return response.blob();
   }).then(function(blob) {
     document.querySelector('#avatar').src = URL.createObjectURL(blob);
   });

Conclusion

The fetch API's support for Promises makes it the ideal choice making AJAX requests the right way.