JavaScript · Intermediate level

Intermediate level · Module 3: Fetch, APIs and JSON in the Browser · Lesson 1 of 3

Getting Data with fetch

Request JSON from an API with fetch, check the response and display the data.

In this lesson you will

  • Use fetch with async/await to get JSON
  • Check response.ok and status codes before using data

Key concepts

fetchResponse objectresponse.ok and statusresponse.json()

The lesson

fetch(url) sends an HTTP request and returns a promise for a Response. The response arrives in two steps: first the status and headers, then the body, which you read with await response.json().

fetch only rejects for network failures. A 404 or 500 response still resolves, so check response.ok (true for status 200–299) and throw an error yourself when it is false.

Inspect requests in the DevTools Network tab: the URL, status, headers, timing and the response body. It is the quickest way to see whether a problem is in your code or in the API.

Step by step

  1. Fetch JSON from a practice API and log it.
  2. Check response.ok and throw for errors.
  3. Request a URL that returns 404 and handle it.
  4. Inspect both requests in the Network tab.

Practice activity

Write a getJSON(url) helper that returns parsed JSON or throws an error naming the status code, and use it to display a list from an API.

Expected result: The list displays for a valid URL and a clear error appears for a 404.

Check your understanding

  1. Does fetch reject for a 404 response?

    Show answer

    No; it resolves, so you must check response.ok.

  2. How do you read a JSON body from a response?

    Show answer

    await response.json().

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.