Skip to the workspace
Pebellslearn by building
Working with APIs  ›  Lesson

The Fetch API

Working with APIs 15 min

javascript / The Fetch API

Explore each scene at your own pace.

01 · The Fetch API

The Fetch API

The Fetch API

fetch requests a resource and returns a promise for a Response. HTTP error statuses generally fulfill that promise; code must check response.ok and handle body parsing separately.

A completed HTTP exchange is not the same as a successful application result.

See the mechanism

Walk through the modelThe Fetch APIAuthored snapshots of the example; use Run below to test the code.
interface stateloading
Start the request and show a meaningful pending state.
1 of 3

Follow one example

html

This deterministic data URL supplies a local JSON fixture, not a live API or a demonstration of server latency. A real HTTP endpoint can return 404 or 500 while fetch itself fulfills. Network failure or cancellation can reject. response.json also returns a promise and can fail on invalid JSON. Add an AbortController signal to cancel obsolete requests; ignore stale results rather than letting an older search overwrite a newer one.

Predict, change and check

Predict: If a server answers 404, should success be decided by whether await fetch threw?

Test your explanation: Change the fixture to a JSON object instead of an array to exercise the shape error. Mini-project: retain loading, success, empty and error states; add a retry button and explain how you would prevent stale search results.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

A fulfilled fetch is only one boundary passed

fetch generally fulfills with a Response even for an HTTP failure status. Check ok or the required status policy before treating data as successful. Parsing JSON is asynchronous and can fail independently, and a parsed value can still have the wrong schema.

Represent loading, empty, error and success as separate interface states. Pass an AbortSignal when obsolete work can be cancelled and also guard against stale results when necessary. A data URL makes a reproducible local example, but it is not evidence that a real server's latency, credentials, status policy or CORS configuration has been tested.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.