Fetch API (Browser)

Send requests, set headers, handle JSON, and manage errors.

On this page

Fetch is the modern browser client

The Fetch API is the standard way to call APIs from the browser. It is Promise-based and requires explicit error handling because fetch only rejects on network errors.

Basic GET

const res = await fetch("/api/users/42", {
  headers: { "Accept": "application/json" }
});

if (!res.ok) throw new Error("Request failed: " + res.status);

const data = await res.json();

POST JSON

const res = await fetch("/api/orders", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json"
  },
  body: JSON.stringify({ productId: 123, quantity: 2 })
});

const body = await res.json().catch(() => null);

if (!res.ok) {
  throw new Error(body?.detail || body?.title || "Request failed");
}

Bearer token

const res = await fetch("/api/me", {
  headers: {
    "Accept": "application/json",
    "Authorization": "Bearer " + accessToken
  }
});

Timeout with AbortController

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);

try {
  const res = await fetch("/api/users", { signal: controller.signal });
  clearTimeout(timer);
} catch (e) {
  clearTimeout(timer);
  throw e;
}

Common mistakes

  • Assuming fetch throws for 400/500 responses (it doesn't)
  • Forgetting Content-Type when sending JSON
  • Not handling JSON parse failures on error responses

Checklist

  • Check res.ok for HTTP errors.
  • Parse JSON safely (catch parse errors).
  • Use AbortController for timeouts.