Fetch API in Vanilla JavaScript

β€” 3 minute read

permalink

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 permalink

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 permalink

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 permalink

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! permalink

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