Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 3

Talking to an HTTP API with fetch

Read JSON from an API, tell HTTP errors apart from network failures, and send JSON bodies with the right method and headers — against a local mock server.

Contentsand lesson path

What you will learn

  • Call a JSON HTTP API with fetch: check response.ok, distinguish HTTP errors from network failures, parse the body, and send JSON with the correct method and headers.

Prerequisites: JavaScript Foundations

01. The problem

You are building a small shop client. It must list the catalogue, show one item, and let the user add an item. The API speaks JSON over HTTP, and the client has to survive the two ways a call can fail: the server answers with an error status, or no answer arrives at all. Both happen constantly in real apps, and treating them the same way is a classic fetch bug.

To keep every output reproducible, this lesson talks to a mock API running on your own machine with node:http — the same HTTP a public API would speak. The HTTP semantics themselves (methods, status classes, bodies) are covered in depth in the HTTP skill; here we focus on what fetch does with them.

02. Step 1: the API on the other end

JavaScript · api.mjs
import { createServer } from 'node:http';

const items = [
  { id: 1, name: 'Mechanical keyboard' },
  { id: 2, name: 'USB-C hub' },
  { id: 3, name: 'Desk mat' },
];

function send(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
}

createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const match = url.pathname.match(/^\/items\/(\d+)$/);

  if (req.method === 'GET' && url.pathname === '/items') {
    return send(res, 200, items);
  }
  if (req.method === 'GET' && match) {
    const item = items.find((i) => i.id === Number(match[1]));
    return item ? send(res, 200, item)
      : send(res, 404, { error: `no item ${match[1]}` });
  }
  if (req.method === 'POST' && url.pathname === '/items') {
    let raw = '';
    req.on('data', (chunk) => (raw += chunk));
    req.on('end', () => {
      const type = req.headers['content-type'];
      let parsed = null;
      try { parsed = JSON.parse(raw); } catch { parsed = null; }
      if (type !== 'application/json' || parsed === null) {
        return send(res, 415, { error: 'send Content-Type: application/json' });
      }
      const created = { id: items.length + 1, ...parsed };
      items.push(created);
      return send(res, 201, created);
    });
    return;
  }
  res.writeHead(405, { Allow: 'GET, POST' });
  res.end();
}).listen(4100, () => console.log("mock shop API on http://localhost:4100"));

Run it with node api.mjs and it serves three GET/POST routes: list, detail (404 for unknown ids), and create (415 unless the request really is JSON). Keep it running in one terminal and put the client code in a second file, because every output below comes from talking to this server. In the browser your page would call the same kind of endpoints; only the hostname would change.

03. Step 2: reading data — status, ok and the body

JavaScript · client.mjs
const BASE = 'http://localhost:4100';

const list = await fetch(`${BASE}/items`);
console.log('GET /items ->', list.status, 'ok:', list.ok);
console.log(await list.json());

const missing = await fetch(`${BASE}/items/99`);
console.log('GET /items/99 ->', missing.status, 'ok:', missing.ok);
console.log('body:', await missing.json());
Expected output
GET /items -> 200 ok: true
[
  { id: 1, name: 'Mechanical keyboard' },
  { id: 2, name: 'USB-C hub' },
  { id: 3, name: 'Desk mat' }
]
GET /items/99 -> 404 ok: false
body: { error: 'no item 99' }

The single most important line here is the 404 one: fetch resolved normally. A resolved promise means a complete HTTP round trip happened — any status counts, including 4xx and 5xx. fetch rejects only when no usable response exists, which is the next step.

So the client must judge the outcome itself, from res.ok (true for statuses 200–299) or res.status. The 404 still carries a JSON body — an error message the API designed on purpose — which is exactly why you cannot detect failure by whether parsing works. Check ok first, then read the body.

04. Step 3: network failures — the case fetch does reject

JavaScript · client.mjs (continued)
try {
  await fetch('http://localhost:4999/items'); // nothing listens on 4999
} catch (err) {
  console.log('network error ->', err.name, '|', err.message,
    '|', err.cause?.code);
}
Expected output
network error -> TypeError | fetch failed | ECONNREFUSED

No server on port 4999, so there is no response at all: fetch rejects with a TypeError. The same rejection covers DNS failures, refused connections and responses blocked by CORS policy. The distinction that matters for your UI:

  • HTTP error (fetch resolved, res.ok is false): the server was reached and answered on purpose. Retry behaviour is a per-status decision — a 404 will not fix itself, a 503 might.
  • Network failure (fetch rejected with TypeError): nothing usable came back. The cause lives on err.cause in Node; in a browser it is often hidden for security. Retrying after a delay is reasonable.
  • Abort (rejected with an AbortError): you cancelled it yourself — lesson 4.

