Skip to content

Lesson 29 of 50Async JavaScript

Working with APIs

Talk to REST APIs from the browser like a professional: methods, status codes, query strings, auth, CORS, UI states, pagination, caching and a typed client.

19 min read0/4 questions

Almost every app you build will spend its life talking to someone else's server: a weather service, a payment provider, your own backend. The previous lesson showed how fetch works. This one is about the conversation itself: what the server expects you to send, what its answers mean, and how to turn those answers into a page that behaves well when the network is slow, the list is empty or the server is down. You will finish with a small typed API client you can reuse in any project.

REST from the client's side

An API (application programming interface) is a set of URLs a program can call. A REST API organises those URLs around resources, the nouns of the app: /users, /users/42, /users/42/orders. You say what you want to do with a resource using an HTTP method, the verb:

MethodMeaningExampleSafe to repeat?
GETReadGET /recipes?tag=veganYes
POSTCreate (or trigger an action)POST /recipes with a JSON bodyNo
PUTReplace a whole resourcePUT /recipes/7Yes
PATCHChange some fieldsPATCH /recipes/7 with { "title": "..." }Usually
DELETERemoveDELETE /recipes/7Yes

"Safe to repeat" is the technical idea of idempotency: sending the request twice leaves the server in the same state as sending it once. It matters because it tells you what you may retry automatically. Retrying a GET is harmless; retrying a POST /payments might charge someone twice.

The server answers with a status code, a three-digit number grouped by its first digit: 2xx success, 3xx redirect, 4xx you made a mistake, 5xx the server made a mistake.

CodeNameWhat your UI should do
200OKShow the data
201CreatedShow the new item (often returned in the body)
204No ContentSuccess with no body: do not call res.json()
400 / 422Bad Request / UnprocessableShow validation messages next to the fields
401UnauthorizedNot logged in (or the token expired): send to sign-in
403ForbiddenLogged in but not allowed: explain, do not retry
404Not FoundShow a "not found" state
409ConflictSomeone else changed it: reload and try again
429Too Many RequestsSlow down; respect the Retry-After header
500 / 503Server Error / UnavailableShow an error with a retry button
Match the pairs0/4 matched

Match each response to what the client should do.

Choose an item, then its match on the other side.

Headers and JSON

Headers are key-value lines that travel with every request and response, describing the message rather than carrying it. The three you will set most:

  • Content-Type: application/json tells the server your body is JSON.
  • Accept: application/json asks for JSON back.
  • Authorization: Bearer <token> proves who you are (more below).

Bodies are almost always JSON: send with JSON.stringify(data), read with await res.json().

Query strings with URLSearchParams

Filters, search terms and page numbers usually go in the query string, the part of the URL after ?. Building it by gluing strings together breaks the moment a value contains a space, & or #. URLSearchParams does the encoding for you:

JavaScript
const params = new URLSearchParams({ q: "mac & cheese", tag: "vegan", page: "2" });params.append("tag", "quick"); // a key can appear more than onceconsole.log(params.toString()); const url = new URL("https://api.example.com/recipes");url.search = params;console.log(url.href); // Reading works the other way roundconst incoming = new URLSearchParams("?q=soup&page=3");console.log(incoming.get("q"), Number(incoming.get("page")), incoming.has("tag"));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

What does this print?

const p = new URLSearchParams({ q: "fish & chips" });
console.log(p.toString());
Need a nudge? Hints walk you through it.

Auth headers and secrets

Most APIs need to know who is calling. After a user signs in, the server typically gives your app a token, a long random-looking string, and you send it on each request as a Bearer token:

const res = await fetch("/api/me", {
  headers: { Authorization: `Bearer ${accessToken}` },
});

