How to Use the JavaScript Fetch API to Get JSON Data

In How to Use JSON Data with PHP or JavaScript, I discussed how to use XMLHttpRequest() to get data from a JSON feed.

The Fetch API is a newer built-in feature of JavaScript that makes working with requests and responses easier.

// Replace ./data.json with your JSON feed
  .then(response => {
    return response.json()
  .then(data => {
    // Work with JSON data here
  .catch(err => {
    // Do something for an error here

Note that with Fetch, even a 404 or 500 error will not return an error. Only a network error or a request not completing will throw an error.

Leave a comment

Plain text only. Comment must be over 20 characters.

Join the newsletter

I write about JavaScript, programming, and front-end design. Join other developers in keeping up with my content. Unsubscribe whenever. Never any spam, ads, or affiliate links.