JavaScript lesson · 26 min
JavaScript fetch and JSON
Understand the shape of fetch code, async JSON parsing, and error checks without making a real network request.
What you will practice
- Understand what fetch normally returns.
- Use await with a response-like object.
- Check ok before trusting JSON data.
What this means
`fetch` is the browser API normally used to request data from a server.
A real fetch call returns a Promise for a Response object. You usually check `response.ok`, then call `response.json()` to parse the response body.
This lesson uses a safe fake request because Lumio lesson code runs locally and does not make network calls from the runner.
If this is your first time seeing this
fetch is how browser code usually asks a server for data.
A response can fail, so good code checks the response before using the data.
Mini glossary
- fetch
- A browser API for making HTTP requests.
- Response
- The object returned by a fetch request, with status and body-reading methods.
- json
- A method that parses a JSON response body into JavaScript data.
Example from everyday life
A fetch request is like asking a service desk for a file. First you ask for it, then you check whether the desk actually found it, and only then you open the file and read the contents.
How it works step by step
- `fakeFetch` returns an object that behaves like the important parts of a real Response.
- `await fakeFetch(...)` waits until the request-like operation is ready.
- `if (!response.ok)` protects the code from treating an error as good data.
- `await response.json()` reads the JSON payload and turns it into a JavaScript object.
Where you will use this
- A dashboard loads user statistics from `/api/stats`.
- A search page requests filtered results from a backend.
- A settings page loads saved preferences before rendering the form.
Before you run the code
Real production code would use `await fetch('/api/profile')`. The safe lesson runner blocks network APIs, so the example keeps the same control flow with fake data.
Always think about unhappy paths: server errors, invalid JSON, slow requests, and missing fields.
Common beginner mistakes
- Forgetting `await` and trying to use a Promise like real data.
- Skipping the `response.ok` check.
- Assuming server data always has the exact fields you expect.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Change `ok` to `false` and watch the error path.
- Add another field to the fake JSON response.
- Rename `completedLessons` and see why field names matter.