A Basic Guide to the Fetch API

As web developers, we often need the ability to retrieve data from the server in order to update our applications asynchronously. Traditionally this data is retrieved using JavaScript and the XMLHttpRequest object.

A simple example of this might look something like the code below.

In the code above, there are two calls to open() and send() as well as two listeners to handle a successful and failure request. The code above isn't that difficult to read, but as you start to add more and more logic and callbacks, it can quickly become messy.

The funny thing is that the XMLHttpRequest object was originally created by the developers of Outlook Web Access for Microsoft Exchange Server. After a number of permutations, it eventually became the standard for what we use today to make HTTP requests in JavaScript. The example above fulfills it purpose, but it isn't as clean as it could be. In the past, there have been a number of libraries and techniques to make this code simpler and easier to read with popular libraries such as jQuery and Zepto including cleaner APIs.

Step forward a few years and we have the fetch API to save the day. Take a look at the code below and compare it to the earlier code example that we looked at.

Woah! Much cleaner and easier to read. You might also notice that there are no callbacks and events, but instead that they have been replaced with the then() method. This method is part of ES6's new Promises functionality and aims to make our code much more readable and easier to understand. If you'd like to learn more about Promises, I recommend checking out this article on HTML5 Rocks for more information.

Okay, so what if I wanted to make a POST request? Well, the code would look a little something like this.

In the example above, you simply change the method to POST and add a body parameter in the fetch options. Not only does using Promises make your code cleaner, but it also allows you to chain code together to share logic across fetch requests. For more information on how to get the most out of Promises, I recommend checking out the promisejs.org website.

Support

At the moment, support for the fetch API is better than you may think! It is supported in the latest versions of Firefox, Chrome, Opera and Chrome for Android.

However, if you would like this functionality to work in older browsers, there is a polyfill available on Github. The polyfill offers browser support for IE9+ and Safari 6.1+.

Further Reading

For further information about the fetch API, I recommend having a look at the following sites:

-- Google Developers - Fetch API

-- David Walsh - Fetch API

-- Mozilla MDN - Fetch API