Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 69

Fetching and Processing JSON Data with `fetch()`

This lesson is built with resources from youtube.com, freecodecamp.org and 1 more site.

Hello! In our last lesson, we mastered handling errors in async/await functions with try...catch...finally. We saw that this structure is essential for building robust applications that don't crash when something unexpected happens, like a network request failing.

Today, we're going to put that knowledge to practical use by doing a deep dive into the function we've been using in all our examples: fetch(). Fetching data from external sources is a cornerstone of modern web development, especially in frameworks like Next.js where you'll build pages with data from various APIs.

Our goal for this lesson is to learn how to fetch data from a remote API using the fetch() function and process the JSON response. We'll cover what an API is, how fetch() works under the hood, and how to turn raw data from the internet into usable JavaScript objects.

What are APIs and JSON?

Before we write any code, let's clarify two key terms:

  • API (Application Programming Interface): Think of an API as a restaurant menu. It provides a list of dishes (data) you can order, along with a description of each. You (the client/your program) don't need to know how the kitchen (the server) prepares the food; you just need to know how to place an order from the menu. In web development, an API is a set of rules and URLs that allow our applications to request data from a server.
  • JSON (JavaScript Object Notation): This is the most common format for data sent back and forth by APIs. It's a lightweight, text-based format that is easy for humans to read and for machines to parse. Its syntax is nearly identical to JavaScript object literals, which makes it incredibly convenient to work with in JavaScript.

Why is fetch() Asynchronous? The Event Loop Revisited

When you request data from an API, it travels over the internet. This can take an unpredictable amount of time—from a few milliseconds to several seconds. If JavaScript waited for the response before doing anything else, your entire web page would freeze. This is called "blocking" behavior, and it's a terrible user experience.

To solve this, JavaScript handles network requests asynchronously. As we've discussed, it uses the Event Loop model.

JavaScript Event Loop Diagram with Fetch()
This diagram illustrates how JavaScript handles asynchronous operations. When you call `fetch()`, the request is handed off to the Web APIs environment in the browser. JavaScript's main thread (the Call Stack) remains unblocked and can continue running other code. Once the network request completes, its callback is placed in a queue, and the Event Loop moves it to the Call Stack for execution when the stack is empty.

This non-blocking model is what makes fetch() a Promise-based API. It immediately returns a Promise that acts as a placeholder for the future result.


The Two-Step Process of Fetching JSON Data

Fetching data with fetch() is a two-step asynchronous process. This is a critical concept that often trips up beginners. Let's break it down.

The following video provides an excellent walkthrough of this entire process, from making the initial request to handling the final data.

Fetch API & Rendering Data with JavaScript

The video 'Fetch API & Rendering Data with JavaScript' by Build Tavern clearly demonstrates the fundamental workflow of fetching and processing data.

Watch the video from the beginning until 08:06. Pay close attention to the two separate .then() calls. The first one handles the initial Response object, and the second one handles the data after it has been parsed from JSON.

As you saw in the video, the process looks like this:

  1. Step 1: Make the Request.
    You call fetch() with the URL of the API endpoint. This immediately returns a Promise that resolves to a Response object once the server has responded.

    fetch('https://api.example.com/data')
      .then(response => {
        // 'response' is the Response object. It's not the data yet!
        // We have to move to step 2.
      });
    

    The Response object contains metadata about the response, such as the status code (200 OK, 404 Not Found, etc.), headers, and other information. The actual data is in the response body, which is a ReadableStream.

  2. Step 2: Parse the Response Body.
    To get the actual data, you need to call a method on the Response object to parse its body. Since we're working with JSON, we use the .json() method. Crucially, response.json() is also an asynchronous operation and returns a new Promise! This is because it has to read the entire response stream to completion before it can parse it.

    fetch('https://api.example.com/data')
      .then(response => {
        // Step 1 is done. Now start Step 2.
        return response.json(); // This returns another Promise
      })
      .then(data => {
        // Step 2 is done. 'data' is now a usable JavaScript object!
        console.log(data);
      });
    

Handling Different Data Formats: .json() vs .text()

What response.json() does is a convenient shortcut. Under the hood, it fetches the response body as plain text and then runs JSON.parse() on it to convert the JSON string into a JavaScript object.

Sometimes an API might not return JSON. It might return plain text or HTML. For this, you can use the response.text() method. This next video exercise provides a brilliant practical comparison.

Exercises: Fetch API - Javascript In Depth

In 'Exercises: Fetch API' by Tech with Nader, you'll see a clear contrast between handling a text/HTML response and a JSON response. This will solidify your understanding of what response.json() is actually doing for you.

