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.


