JavaScript Tutorial · Asynchronous JavaScript · Lesson 34 of 44

JavaScript Fetch API

Request data from APIs with fetch, check status codes and send JSON.

Getting data

fetch(url) makes an HTTP request and returns a promise for a Response. Call response.json() (also a promise) to read a JSON body:

const response = await fetch("https://api.example.com/users/1");
if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
console.log(user.name);

Important: fetch only rejects on network failures. A 404 or 500 still resolves — always check response.ok (true for status 200–299).

Sending JSON

const response = await fetch("/api/notes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Buy milk" }),
});
const created = await response.json();

Timeouts and cancelling

const response = await fetch(url, { signal: AbortSignal.timeout(5000) });  // give up after 5 s

Try the pattern

The example below uses a fake fetch so it runs anywhere — swap it for the real one in your projects:

Example 1Try it yourself
// A stand-in for fetch() that answers from an in-memory "server".
const db = { 1: { id: 1, name: "Ada" } };
async function fakeFetch(url) {
  const id = Number(url.split("/").pop());
  const user = db[id];
  return {
    ok: Boolean(user),
    status: user ? 200 : 404,
    json: async () => user ?? { error: "not found" },
  };
}

async function getUser(id) {
  const res = await fakeFetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

console.log(await getUser(1));
try {
  await getUser(2);
} catch (err) {
  console.log("Request failed:", err.message);
}

Output

{ id: 1, name: 'Ada' }
Request failed: HTTP 404

Browsers block requests to other domains unless the server allows them with CORS headers.

Test yourself

Does fetch reject its promise when the server responds with 404?

  1. Yes, always
  2. No — check response.ok
  3. Only in Node.js
  4. Only for POST requests
Show answer

Answer: No — check response.ok