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.

About the author

Hey, I'm Tania, a software engineer, writer, and open-sourcerer. I publish articles and tutorials about modern JavaScript, design, and programming.

Get the newsletterBuy me a coffee