Subscribe

Fetch API in Vanilla JavaScript

โœ๏ธ

Fetch is a better alternative to xhr and $.ajax. Learn in this tutorial how to use it and take code from the examples.

1 Apr, 2020 ยท 2 min read

I remember back in the days of jQuery $.ajax was a big, big thing. But nowadays we have fetch a way cooler, faster solution to fetch data from an API endpoint. It is the better alternative to XHR and AJAX. The best part: the Fetch API request works in Vanilla JavaScript!

How to make a GET request with the Fetch API

fetch('https://api.fungenerators.com/fact/random');

That is as basic as it gets, won't do much since we are not returning any data.

Returning json data with the Fetch API

fetch('https://ghibliapi.herokuapp.com/films')
  .then(function (response) {
    // Successfull fetch return as json
    return response.json();
  })
  .then(function (data) {
    // Data now contains the json
    console.log(data[0]);
  })
  .catch(function (error) {
    // A Error occured
    console.log(error);
  });

Vanilla JS Fetch works with promises, so we can return a promise chain as we learned on 20-03-2020: Promise chains in JavaScript.

The first API response will return an object, not an actual response, so we need to tell the promise that we want to return the response as JSON data.

You can play around with this codepen.

See the Pen Fetch API in Vanilla JavaScript by Chris Bongers (@rebelchris) on CodePen.

Browser support for Vanilla JS API requests

The Fetch API has excellent support, but not in IE. ๐Ÿ˜“

You can use a polyfill for this.

graph of browser support for Fetch API

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1829 devs and subscribe to my newsletter