Cory Rylan

My name is , Software Developer and Speaker. Building Design Systems and Web Components.

Follow @coryrylan
JavaScript

Introduction to the Fetch API

By Cory Rylan

- 1 minute

Updated

XMLHttpRequest has been the browser standard for a long time for JSON and XML requests. For most of us in web development we are quite familiar with AJAX abstractions such as jQuery's $ajax or Angular's $q This is because for a long time browser support for XMLHttpRequest was spotty at best.

Browsers have greatly improved over the past couple of years but we continue to use abstractions because of XMLHttpRequest's clunky and ugly API. Here is a simple example.

var xhrReq = new XMLHttpRequest();
xhrReq.open('GET', '/url/api');
xhrReq.responseType = 'json';

xhrReq.onload = function() {
  console.log(xhr.response);
};

xhrReq.onerror = function(error) {};

xhrReq.send();

Pretty ugly syntax. It's not using promises to handle the response which makes complex asynchronous code a real pain.

The Fetch API

Lets look at the new Fetch API to get some JSON.

fetch('/url/api')
  .then(function(response) {
    console.log(response.json());
  })
  .catch(function(error) {});

In its simplest form that's it! Much cleaner syntax and uses modern ES6 JavaScript promises. We can chain on our promise to modify our response or to handle some other work before we hand it back.

fetch('/url/api')
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {});

Fetch by default uses GET. If you need to POST some JSON to the server you can use something like the following.

fetch('/url/api', {
  method: 'post',
  body: JSON.stringify({
    email: document.querySelector('#emailInput'),
    name: document.querySelector('#nameInput')
  })
}).then(function(response) {
  /* ... */
});

If you need to set response headers for authentication like many API's require you can do something like the following.

fetch('/url/api', {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Auth: 'authkey'
  }
}).then(function(response) {
  /* ... */
});

Fetch is in active development with features being added to it currently. You can start using it today in Chrome and use a polyfill for all other browsers with ie9+ support. To get a in depth understanding of the new Fetch API I suggest looking into the HTML5 Rocks article. Fetch will replace the XMLHttpRequest API and can't come soon enough.

Bluesky Facebook LinkedIn Email
 

Related Posts

JavaScript

Javascript JQuery Ajax

A short code example of how to make a Ajax call in JQuery with ES5 JavaScript.

Read Article
JavaScript

JavaScript ES6 let

Learn about how the ES6/ES2016 let variable statement works in JavaScript and TypeScript.

Read Article
JavaScript

JavaScript Prototypal Inheritance

A beginner tutorial on understanding JavaScript prototypal inheritance.

Read Article