Lesson 7 · Web development foundations
Working with data: JSON and fetch
Load, handle and display data from an API with async and await.
About 35 minutes
Tab indents. Press Escape, then Tab, to leave the editor.
Almost no real app keeps all its data in the page. A weather app asks a weather service, a shop asks its product database, a banking app asks the bank. The page sends a request to an API (Application Programming Interface: a set of URLs a program can call), gets data back, usually as JSON, and turns it into something people can read. Doing that well means dealing with time, because responses take a while, and with failure, because networks and servers fail. This lesson covers both, with a pretend API that runs right here in the page, so it works with no connection.
JSON: data as text
JSON (JavaScript Object Notation) is the standard format for sending structured data between programs. It looks like JavaScript objects and arrays, with stricter rules:
{
"city": "Oslo",
"tempC": 4,
"windy": false,
"alerts": [],
"updated": "2026-11-25T09:00:00Z"
}
- Keys must be in double quotes, and so must strings.
- Values can be strings, numbers,
true,false,null, objects and arrays, nothing else. There are no dates (send them as strings, usually in the ISO 8601 format shown), no functions and noundefined. - No comments and no trailing commas.
JSON travels as text. JavaScript converts in both directions with two built-in functions:
const data = JSON.parse('{"city":"Oslo","tempC":4}') // text to object
data.tempC // 4
const text = JSON.stringify({ city: 'Lima', tempC: 19 }) // object to text
// '{"city":"Lima","tempC":19}'
JSON.parse throws an error if the text isn't valid JSON, which is worth remembering when the text comes from outside your code.
Challenge
Read a JSON payload
The depot's inventory arrived as JSON text.
- Turn it into an object with
JSON.parseand store it in aconstcalleddata. - Log the depot's name.
- Log the total number of litres across the whole kit.
- Nothing logged yet.
- You parsed the JSON into an object called data
- The console shows the depot name
- The console shows the total, 19 litres
Waiting without freezing: Promises
A request might take 50 milliseconds or 10 seconds. JavaScript in the browser runs on a single main thread that also handles clicks and drawing, so it can't just stop and wait; the page would freeze. Instead, slow operations return a Promise: an object standing for a value that will arrive later. A Promise is pending at first, then either fulfilled with a value or rejected with an error.
The modern way to use a Promise is await, inside a function marked async:
async function load() {
const response = await fetch('/api/weather?city=Oslo')
const data = await response.json()
console.log(data.tempC)
}
await pauses this function until the Promise settles, while the rest of the page keeps running. An async function always returns a Promise itself. The step-through below shows what happens to the order of your code, including why code after an await runs later than code that comes after the function call.
Lab
Event loop visualizer
Predict the console output, then step through to see why it comes out in that order.
1console.log('A')2setTimeout(() => {3 console.log('B')4}, 0)5console.log('C')
- run script
The whole script runs as one task. The event loop takes it from the task queue and starts it.
fetch, and the two ways it fails
fetch(url) is the browser's built-in function for HTTP requests. It returns a Promise for a Response object, which has the status code and headers; you read the body with another awaited call such as response.json().
The detail that catches people out: fetch only rejects when there's no response at all, such as when the device is offline or the server can't be reached. A 404 or 500 is still a response, so the Promise fulfills and you must check for yourself:
const response = await fetch(url)
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`)
}
const data = await response.json()
response.ok is true for status codes from 200 to 299. Wrap the whole thing in try/catch and both kinds of failure end up in one place:
try {
// fetch, check ok, parse
} catch (error) {
// show a message
}
Sending data
Reading is half the job. To create or update something, you send JSON in the request body. Most web APIs follow REST conventions, where URLs name resources and the HTTP method says what to do with them: GET /api/items lists items, GET /api/items/42 reads one, POST /api/items creates one, PATCH /api/items/42 updates it and DELETE /api/items/42 removes it.
const response = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Water', qty: 12 }),
})
The Content-Type header tells the server the body is JSON; without it many servers won't parse it. The same response.ok check applies, and a successful create often comes back as 201 Created with the new item, including the id the server gave it, in the body.
When you join a team, the API is usually described in documentation such as an OpenAPI specification, which lists every endpoint, its parameters and the shape of its responses. Reading API docs and trying requests by hand, in the browser's Network panel or a tool like curl, is a routine part of front-end work.
Loading, error and empty states
Real interfaces show more than the happy path. Designers and front-end developers plan at least these states for anything that loads data:
- Loading: something is happening. Show it immediately so people don't click again.
- Success: the data, presented.
- Error: what went wrong in plain words, and what to do, such as "Check your connection and try again".
- Empty: the request worked but there's nothing to show, like a search with no results.
A message that says only "Error" or, worse, a spinner that never stops, makes people think the app is broken. Distinguishing "you're offline" from "that doesn't exist" lets them fix the problem. For screen reader users, put status messages in an element with role="status", which announces changes without moving focus.
Build a weather lookup
The starter code includes fetchWeather(city), a stand-in for a real API call. It behaves like fetch: it waits half a second, then fulfills with a response object that has ok, status and a json() method, or rejects if you tick Simulate no connection. In a real app it would be one line, fetch('/api/weather?city=' + encodeURIComponent(city)).
Challenge
Weather with loading and error states
Write showWeather(city) so the form works:
- Show a loading message (such as "Loading…") in
statusEland clearresult. await fetchWeather(city). Ifresponse.okis false, throw an error; otherwiseawait response.json().- Show the city, temperature and conditions in
result, and clearstatusEl. - If anything fails, show a helpful message in
statusEl: one for an unknown city, and ideally a different one when there's no connection.
Press Run, then try Oslo, an unknown city, and the offline checkbox.
- Nothing logged yet.
- A loading message shows while the request is in flight
- The result shows the city, temperature and conditions
- The loading message is cleared once the data arrives
- An unknown city shows an error message, not a stuck spinner
- With no connection, a message explains what happened
Recap
- JSON is text with strict rules (double quotes, no comments, no trailing commas);
JSON.parseandJSON.stringifyconvert it. - Slow operations return Promises;
awaitinside anasyncfunction waits for one without freezing the page. fetchrejects only when there's no response; checkresponse.okfor HTTP errors like 404 and 500.- Use
try/catchto handle both kinds of failure in one place. - Every data-driven view needs loading, success, error and empty states, with messages that tell people what to do.
Finished this lesson?
Mark it complete to track your progress on this device.