Fetch and APIs
Talk to the network — requests, responses, JSON, and handling failure.
- Make a request with fetch and read a JSON response
- Check response status and handle network errors
- Send data with a POST request
fetch is the built-in way to make network requests from JavaScript. It returns a
promise, so everything from the async and promises lessons applies directly. This
ties the runtime track together: closures, promises, error handling, and APIs all
meeting in everyday code. (These examples talk to the network, so they're shown as
code rather than run in the sandbox.)
A basic GET
fetch resolves to a Response; you call .json() (itself async) to parse the
body:
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}Always check status
A crucial gotcha: fetch only rejects on a network failure (offline, DNS). An
HTTP error like 404 or 500 still resolves — you have to check response.ok
yourself:
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}Forgetting this is one of the most common fetch bugs — you parse an error page
as if it were data.
Handling failure
Wrap calls in try/catch to handle both network errors and the status errors you
threw — this is the APIs-and-protocols fundamentals lesson in practice (the
network is unreliable; design for it):
try {
const user = await getUser(1);
} catch (err) {
console.error("could not load user:", err.message);
}Sending data: POST
To send data, pass an options object with a method, headers, and a JSON body:
await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
});Real apps also handle retries, timeouts, and idempotency for requests that
change data — the reliability concerns from the APIs & protocols lesson. fetch
is the primitive; robust API code wraps it with those safeguards.
Where to go next
That completes The runtime, and the current JavaScript/TS track. Revisit the Fundamentals — concurrency, APIs, testing — and notice how much of this syntax is those ideas wearing JavaScript's clothes.