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. It 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) {
    // Successful fetch return as json
    return response.json();
  })
  .then(function (data) {
    // Data now contains the json
    console.log(data[0]);
  })
  .catch(function (error) {
    // A Error occurred
    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 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter