Thuta Learning
API Tutorial
ExercisesWeb DevelopmentIntermediate

Practice Set 1: Request Fundamentals

API TutorialLesson 3240 min

What you'll walk away with

  • Send the same request with a Bearer token and with an X-API-Key header and explain how the two schemes differ
  • Predict the raw request line a server sees after URL encoding
  • Send a JSON body with the right Content-Type and recognise the 415 and 400 failures when you do not
  • Triage any outcome into ok, empty, unauthorized, not found, invalid, rate limited, bad body or network

Explain it simply

Explain it simply

This is a practice set, not a new topic. You already know the pieces: a method, a URL, headers, an optional body and a status code coming back. Here you assemble them against a local mock server that tells you exactly what it received, so you can compare what you meant to send with what actually went over the wire.

Each task is small. Do it on paper first, predict the answer, then run it; the habit of predicting is the real exercise.

Problem → Why → Solution

The problem: one 200 proves very little

One sample request returning 200 proves very little. The same code can still send the token in the wrong header, build a query string that the server decodes into something else, label a JSON body as plain text or treat an empty list as an error. These slips are invisible when you only look at the status of a happy path, and they surface later as a user with no results or a 415 that appears only in production.

looks-fine.js
// Gets a 200 from a lenient mock, and is still wrong in three ways
const q = "Alice & Bob";
const res = await fetch(`${base}/v1/users?q=${q}&limit=2`, { // the & splits the value
  method: "POST",                                             // a search should be GET
  headers: { "X-API-Token": key },                            // the header is X-API-Key
  body: JSON.stringify({ name: "Alice" }),                    // goes out as text/plain
});
console.log(res.status);

Why isn't the status code enough?

A status code only tells you what the server decided, not what you sent. To practise reading requests you need to see the other end: a server that records the request line and the headers it received, so every task ends with a check against the wire instead of a guess.

Core concept: a request is a contract with six parts

Every request you send is a small contract with six parts, and a practice set is a way to check each part on its own. The table shows what each part decides and the slip that people make most often.

PartWhat it decidesMost common slip
MethodWhat you want to do with the resourcePOST where GET was meant, or the other way round
URLWhich resource, plus the query stringA raw & or space inside a query value
HeadersWho you are, what you send and what you acceptWrong header name, or no Content-Type on a JSON body
BodyThe data, serialised as textSending an object instead of JSON.stringify(object)
AuthenticationWhich identity the server appliesPutting a Bearer token where the API expects a key
ResponseStatus first, then the bodyTreating an empty list as an error

Authentication has two common shapes. A Bearer token travels in Authorization: Bearer <token>; it usually identifies a user or an app and may expire. An API key is a static secret in a header whose name the provider chooses, such as X-API-Key, so read the docs for the exact name. Header names are case-insensitive, so Authorization, authorization and AUTHORIZATION are one header, but header values such as a key are case-sensitive: lab-key and LAB-KEY are different keys.

Query strings need encoding. The URL and URLSearchParams classes do it for you: a space becomes + and an ampersand inside a value becomes %26, which keeps it from splitting the parameter in two. A body needs two things, serialised data and a Content-Type that says how to read it. fetch labels a string body text/plain;charset=UTF-8 by default, so JSON needs an explicit application/json.

Read the response in layers: did an answer arrive at all (transport), what did the server decide (status), and does the body parse and contain what you expect (content). A 200 with an empty list is a valid answer, a 404 is not a 401, and a 200 whose body is not JSON means a broken server or proxy.

Mental model: send, then check the wire
  1. Predict the raw request before sending
  2. Send it with fetch
  3. Compare it with what the server recorded
  4. Read the response in three layers

A status code only tells you what the server decided. Looking at the request line the server recorded tells you what you actually sent.

General pattern

javascript
const url = new URL("/v1/things", base);
url.searchParams.set("q", value); // encoding is done for you

const res = await fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-API-Key": key },
  body: JSON.stringify(payload),
});

The URL object encodes the query value, and fetch takes the method, headers and body; a JSON body gets its Content-Type written out explicitly.

Tasks 1 to 3, plus what the server really saw

The lab server accepts either a Bearer token or an X-API-Key and records every request line exactly as it arrives. The tasks from the practice set come first: a Bearer request and its status, the same request with an API key, and a field pulled out of the JSON, with a guard for the empty list. After them come three extra checks that practise reading the wire: header case, query encoding and a JSON body sent with and without its Content-Type.

Before you run it, write down your prediction for each printed line. Every line that surprises you is a gap in your mental model of requests, which is exactly what this set is for.

lab.mjs
// Practice Set 1: the lab server records what it receives, so you can compare
// your request with what really went on the wire. Run: node lab.mjs
import http from "node:http";