"Bearer" means "whoever holds this is allowed in", so treat tokens like keys. That leads to the most important rule in this lesson: anything in frontend code is public. Every line of JavaScript you ship, every environment variable baked into the bundle (in Next.js, anything prefixed NEXT_PUBLIC_; in Vite, VITE_), can be read by anyone who opens DevTools. A user's own token is fine to hold in the browser because it only unlocks their data. Your company's secret keys (a payment provider's secret key, an AI API key, a database password) are not. Put them on a server, and have the browser call your server, which adds the key and forwards the request.

Quick check
You want your React app to call a paid AI API. Where does the API key go?
Need a nudge? A hint rules out a wrong answer.

CORS from the browser's point of view

Sooner or later you will see this in the console: "has been blocked by CORS policy". Here is what is happening. By default the browser's same-origin policy stops a page from reading responses from a different origin (the scheme, host and port: https://shop.com and https://api.shop.com are different origins). CORS (Cross-Origin Resource Sharing) is how a server opts in: it replies with an Access-Control-Allow-Origin header naming the origins it trusts.

For "non-simple" requests (a JSON body, an Authorization header, methods like PUT or DELETE), the browser first sends a preflight: an automatic OPTIONS request asking permission.

A cross-origin request with a preflight
Your pageBrowserAPI serverfetch PUT /recipes/7OPTIONS /recipes/7Allow-Origin: app...PUT /recipes/7200 + CORS headersResponse

Your page lives on https://app.example.com; the API is on https://api.example.com.

1/6

Three facts clear up most confusion. CORS is enforced by the browser, so the same request from curl or a server works fine. You fix it on the server (or by calling through your own backend), never with a frontend setting; mode: "no-cors" just gives you an empty response you cannot read. And CORS is not an auth system: it protects users' browsers, not your API.

Quick check
Your request works in Postman but fails in the browser with a CORS error. What is the right fix?
Need a nudge? A hint rules out a wrong answer.

Loading, error and empty states

Every screen backed by an API is in one of four states, and users notice when you forget one:

  1. Loading: show a spinner or skeleton, and disable the button that started it.
  2. Error: say what went wrong in plain words and offer a retry.
  3. Empty: success, but zero results. "No recipes match 'kale'" beats a blank page.
  4. Success: the data.

The little app below uses a fake fetch (the preview has no network) that returns real Response objects after a delay. Use the buttons to force each state:

HTML & CSS
<style> body { font-family: system-ui, sans-serif; padding: 16px; } .controls { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 12px; } button { padding: 6px 12px; font-size: 14px; } ul { padding-left: 20px; } .error { color: #b00020; } .muted { color: #555; }</style><div class="controls"> <button data-mode="ok">Load recipes</button> <button data-mode="empty">Load (empty)</button> <button data-mode="fail">Load (server error)</button></div><div id="view" aria-live="polite" class="muted">Pick a button to load recipes.</div><script> const RECIPES = [ { id: 1, title: "Tomato soup", minutes: 25 }, { id: 2, title: "Lemon pasta", minutes: 15 }, { id: 3, title: "Bean chilli", minutes: 40 }, ]; function fakeFetch(url) { const mode = new URL(url, "https://example.test").searchParams.get("mode"); return new Promise((resolve) => { setTimeout(() => { if (mode === "fail") resolve(new Response("{}", { status: 503 })); else resolve(Response.json(mode === "empty" ? [] : RECIPES)); }, 800); }); } const view = document.getElementById("view"); let lastMode = "ok"; async function load(mode) { lastMode = mode; view.className = "muted"; view.textContent = "Loading recipes..."; try { const res = await fakeFetch("/api/recipes?mode=" + mode); if (!res.ok) throw new Error("The server answered " + res.status); const recipes = await res.json(); if (recipes.length === 0) { view.textContent = "No recipes yet. Add your first one."; return; } view.className = ""; const list = document.createElement("ul"); for (const r of recipes) { const li = document.createElement("li"); li.textContent = r.title + " (" + r.minutes + " min)"; list.append(li); } view.replaceChildren(list); } catch (err) { view.className = "error"; view.textContent = "Could not load recipes. " + err.message + ". "; const retry = document.createElement("button"); retry.textContent = "Try again"; retry.addEventListener("click", () => load(lastMode === "fail" ? "ok" : lastMode)); view.append(retry); } } document.querySelectorAll("[data-mode]").forEach((btn) => { btn.addEventListener("click", () => load(btn.dataset.mode)); });</script>

Preview

Notice aria-live="polite": screen readers announce the text when it changes, so a blind user also hears "Loading" and then the result. Try changing the delay to 3000 and imagine waiting without the loading message.

Pagination

APIs rarely return 10,000 rows at once. They split results into pages. You will meet two styles:

  • Offset (page number): ?page=3&limit=20. Easy, and lets users jump to page 7, but items can be skipped or repeated if rows are added while someone pages.
  • Cursor: the response includes nextCursor, an opaque marker you send back as ?cursor=... to get the next page. Stable under inserts and fast on huge tables; used by most large APIs. You cannot jump to page 7, which suits infinite scroll.
JavaScript
const ALL = Array.from({ length: 7 }, (_, i) => `recipe ${i + 1}`); async function fakeApi(url) { const params = new URL(url, "https://api.example.com").searchParams; const start = Number(params.get("cursor") ?? 0); const limit = Number(params.get("limit")); const items = ALL.slice(start, start + limit); const next = start + limit < ALL.length ? String(start + limit) : null; return Response.json({ items, nextCursor: next });} async function fetchAll(limit) { const results = []; let cursor = null; do { const params = new URLSearchParams({ limit: String(limit) }); if (cursor) params.set("cursor", cursor); const res = await fakeApi(`/recipes?${params}`); const page = await res.json(); console.log(`got ${page.items.length}, next cursor: ${page.nextCursor}`); results.push(...page.items); cursor = page.nextCursor; } while (cursor); return results;} console.log((await fetchAll(3)).length, "recipes in total");
Output
Press Run (⌘ Enter) to see what happens.

In a real UI you would load one page at a time (a "Load more" button or infinite scroll) rather than everything at once.

Caching responses in memory

If three components ask for the same user within a second, sending three identical requests is waste. A small in-memory cache keyed by URL fixes it. The trick is to cache the promise, not the data: a second caller during the first request gets the same in-flight promise, so duplicates are merged. Add a time to live (TTL) so data does not go stale forever, and drop failures so a retry can try again:

JavaScript
let requests = 0;async function fakeFetchJson(url) { requests++; await new Promise((r) => setTimeout(r, 20)); return { url, loadedAt: requests };} const cache = new Map(); function cachedGet(url, ttlMs = 60_000) { const hit = cache.get(url); if (hit && Date.now() - hit.time < ttlMs) return hit.promise; const promise = fakeFetchJson(url).catch((err) => { cache.delete(url); // do not cache failures throw err; }); cache.set(url, { promise, time: Date.now() }); return promise;} const [a, b] = await Promise.all([cachedGet("/users/1"), cachedGet("/users/1")]);const c = await cachedGet("/users/1");await cachedGet("/users/2");console.log("requests sent:", requests);console.log(a === b && b === c);
Output
Press Run (⌘ Enter) to see what happens.

Four calls, two requests. Real apps usually reach for a library (TanStack Query, SWR, RTK Query) that adds invalidation after writes, background refresh and the stale-request handling from the previous lesson, but they are built on this same idea.

A typed API client in TypeScript

This section uses TypeScript, which has its own unit at the end of the course. If you have not reached it yet, skip ahead to the terms and come back later.

TypeScript lets you describe the shape you expect. But res.json() returns any at runtime: the server can send anything, and a type annotation does not check it. A good client does both: a type for your editor and a runtime check for reality.

api.ts
export type Recipe = { id: number; title: string; minutes: number };
 
export class ApiError extends Error {
  constructor(public status: number, message: string) {
    super(message);
  }
}
 
function isRecipe(value: unknown): value is Recipe {
  if (typeof value !== "object" || value === null) return false;
  const v = value as Record<string, unknown>;
  return typeof v.id === "number" && typeof v.title === "string" && typeof v.minutes === "number";
}
 
type RequestOptions = Omit<RequestInit, "headers"> & { headers?: Record<string, string> };
 
async function request(path: string, init: RequestOptions = {}): Promise<unknown> {
  const res = await fetch(`/api${path}`, {
    ...init,
    headers: { Accept: "application/json", ...init.headers },
    signal: init.signal ?? AbortSignal.timeout(8000),
  });
  if (!res.ok) throw new ApiError(res.status, `${init.method ?? "GET"} ${path} failed`);
  return res.status === 204 ? null : res.json();
}
 
export async function listRecipes(query: { tag?: string; page?: number } = {}): Promise<Recipe[]> {
  const params = new URLSearchParams();
  if (query.tag) params.set("tag", query.tag);
  if (query.page) params.set("page", String(query.page));
  const data = await request(`/recipes?${params}`);
  if (!Array.isArray(data) || !data.every(isRecipe)) {
    throw new Error("Unexpected response shape from /recipes");
  }
  return data; // now truly Recipe[]
}

The value is Recipe return type is a type guard (from the narrowing lessons): after data.every(isRecipe) passes, TypeScript knows data is Recipe[], and so do you. Throwing an ApiError with the status lets the UI choose the right state (401 to sign-in, 404 to "not found"). On bigger projects, a schema library such as Zod writes the type and the check from one definition; check its docs for the current API.

Key terms
REST
A style of API built around resources at URLs, acted on with HTTP methods like GET, POST and DELETE.
idempotent
Safe to repeat: sending the request twice leaves the server as sending it once would.
Bearer token
A credential sent as Authorization: Bearer <token>; whoever holds it gets access.
CORS
Browser rule that lets a server allow other origins to read its responses, via Access-Control headers.
preflight
The automatic OPTIONS request a browser sends to ask permission before some cross-origin requests.
cursor pagination
Paging with an opaque marker from the previous response instead of a page number.
type guard
A function returning value is T that checks a value at runtime and narrows its type.