The distinction decides your UI, too. An HTTP error can show the message the API wrote for humans; a network failure has no such message, so the interface should say the connection failed and offer a retry, instead of displaying an empty screen or a misleading "not found".

05. Step 4: sending JSON

JavaScript · client.mjs (continued)
const created = await fetch(`${BASE}/items`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Laptop stand' }),
});
console.log('POST /items ->', created.status, await created.json());

const wrong = await fetch(`${BASE}/items`, {
  method: 'POST',
  body: JSON.stringify({ name: 'Cable' }),
});
console.log('POST again ->', wrong.status, await wrong.json());
Expected output
POST /items -> 201 { id: 4, name: 'Laptop stand' }
POST again -> 415 { error: 'send Content-Type: application/json' }

Three parts have to agree. The method says what the request is for. The body carries the data — for a JSON API it must be a string, which is why JSON.stringify is required. (fetch also accepts bodies such as FormData, Blob, URLSearchParams and streams, but never a plain object: passing one would send the text [object Object].) And the Content-Type header tells the server how to read that string. Omit it and a strict server answers 415 Unsupported Media Type, as this one does — a polite outcome compared with silently misparsing the body.

The 201 Created response is the server confirming the new resource, with its assigned id. Note that await created.json() parses the body of that POST response; servers commonly return the created object, but check the status contract of the API you are calling.

06. Step 5: three body rules with sharp edges

Response bodies, request bodies and empty responses each have a rule that bites beginners. All three were run against the mock API.

JavaScript · body-once.mjs
const BASE = 'http://localhost:4100';
const res = await fetch(`${BASE}/items`);
const items = await res.json();
console.log('first read:', items.length, 'items');
try {
  await res.json();
} catch (err) {
  console.log('second read ->', err.name, '|', err.message);
}
Expected output (ran after the POST above, so 4 items)
first read: 4 items
second read -> TypeError | Body is unusable: Body has already been read

A body is a stream that can be read once. Read it again — or even peek at it after json() has consumed it — and it throws. If you need the data twice, keep the parsed value. The other two rules concern requests:

JavaScript · edge.mjs
const BASE = 'http://localhost:4100';
try {
  await fetch(`${BASE}/items`, { method: 'GET', body: '{"x":1}' });
} catch (err) {
  console.log('GET with body ->', err.name, '|', err.message);
}

const empty = await fetch(`${BASE}/items`, { method: "PUT" });
console.log('status:', empty.status,
  '| content-length:', empty.headers.get('content-length'));
try {
  await empty.json();
} catch (err) {
  console.log('json() ->', err.name, '|', err.message);
}
Expected output
GET with body -> TypeError | Request with GET/HEAD method cannot have body.
status: 405 | content-length: null
json() -> SyntaxError | Unexpected end of JSON input

First: a GET (or HEAD) request cannot carry a body, so fetch throws a TypeError before sending anything — filters belong in the query string. Second: res.json() parses, it does not inspect. Hand an empty body (a 204, or this 405) to json() and it throws a SyntaxError because there was never any JSON. Only parse when the status contract says a body exists.

07. Mistakes to watch for

08. Check your understanding

Practice check · 3 questions

fetch in practice

Predict what each call does before running it.

Q1. You read a response with `await res.json()` and later call `res.json()` again on the same response. What happens?
Q2. An endpoint answers 204 No Content with an empty body. What does `await res.json()` do?
Q3. What happens when you pass a `body` option to a GET request in `fetch`?
Practice only: not graded, not saved, not evidence.

09. Apply it

The lab for this skill builds a search client on exactly these rules. To practise now, extend the mock API and client:

  1. Add a DELETE /items/:id route to api.mjs that returns 204 with no body. Call it from the client and note what res.ok is — and that calling res.json() on it throws.
  2. Write a getJson(url) helper that awaits fetch, throws a descriptive Error when res.ok is false (including the status), and returns the parsed body otherwise. Rebuild steps 2 and 3 on top of it.
  3. Point the same client at a second port with no server running, and confirm you get the TypeError branch, not the 404 branch.

10. Review prompt

Without looking back: when does the promise from fetch resolve, and when does it reject? What do res.ok and res.status each tell you, and why must you check one of them before parsing? Name the three parts of a JSON POST request, the error each missing part produces, and the two errors res.json() can throw on its own.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check