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.
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