// ===== Lab server (accepts a Bearer token OR an X-API-Key) =====
const BEARER = "lab-token";
const API_KEY = "lab-key";
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
  { id: "u_3", name: "Chidi", email: "chidi@example.com" },
];
const seen = []; // request lines exactly as they arrived, e.g. "GET /v1/users?limit=2"

function reply(res, status, body) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(body));
}
const problem = (code, message) => ({ error: { code, message } });

const lab = http.createServer(async (req, res) => {
  seen.push(`${req.method} ${req.url}`);
  const bearerOk = req.headers.authorization === `Bearer ${BEARER}`;
  if (!bearerOk && req.headers["x-api-key"] !== API_KEY) {
    return reply(res, 401, problem("UNAUTHORIZED", "Bad credentials"));
  }
  const url = new URL(req.url, "http://lab");
  if (req.method === "GET" && url.pathname === "/v1/users") {
    const q = (url.searchParams.get("q") ?? "").toLowerCase();
    const limit = Number(url.searchParams.get("limit") ?? 10);
    const data = users.filter((u) => u.name.toLowerCase().includes(q)).slice(0, limit);
    return reply(res, 200, { data });
  }
  if (req.method === "POST" && url.pathname === "/v1/users") {
    const type = req.headers["content-type"] ?? "(none)";
    if (!type.startsWith("application/json")) {
      return reply(res, 415, problem("UNSUPPORTED_MEDIA_TYPE", `Got ${type}`));
    }
    let raw = "";
    for await (const chunk of req) raw += chunk;
    let input;
    try {
      input = JSON.parse(raw);
    } catch {
      return reply(res, 400, problem("INVALID_JSON", "Body is not JSON"));
    }
    const user = { id: `u_${users.length + 1}`, name: input.name, email: input.email };
    users.push(user);
    return reply(res, 201, { data: user });
  }
  reply(res, 404, problem("NOT_FOUND", "No such route"));
});