Watch from 01:15 to 20:01. First, observe how he fetches HTML from a website using response.text(). Then, see how he switches to response.json() to fetch from a JSON API and explains why trying to access properties on a text string fails, but works perfectly after parsing to an object.

To summarize the key insight from the video:

  • await response.text() gives you a string. You can't do data.title.
  • await response.json() gives you a JavaScript object. You can do data.title.

This is directly related to the JSON.parse() and JSON.stringify() methods built into JavaScript.

Working with JSON - Learn web development | MDN

The MDN article 'Working with JSON' provides a definitive explanation of these core methods. Understanding them clarifies what happens behind the scenes in a fetch call.

Read the section 'Converting between objects and text'. This will show you how JSON.parse() converts a JSON string to an object, and JSON.stringify() does the reverse.


A Complete, Robust Example with async/await

Now let's combine everything we've learned: fetch(), the two-step response processing, and the try...catch error handling from our previous lesson. Using async/await makes this flow much more readable.

A critical point for error handling is that fetch() only rejects its promise if there's a network error (e.g., you're offline). It does not reject for HTTP error statuses like 404 Not Found or 500 Internal Server Error. For those cases, the promise resolves successfully, but the response.ok property will be false. We must check this manually.

Here is the standard, robust pattern for fetching JSON data:

async function fetchUserData(username) {
  const url = `https://api.github.com/users/${username}`;

  try {
    // Step 1: Make the request
    const response = await fetch(url);

    // Manually check for HTTP errors
    if (!response.ok) {
      throw new Error(`HTTP Error! Status: ${response.status}`);
    }

    // Step 2: Parse the response body as JSON
    const data = await response.json();

    // Now we can use the data!
    console.log(`User Found: ${data.name}, from ${data.location}`);
    return data;

  } catch (error) {
    // This will catch both network errors and the error we threw
    console.error('Something went wrong:', error.message);
  }
}

// Test cases
fetchUserData('wesbos'); // Should succeed
fetchUserData('non-existent-user-xyz123'); // Should fail with a 404 error
Test your understanding!

You are tasked with fetching data about a specific Pokémon using the PokeAPI. The endpoint for "ditto" is https://pokeapi.co/api/v2/pokemon/ditto.

The JSON response is a large, nested object. Your goal is to extract the URL for the Pokémon's "front default" sprite. Looking at the API's response structure, you'd find it at data.sprites.front_default.

Write an async function getPokemonSprite(pokemonName) that:

  1. Takes a pokemonName as an argument.
  2. Fetches the data from the appropriate PokeAPI URL.
  3. Handles potential network errors and bad HTTP responses (!response.ok).
  4. Parses the JSON and returns just the front_default sprite URL string.
  5. If any error occurs, it should log the error and return null.
Show answer
async function getPokemonSprite(pokemonName) {
  const url = `https://pokeapi.co/api/v2/pokemon/${pokemonName}`;

  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`Could not find Pokémon: ${pokemonName}. Status: ${response.status}`);
    }

    const data = await response.json();
    
    // Navigate the nested object to get the sprite URL
    const spriteUrl = data.sprites.front_default;
    
    console.log(`Sprite URL for ${pokemonName}: ${spriteUrl}`);
    return spriteUrl;

  } catch (error) {
    console.error('Error fetching Pokémon data:', error.message);
    return null;
  }
}

// Example usage:
getPokemonSprite('pikachu');
getPokemonSprite('notapokemon');

This solution correctly implements the full try...catch flow, checks response.ok, and correctly navigates the nested JSON object to return the specific piece of data required.


Conclusion

You now have the complete toolkit for one of the most common and essential tasks in modern JavaScript: requesting data from an API. This skill is the bridge between your client-side application and the vast world of data and services available on the web.

Key Takeaways:

  • fetch() is the modern, Promise-based function for making network requests.
  • Fetching is a two-step async process: first get the Response object, then parse its body with a method like .json() or .text(), which also returns a Promise.
  • JSON is the standard data format for web APIs, and it maps almost perfectly to JavaScript objects.
  • You must always check for bad HTTP responses (like 404) with if (!response.ok) and throw an error manually, as fetch() won't do this for you.
  • Using async/await with try...catch is the cleanest and most robust way to structure your data-fetching code.

Next Up

This lesson concludes our module on Asynchronous JavaScript. You've journeyed from the event loop and callbacks to the power and elegance of Promises and async/await. These concepts are fundamental for building the interactive, data-driven applications that users expect today.

With this solid foundation in core JavaScript—including scopes, closures, objects, arrays, and asynchronous operations—you are now fully prepared to take the next big step: transitioning to TypeScript and the Next.js environment. In our upcoming lessons, we will see how these tools build upon the JavaScript you've learned to create powerful, type-safe, and performant web applications.