Show contents
Chapter 2 of 6 · 20 min
fetch and web APIs
By the end of this chapter, you'll be able to
- Send a GET or POST request with fetch and read a JSON response
- Tell a network error from an HTTP error response
- Cancel a request or give it a time limit with AbortController and AbortSignal.timeout
- Write an API access function that produces clear errors
One request, one response
A web API is a set of addresses (URLs) to which a program sends HTTP requests. The server answers with a status code (200: success, 201: created, 404: not found, 500: server error…) and a body, most often in JSON format. In a real page:
const response = await fetch("https://api.example.org/weather/dakar");
const weather = await response.json();
console.log(weather.temperature);
fetch returns a promise of a response; response.json() returns a second promise, that of the decoded body. This course's labs have no network access: each example therefore starts with a simulated server, a small fetch function that mimics the real one with an 80 ms delay. You can ignore it and read the rest as if you were talking to a real server.
// --- Simulated server: mimics fetch() so the example runs without a network ---
const data = { "/weather/dakar": { city: "Dakar", temperature: 29 }, "/weather/oslo": { city: "Oslo", temperature: -2 } };
const fetch = (url, options = {}) => new Promise((resolve, reject) => {
const path = new URL(url).pathname;
const status = options.method === "POST" ? 201 : path in data ? 200 : 404;
const body = options.method === "POST" ? { received: JSON.parse(options.body), id: 42 } : data[path] ?? { error: "not found" };
const timer = setTimeout(() => path === "/slow" || resolve({ ok: status < 300, status, json: async () => body }), 80);
options.signal?.addEventListener("abort", () => { clearTimeout(timer); reject(options.signal.reason); });
});
// --- End of simulated server ---
async function weather(city) {
const response = await fetch(`https://api.example.org/weather/${city}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${city}`);
}
return response.json();
}
const dakar = await weather("dakar");
console.log(`${dakar.city}: ${dakar.temperature} °C`);
try {
await weather("atlantis");
} catch (e) {
console.log("Error:", e.message);
}
Dakar: 29 °C
Error: HTTP 404 for atlantis
For an unknown city, fetch still succeeds: it's up to us to test response.ok and throw an error.
Text description of the animation
- fetch sends the request and returns a promise right away.
- The server answers. If the network were down, the promise would be rejected here: it's the only case in which fetch fails.
- The status signals success: the body can be read.
- json() decodes the JSON text into a JavaScript object.
- For an unknown city, fetch still succeeds: it's up to us to test response.ok and throw an error.
Sending data
To create a resource, you send a POST request with a JSON body. The Content-Type header tells the server how to read that body:
// --- Simulated server: mimics fetch() so the example runs without a network ---
const data = { "/weather/dakar": { city: "Dakar", temperature: 29 }, "/weather/oslo": { city: "Oslo", temperature: -2 } };
const fetch = (url, options = {}) => new Promise((resolve, reject) => {
const path = new URL(url).pathname;
const status = options.method === "POST" ? 201 : path in data ? 200 : 404;
const body = options.method === "POST" ? { received: JSON.parse(options.body), id: 42 } : data[path] ?? { error: "not found" };
const timer = setTimeout(() => path === "/slow" || resolve({ ok: status < 300, status, json: async () => body }), 80);
options.signal?.addEventListener("abort", () => { clearTimeout(timer); reject(options.signal.reason); });
});
// --- End of simulated server ---
const response = await fetch("https://api.example.org/reports", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ district: "Medina", problem: "street light out" }),
});
const created = await response.json();
console.log(response.status, created.id, created.received.problem);
201 42 street light out
JSON.stringify turns the object into JSON text; the server answers 201 ("created") with the new resource's identifier.
Cancelling and limiting the wait
A request can stay unanswered for minutes. AbortSignal.timeout(ms) creates a signal that cancels the request after the delay; an AbortController lets you cancel it yourself, for example when the user leaves the page or starts a new search:
// --- Simulated server: mimics fetch() so the example runs without a network ---
const data = { "/weather/dakar": { city: "Dakar", temperature: 29 }, "/weather/oslo": { city: "Oslo", temperature: -2 } };
const fetch = (url, options = {}) => new Promise((resolve, reject) => {
const path = new URL(url).pathname;
const status = options.method === "POST" ? 201 : path in data ? 200 : 404;
const body = options.method === "POST" ? { received: JSON.parse(options.body), id: 42 } : data[path] ?? { error: "not found" };
const timer = setTimeout(() => path === "/slow" || resolve({ ok: status < 300, status, json: async () => body }), 80);
options.signal?.addEventListener("abort", () => { clearTimeout(timer); reject(options.signal.reason); });
});
// --- End of simulated server ---
try {
await fetch("https://api.example.org/slow", { signal: AbortSignal.timeout(150) });
} catch (e) {
console.log(e.name, "→ the server didn't answer in time");
}
const controller = new AbortController();
const request = fetch("https://api.example.org/weather/oslo", { signal: controller.signal });
controller.abort();
try {
await request;
} catch (e) {
console.log(e.name, "→ request cancelled by the user");
}
TimeoutError → the server didn't answer in time
AbortError → request cancelled by the user
A cancelled request rejects its promise with an error named AbortError, or TimeoutError for an expired delay: that's how you tell the cases apart.
Your turn
Mini-lab: the weather in several citiesJavaScript
Output
Click “Run” to execute your code.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: a robust access function
Write loadJson(url, { timeoutMs }), which returns a request's JSON body and throws an error with a clear message in three cases: no answer within the time limit, network unavailable, HTTP error status. Test it on a known city, an unknown city and an address that never answers.
Hint 1
fetch in a try/catch: an error at that point is a network or timeout problem. e.name === "TimeoutError" identifies the timeout.Hint 2
try, test response.ok and throw an error with the status.Show the solution and common mistakes
// --- Simulated server: mimics fetch() so the example runs without a network ---
const data = { "/weather/dakar": { city: "Dakar", temperature: 29 }, "/weather/oslo": { city: "Oslo", temperature: -2 } };
const fetch = (url, options = {}) => new Promise((resolve, reject) => {
const path = new URL(url).pathname;
const status = options.method === "POST" ? 201 : path in data ? 200 : 404;
const body = options.method === "POST" ? { received: JSON.parse(options.body), id: 42 } : data[path] ?? { error: "not found" };
const timer = setTimeout(() => path === "/slow" || resolve({ ok: status < 300, status, json: async () => body }), 80);
options.signal?.addEventListener("abort", () => { clearTimeout(timer); reject(options.signal.reason); });
});
// --- End of simulated server ---
async function loadJson(url, { timeoutMs = 5000 } = {}) {
let response;
try {
response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
} catch (e) {
if (e.name === "TimeoutError") throw new Error(`no answer after ${timeoutMs} ms: ${url}`);
throw new Error(`network unavailable: ${url}`);
}
if (!response.ok) throw new Error(`HTTP ${response.status}: ${url}`);
return response.json();
}
for (const path of ["/weather/oslo", "/weather/atlantis", "/slow"]) {
try {
const body = await loadJson(`https://api.example.org${path}`, { timeoutMs: 200 });
console.log("ok:", body.city);
} catch (e) {
console.log("failed:", e.message);
}
}
ok: Oslo
failed: HTTP 404: https://api.example.org/weather/atlantis
failed: no answer after 200 ms: https://api.example.org/slow
The rest of the application never calls fetch directly again: it calls loadJson, and has only one kind of error to handle, with a message that explains what happened.
Common mistakes:
- Putting
response.json()in the sametryasfetchand reporting "network unavailable" for everything: a 404 or invalid JSON would be misdiagnosed. - Forgetting
awaitbeforeresponse.json(): you get a promise instead of the data, andbody.cityisundefined.
Summary
- 1fetch(url) returns a promise of a response; response.json() a promise of the decoded body.
- 2fetch only fails on a network error: always test response.ok before reading the body.
- 3A POST request sends a JSON.stringify body with the Content-Type: application/json header.
- 4AbortSignal.timeout limits the wait; AbortController cancels a request on demand.
- 5Group API access in a function that produces clear errors.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.