// ===== The tasks =====
await new Promise((resolve) => lab.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${lab.address().port}`;
const bearer = { Authorization: `Bearer ${BEARER}` };
try {
  // Task 1: Bearer token
  const t1 = await fetch(`${base}/v1/users`, { headers: bearer });
  console.log("task 1: status", t1.status);

  // Task 2: the same request with an API key header instead
  const t2 = await fetch(`${base}/v1/users`, { headers: { "X-API-Key": API_KEY } });
  console.log("task 2: status", t2.status);

  // Task 3: pull one field out of the JSON, then guard the empty list
  const sample = { data: [{ id: "u_1", name: "Alice", email: "alice@example.com" }] };
  console.log("task 3:", sample.data[0].email);
  const empty = { data: [] };
  console.log("task 3 on an empty list:", empty.data[0]?.email ?? "(no users)");

  // Header names are case-insensitive; the key's value is not
  const loud = await fetch(`${base}/v1/users`, { headers: { "X-API-KEY": API_KEY } });
  const shout = await fetch(`${base}/v1/users`, { headers: { "x-api-key": "LAB-KEY" } });
  console.log("header name case:", loud.status, "| key value case:", shout.status);

  // Let URL encode the query string, then look at the wire
  const url = new URL("/v1/users", base);
  url.searchParams.set("q", "Alice & Bob");
  url.searchParams.set("limit", "2");
  const found = await (await fetch(url, { headers: bearer })).json();
  console.log("on the wire:", seen.at(-1));
  console.log("users found:", found.data.length, "(an empty list is still a 200)");

  // A JSON body needs an explicit Content-Type
  const post = (body, type) =>
    fetch(`${base}/v1/users`, {
      method: "POST",
      headers: { ...bearer, ...(type && { "Content-Type": type }) },
      body,
    });
  const person = JSON.stringify({ name: "Dara", email: "dara@example.com" });
  const noType = await (await post(person)).json();
  console.log("POST without Content-Type:", noType.error.code, "-", noType.error.message);
  const good = await post(person, "application/json");
  console.log("POST with the header:", good.status, (await good.json()).data.id);
  const broken = await post("{name: Dara", "application/json");
  console.log("POST with broken JSON:", broken.status, (await broken.json()).error.code);
} finally {
  lab.close();
}

Code breakdown

  1. API key instead of Bearerheaders: { "X-API-Key": API_KEY }

    Task 2 sends the same request with an X-API-Key header instead of Authorization. The lab server accepts both, so both statuses are 200 and only the header differs.

  2. Let URL encode the queryurl.searchParams.set("q", "Alice & Bob");

    You never escape the space or the & by hand. searchParams turns them into + and %26, so the parameter stays a single parameter.

  3. Compare with the wireseen.at(-1)

    seen holds every request line the server received, and at(-1) is the latest one. Comparing it with your own prediction is the main habit of this lesson.

  4. Guard the empty listempty.data[0]?.email ?? "(no users)"

    data[0].email throws a TypeError on an empty list. The ?. stops at undefined and ?? supplies a fallback text, so an empty list is handled as a normal result.

  5. Content-Type is explicit...(type && { "Content-Type": type }),

    The post() helper adds Content-Type only when a type is given. Leave it out and fetch sends text/plain, so the server answers 415, as the output shows.

You should see
task 1: status 200
task 2: status 200
task 3: alice@example.com
task 3 on an empty list: (no users)
header name case: 200 | key value case: 401
on the wire: GET /v1/users?q=Alice+%26+Bob&limit=2
users found: 0 (an empty list is still a 200)
POST without Content-Type: UNSUPPORTED_MEDIA_TYPE - Got text/plain;charset=UTF-8
POST with the header: 201 u_4
POST with broken JSON: 400 INVALID_JSON

How to work through a task

1. Predict

Write the method, path, query string and headers you expect, and the status you expect back.

2. Send

Run the request against the lab server, not a real API.

3. Compare

Check the recorded request line and the response; any difference is a lesson.

4. Break it

Change one part (wrong key, missing header, broken JSON) and predict the new status before running.

Never practise with a real token

Every task here uses lab-token and lab-key against a server that exists only for the length of the script. A real token in an exercise ends up in a commit, a log or a screenshot sooner or later.

Triage: the order in which to read a response

LayerQuestionExample failure
TransportDid any answer arrive?ECONNREFUSED: nothing is listening
StatusWhat did the server decide?401, 404, 422 or 429, each needing a different reaction
ContentDoes the body parse and match what you expect?200 with HTML, or 200 with an empty list

This order is exactly what the challenge's probe() function implements. Reading the layers in that order means each branch of your code has one job.

In real projects

In real projects

In a real team these tasks turn into tests that run on every commit: a contract test that sends a known request to a mock or sandbox and asserts the status and the shape, and a smoke test that checks authentication still works after a key rotation. Support engineers do the same by hand when a customer says 'your API returns nothing': they reproduce the exact request, compare it with what the server logged, and usually find a wrong header, an unencoded character or an empty list that the customer's code treated as an error.

The habit of recording what the server saw is just as valuable in production. Good APIs echo a request id, and good clients log the method, URL and status, with every secret redacted, so a bug report can be matched to a server-side log line.

Common mistakes

Common mistakes

Judging a request by its status alone

console.log(res.status) prints 200 for a request that sent the key in the wrong place if the server is lenient, and for one whose query value was cut at an ampersand. Compare with what the server received, and assert the body as well as the status.

Building query strings by hand

`?q=${q}` with q set to Alice & Bob sends two parameters and silently drops half the value. Use URL and searchParams.set, which encode the value for you.

Indexing the first element of a possibly empty list

data[0].email throws TypeError: Cannot read properties of undefined (reading 'email') when the list is empty, which is a normal and valid answer. Check data.length, or use data[0]?.email with a fallback.

Mini challenge

Build a response triage function

Write probe(url, init) that turns any outcome into one { kind, detail } verdict, so the rest of your program can switch on kind instead of juggling status codes. Run it against a mock that returns a normal list, an empty list, a wrong key, a missing user, an invalid body, a throttled request, a 204, a garbled body, and finally a port where nothing is listening.

  • A fetch that rejects returns kind network, with the real code read from err.cause.code
  • Read the body as text first, then JSON.parse it inside try/catch; unparseable text is bad_body
  • 401, 404, 422 and 429 map to unauthorized, not_found, invalid and rate_limited, with a useful detail (error code, field names, Retry-After seconds)
  • A 204 is ok with no content, and a 2xx with an empty data array is empty rather than an error
probe.mjs
// Response triage: turn ANY outcome into one { kind, detail } verdict.
// kinds: ok | empty | unauthorized | not_found | invalid | rate_limited
//        | bad_body | http_error | network

async function probe(url, init = {}) {
  // TODO 1: await fetch(url, init); if it rejects, return { kind: "network", detail }
  //         and read the real code from err.cause?.code instead of assuming one
  // TODO 2: read the body with res.text() FIRST; a 204 or an empty 2xx body is "ok"
  // TODO 3: JSON.parse the text inside try/catch; failure means { kind: "bad_body" }
  // TODO 4: map 401, 404, 422 (list the field names), 429 (include Retry-After seconds)
  // TODO 5: a 2xx whose data is an empty array is "empty", not an error
}

// TODO 6: point probe() at your own mock (or the lesson's lab server) for nine cases,
//         including a closed port, and print one "label -> kind (detail)" line each

Expected: Nine lines of the form label -> kind (detail), ending with closed port -> network (ECONNREFUSED).

Show hint

res.text() never throws on a normal body, so you can call JSON.parse on it yourself and catch the SyntaxError. For the closed port, create a server, read its port, close it and then fetch that port.

Show solution
probe.mjs
import http from "node:http";

const KEY = "lab-key";
const json = (res, status, body, headers = {}) => {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
};

// A mock that misbehaves in exactly the ways a real provider eventually will
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://mock");
  if (req.headers["x-api-key"] !== KEY) {
    return json(res, 401, { error: { code: "UNAUTHORIZED", message: "Bad key" } });
  }
  if (url.pathname === "/v1/users" && req.method === "GET") {
    const q = url.searchParams.get("q");
    const data = q ? [] : [{ id: "u_1" }, { id: "u_2" }, { id: "u_3" }];
    return json(res, 200, { data });
  }
  if (url.pathname === "/v1/users/u_404") {
    return json(res, 404, { error: { code: "NOT_FOUND", message: "No such user" } });
  }
  if (url.pathname === "/v1/users" && req.method === "POST") {
    const fields = { name: "required", email: "invalid" };
    const error = { code: "VALIDATION_ERROR", message: "Bad input", fields };
    return json(res, 422, { error });
  }
  if (url.pathname === "/v1/users/u_1" && req.method === "DELETE") {
    res.writeHead(204);
    return res.end();
  }
  if (url.pathname === "/v1/burst") {
    const body = { error: { code: "RATE_LIMITED", message: "Slow down" } };
    return json(res, 429, body, { "Retry-After": "3" });
  }
  if (url.pathname === "/v1/garbled") {
    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end("<html>maintenance</html>");
  }
  json(res, 404, { error: { code: "NOT_FOUND", message: "No such route" } });
});

// Turn ANY outcome into one { kind, detail } verdict
async function probe(url, init = {}) {
  let res;
  try {
    res = await fetch(url, init);
  } catch (err) {
    return { kind: "network", detail: err.cause?.code ?? err.name };
  }
  const text = await res.text();
  if (res.status === 204 || (res.ok && text === "")) {
    return { kind: "ok", detail: "no content" };
  }
  let body;
  try {
    body = JSON.parse(text);
  } catch {
    return { kind: "bad_body", detail: `status ${res.status}` };
  }
  if (res.status === 401) return { kind: "unauthorized", detail: body.error.code };
  if (res.status === 404) return { kind: "not_found", detail: body.error.code };
  if (res.status === 422) {
    return { kind: "invalid", detail: Object.keys(body.error.fields ?? {}).join(", ") };
  }
  if (res.status === 429) {
    const seconds = Number(res.headers.get("retry-after") ?? 1);
    return { kind: "rate_limited", detail: `retry in ${seconds}s` };
  }
  if (!res.ok) return { kind: "http_error", detail: `status ${res.status}` };
  if (Array.isArray(body.data) && body.data.length === 0) {
    return { kind: "empty", detail: "0 items" };
  }
  return { kind: "ok", detail: `${body.data?.length ?? 1} items` };
}

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const deadBase = `http://127.0.0.1:${closed.address().port}`;
await new Promise((resolve) => closed.close(resolve));

const auth = { headers: { "X-API-Key": KEY } };
const cases = [
  ["list", `${base}/v1/users`, auth],
  ["search nobody", `${base}/v1/users?q=zzz`, auth],
  ["wrong key", `${base}/v1/users`, { headers: { "X-API-Key": "nope" } }],
  ["missing user", `${base}/v1/users/u_404`, auth],
  ["invalid body", `${base}/v1/users`, { ...auth, method: "POST", body: "{}" }],
  ["too fast", `${base}/v1/burst`, auth],
  ["delete", `${base}/v1/users/u_1`, { ...auth, method: "DELETE" }],
  ["garbled", `${base}/v1/garbled`, auth],
  ["closed port", `${deadBase}/v1/users`, auth],
];
try {
  for (const [label, url, init] of cases) {
    const { kind, detail } = await probe(url, init);
    console.log(`${label.padEnd(14)}-> ${kind} (${detail})`);
  }
} finally {
  server.close();
}

Quick quiz 1 / 3

What does new URLSearchParams({ q: 'a&b' }).toString() return?

Quick quiz 2 / 3

A server compares req.headers['x-api-key'] with 'lab-key'. Your client sends the header X-API-KEY: LAB-KEY. What status does it get?

Quick quiz 3 / 3

A list endpoint answers 200 with { "data": [] }. Which handling is right?

What to remember

  • A Bearer token goes in Authorization, an API key in the header the provider names; header names ignore case, values do not
  • Let URL and URLSearchParams encode query values instead of gluing strings together
  • A JSON body needs an explicit Content-Type: application/json, because fetch labels a string text/plain
  • Read a response in layers (transport, status, content) and treat an empty list as a normal success

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice Set 1: Request Fundamentals | Thuta Learning