Skip to content
Parwaz DigitalMarketing · Web · Courses

Web Development Course · Module 3, lesson 5

Fetching data from an API with async and await

Load data from a web API with fetch, handle it with async and await, show it on the page and deal with errors and loading states.

What you will learn

  • Request data from an API using fetch
  • Write asynchronous code with async functions and await
  • Handle loading states and errors so the page never breaks silently

An API lets one program request data from another. Many web APIs return JSON over HTTP. The fetch() function sends a request from the browser and returns a promise, an object representing a value that will arrive later. Network requests take time, so JavaScript does not stop and wait. Instead, your code says what to do once the response arrives.

The clearest way to write this is with async and await. Inside an async function, const response = await fetch(url) pauses that function until the response arrives, while the rest of the page carries on. Then const data = await response.json() reads the body as JSON. From there, you can use map to turn the data into elements and add them to the page.

Requests can fail. fetch only rejects on network errors, so also check response.ok, which is false for status codes such as 404 or 500. Wrap the code in try and catch to handle problems and show a helpful message instead of a blank space. Showing a short loading message while the request runs tells visitors that something is happening.

Practice task

Save your product array as a products.json file next to your page, then use fetch with async and await to load it and display each product, with a loading message and an error message.

Web Development Course

Learn this properly,with a final project.

These pages summarise each lesson. The full course teaches them hands-on. Message us for the current fee, schedule, and format.

Available for new projects — Replies within one business day