Explain it simply
Explain it simply
Practice Set 1 checked single requests. This set chains them: create, list in pages, update, delete, and then verify each step by asking the server again instead of trusting your own variables. The extra skill is error flow: for every task you also decide what should happen when the request is refused, throttled or never arrives.
Compare writing in a diary with going to check your bank statement. The diary tells you what you believe happened; only the statement tells you what really did. In this set your variables are the diary and the server is the statement.
Problem → Why → Solution
The problem: a CRUD screen that only works on demo data
A CRUD screen that works on demo data proves little. It can pass while the second page repeats the first page's last user, while an update looks saved only because the client edited its own copy, while a delete leaves the record in the list, and while a throttled request is silently dropped. Each of these only shows when you verify through a fresh request and inject failures on purpose.
// "Passes" because it only ever trusts its own variables
const created = [];
for (const name of ["A", "B", "C"]) created.push(await createUser(name));
created[1].email = "b@new.example.com"; // edited the local copy, no PATCH was sent
created.splice(0, 1); // removed locally, no DELETE was sent
console.log(created.length === 2 ? "all good" : "broken"); // the server was never askedWhere does verification have to cross?
Verification has to cross the same boundary the real user crosses. The client's memory is not the system of record; the server is. So every mutation in this set is followed by a read that goes back over HTTP, and every failure path is triggered deliberately.
Core concept: state, invariants and failure injection
A realistic exercise starts from the rules that must hold afterwards, not from the code. Write those invariants first, then build the calls, then break them on purpose.
1. Write the invariants first
After three creates and limit=2, page 1 holds two users, page 2 holds one, meta.total is 3 and page 3 is an empty list, not an error. Ids are unique and never reused after a delete.
2. Mutate, then re-read
Every PATCH and DELETE is followed by a fresh GET. The response of the mutating call tells you what the server accepted; only the follow-up read tells you what was stored.
3. Inject the failure on purpose
Decide for each task how the client reacts to 401, 404, 409, 422, 429 and a dead connection, and trigger each one against the mock so the decision is tested rather than hoped for.
| Status or failure | Client reaction | Retry? |
|---|---|---|
| 401 | Stop and tell the user the token looks wrong | No |
| 404 after DELETE | Success, the record is already gone | No |
| 409 | Skip the item or look up the existing record | No |
| 422 | Report the offending fields to the user | No |
| 429 with Retry-After | Wait the given time, resend the same request | Yes, with a limit |
| Connection refused | Stop and report the code, or retry with backoff | Maybe |
Create users in a for...of loop with await, not with Promise.all, when order matters. Parallel requests can reach the server in any order, so ids and the page split would differ between runs. Use Promise.all only for independent requests whose order you do not care about.
Pagination has its own invariants. Page numbers start at 1, the last page may be shorter, a page past the end is an empty list rather than an error, and a loop that walks pages should stop on meta.total and also on an empty page, so a wrong total can never cause an endless loop.
- State what must be true afterwards
- Do the call
- Read it back over HTTP
- Break it on purpose, assert again
Your variables describe what you hoped happened. Only a fresh request describes what the server actually stored.
General pattern
await mutate(); // POST / PATCH / DELETE
const after = await readBack(); // a fresh GET, never local state
assertEqual(after, expected);
queueFault(status); // refuse, throttle or drop ONE request
const outcome = await attempt(mutate);
assertEqual(outcome.kind, expectedKind);Every mutation is followed by a read-back and an assert, and then one failure is queued so the client's reaction can be asserted as well.
Tasks 1 to 4, verified by re-reading
The mock API starts empty, so the first thing the file does is list an empty collection, a case that many clients forget. Then it solves the four tasks of the set in order: three creates followed by two pages and a third page that is empty, a PATCH confirmed by a GET, a DELETE confirmed by a 404, and a wrong token turned into one friendly sentence.
The small call() helper never throws on an HTTP error; it returns { status, body }. That makes it easy to assert on a 404 or a 401 as ordinary results. Predict each printed line before running.
// Practice Set 2: create, page, update, delete and fail, verified by re-reading.
// Run: node lifecycle.mjs (the mock API lives in this file)
import http from "node:http";
// ===== Mock API: starts EMPTY, so the empty list is a real case =====
const GOOD = "good-token";
const users = [];
let nextId = 1;
function reply(res, status, body) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(body === undefined ? undefined : JSON.stringify(body));
}
const problem = (code, message) => ({ error: { code, message } });
async function readBody(req) {
let raw = "";
for await (const chunk of req) raw += chunk;
return JSON.parse(raw);
}
const mock = http.createServer(async (req, res) => {
if (req.headers.authorization !== `Bearer ${GOOD}`) {
return reply(res, 401, problem("UNAUTHORIZED", "Bad token"));
}
const url = new URL(req.url, "http://mock");
const id = url.pathname.split("/")[3]; // /v1/users/:id
const user = users.find((u) => u.id === id);
if (req.method === "GET" && !id) {
const page = Number(url.searchParams.get("page") ?? 1);
const limit = Number(url.searchParams.get("limit") ?? 10);
const data = users.slice((page - 1) * limit, page * limit);
return reply(res, 200, { data, meta: { page, limit, total: users.length } });
}
if (req.method === "POST" && !id) {
const created = { id: `u_${nextId++}`, ...(await readBody(req)) };
users.push(created);
return reply(res, 201, { data: created });
}
if (id && !user) return reply(res, 404, problem("NOT_FOUND", `No user ${id}`));
if (req.method === "GET") return reply(res, 200, { data: user });
if (req.method === "PATCH") {
Object.assign(user, await readBody(req));
return reply(res, 200, { data: user });
}
if (req.method === "DELETE") {
users.splice(users.indexOf(user), 1);
return reply(res, 204);
}
reply(res, 405, problem("METHOD_NOT_ALLOWED", req.method));
});
// ===== A tiny helper: never throws on HTTP errors, returns { status, body } =====
async function call(base, method, path, { body, token = GOOD } = {}) {
const res = await fetch(`${base}${path}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
...(body && { "Content-Type": "application/json" }),
},
body: body && JSON.stringify(body),
});
const text = await res.text();
return { status: res.status, body: text ? JSON.parse(text) : null };
}
const names = (r) => r.body.data.map((u) => u.name).join(", ") || "(empty)";
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${mock.address().port}/v1`;
const get = (path, token) => call(base, "GET", path, { token });
try {
const first = await get("/users");
console.log("empty list: total =", first.body.meta.total);
// Task 1: create three users IN ORDER, then page through them
for (const letter of ["A", "B", "C"]) {
const email = `${letter.toLowerCase()}@example.com`;
await call(base, "POST", "/users", { body: { name: letter, email } });
}
const pages = [];
for (const page of [1, 2, 3]) pages.push(await get(`/users?page=${page}&limit=2`));
console.log("task 1:", pages.map((p, i) => `page ${i + 1} = ${names(p)}`).join(" | "));
console.log("task 1: total =", pages[1].body.meta.total);
// Task 2: PATCH one user, then prove it with a fresh GET
const change = { email: "b@new.example.com" };
const patched = await call(base, "PATCH", "/users/u_2", { body: change });
const reread = await get("/users/u_2");
console.log(`task 2: ${patched.status} ${patched.body.data.email}`);
console.log("task 2: GET confirms", reread.body.data.email);
// Task 3: DELETE, then expect a 404 (not a failure!) when reading it back
const removed = await call(base, "DELETE", "/users/u_2");
const gone = await get("/users/u_2");
const after = `GET ${gone.status} ${gone.body.error.code}`;
console.log(`task 3: DELETE ${removed.status} | ${after}`);
console.log("task 3: left =", names(await get("/users")));
// Task 4: a wrong token becomes a friendly sentence
const denied = await get("/users", "wrong");
const friendly = "That token looks wrong - please double-check it.";
console.log("task 4:", denied.status, "->", denied.status === 401 ? friendly : "ok");
} finally {
mock.close();
}Code breakdown
- Sequential creates
for (const letter of ["A", "B", "C"]) {A plain for...of loop with await creates the users as A, B, C in that order, so the ids are u_1, u_2, u_3 on every run.
- Page 3 is empty, not an error
pages.push(await get(`/users?page=${page}&limit=2`))All three pages are requested. Page 3 is past the end, and you will see it come back as a 200 with empty data, printed as (empty), rather than a 404.
- Re-read after PATCH
const reread = await get("/users/u_2");The PATCH response says what the server accepted. This fresh GET is what proves the changed email was really stored.
- A 404 after DELETE is the goal
const gone = await get("/users/u_2");After the delete this GET should return 404 NOT_FOUND. That is not a failure; it is the proof that the delete worked.
- Helper returns statuses as data
return { status: res.status, body: text ? JSON.parse(text) : null };call() returns error statuses as data instead of throwing. For a 204 with no body it returns null, so there is no parsing error either.
empty list: total = 0
task 1: page 1 = A, B | page 2 = C | page 3 = (empty)
task 1: total = 3
task 2: 200 b@new.example.com
task 2: GET confirms b@new.example.com
task 3: DELETE 204 | GET 404 NOT_FOUND
task 3: left = A, C
task 4: 401 -> That token looks wrong - please double-check it.Pagination edge cases to test
Pagination bugs like to hide at the edges. The table shows what a client should expect for each size of collection. The example covers the first, third and (through page 3) fourth rows; your own tests should cover the rest.
| Case | Request | Expected |
|---|---|---|
| Empty collection | GET /users | 200, data empty, meta.total 0 |
| Exact multiple | 4 users, limit=2 | Two full pages, page 3 empty |
| Short last page | 3 users, limit=2 | Page 2 holds one user |
| Past the end | page=99 | 200 with an empty list, not 404 |
| Bad limit | limit=0 or limit=-1 | Server decides: clamp or a 4xx, so read the docs |
Write the failure plan before the code
A failure plan is a table you fill in before coding: for each call, which statuses can come back and what the client does about each. Writing it first stops two classic mistakes: retrying a 422, which will fail identically forever, and swallowing a 401, which hides a broken credential behind an empty screen.
Do not retry what repeating cannot fix
A 422 or a 401 returns the same answer every time, so retrying only delays the error message. Reserve retries for 429, timeouts and transient 5xx.
In real projects
In real projects
This chain is the skeleton of nearly every integration test suite: create fixtures, exercise the endpoint, read back, clean up, plus a fault matrix for the unhappy paths. Teams run it in CI against a sandbox or a mock server, and the 'inject a 429' step is usually the one that finds the bug nobody noticed in manual testing, because rate limits do not appear when a developer clicks around slowly.
Bulk imports, which the challenge builds, are everywhere: onboarding a customer's contact list, migrating users between systems, syncing a spreadsheet. Their defining requirement is a report. Operators need to know exactly which rows were created, which were skipped as duplicates and which were rejected and why, so they can fix the data and rerun without redoing the whole job.
Common mistakes
Common mistakes
Verifying with local variables
Editing the object you got back from POST and then asserting on it proves nothing about the server. After every mutation, make a fresh GET and assert on that.
Assuming order with Promise.all
Firing three creates in parallel lets them reach the server in any order, so ids, page contents and the total differ between runs. Use a sequential loop when order matters.
Treating 404 after DELETE as a bug
The 404 is the proof that the delete worked. Assert it, and in a script that only needs the record gone, treat a 404 on DELETE as success too.
Retrying a 429 forever or ignoring Retry-After
Without a retry limit a permanent throttle hangs the import; ignoring the header hammers the server again at once. Wait the advertised time and give up after a few tries.
Mini challenge
Build a bulk import with a report
Write importUsers(baseUrl, items, { sleep, maxRetries }) that POSTs every item in order and never throws for an expected failure. It returns a report with created, skipped (409), rejected (422, naming the bad fields) and aborted (set when nothing can be reached). A 429 must wait the Retry-After time and resend the same item. Afterwards walk the pages with limit=2 and print every name.
- Items are sent one after another with for...of and await, never with Promise.all
- 201 goes to created, 409 to skipped, 422 to rejected with the offending field names
- A 429 waits Retry-After seconds through the injected sleep and resends the same item, at most maxRetries times
- A rejected fetch (nobody listening) sets report.aborted to the real error code and stops the import
- An empty items array returns an empty report, and listAll stops on an empty page or on meta.total
// Bulk import that survives refusals.
// Use the mock server from the lesson example, or write your own.
async function importUsers(baseUrl, items, { sleep, maxRetries = 2 } = {}) {
const report = { created: [], skipped: [], rejected: [], aborted: null };
// TODO 1: POST each item in ORDER (for...of with await, not Promise.all)
// TODO 2: 201 -> created, 409 -> skipped, 422 -> rejected (name the bad fields)
// TODO 3: 429 -> wait Retry-After seconds with sleep(ms) and resend the SAME item,
// at most maxRetries times
// TODO 4: fetch rejects (nobody listening) -> report.aborted = the error code, stop
return report;
}
async function listAll(baseUrl, pageSize) {
// TODO 5: walk page=1,2,... until a page is empty or page * pageSize >= meta.total
}
// TODO 6: import five items (new, duplicate, throttled, invalid, new), then listAll,
// then try an empty array and a closed portExpected: Seven lines: created, skipped and rejected lines for the five items with a single recorded sleep of 2000 ms, then the four names on two pages, then an empty report for the empty input and ECONNREFUSED for the dead server.
Show hint
Use a for loop with an attempt counter inside each item, and continue it after a 429. Read the code with err.cause?.code. For listAll, compare page * pageSize with meta.total, and stop on an empty page as a second guard.
Show solution
import http from "node:http";
// ===== Mock API: one existing user, a duplicate check, and one throttled POST =====
const users = [{ id: "u_1", name: "Alice", email: "alice@example.com" }];
let nextId = 2;
let postsSeen = 0;
function reply(res, status, body, headers = {}) {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
}
const problem = (code, message, fields) => ({ error: { code, message, fields } });
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://mock");
if (req.method === "GET" && url.pathname === "/v1/users") {
const page = Number(url.searchParams.get("page") ?? 1);
const limit = Number(url.searchParams.get("limit") ?? 10);
const data = users.slice((page - 1) * limit, page * limit);
return reply(res, 200, { data, meta: { page, limit, total: users.length } });
}
if (req.method === "POST" && url.pathname === "/v1/users") {
postsSeen++;
let raw = "";
for await (const chunk of req) raw += chunk;
const input = JSON.parse(raw);
if (postsSeen === 3) { // the third POST is throttled, once
const error = problem("RATE_LIMITED", "Slow down");
return reply(res, 429, error, { "Retry-After": "2" });
}
const fields = {};
if (!input.name) fields.name = "required";
if (!/^[^@\s]+@[^@\s]+$/.test(input.email ?? "")) fields.email = "invalid";
if (Object.keys(fields).length) {
return reply(res, 422, problem("VALIDATION_ERROR", "Invalid user", fields));
}
if (users.some((u) => u.email === input.email)) {
return reply(res, 409, problem("CONFLICT", "Email already in use"));
}
const user = { id: `u_${nextId++}`, ...input };
users.push(user);
return reply(res, 201, { data: user });
}
reply(res, 404, problem("NOT_FOUND", "No such route"));
});
// ===== The importer: one report, no exceptions for expected failures =====
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function importUsers(baseUrl, items, { sleep = wait, maxRetries = 2 } = {}) {
const report = { created: [], skipped: [], rejected: [], aborted: null };
for (const item of items) {
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(`${baseUrl}/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(item),
});
} catch (err) {
report.aborted = err.cause?.code ?? "NETWORK_ERROR"; // nobody to talk to: stop
return report;
}
if (res.status === 429 && attempt < maxRetries) {
await sleep(Number(res.headers.get("retry-after") ?? 1) * 1000);
continue; // same item, one more try
}
const body = await res.json().catch(() => null);
if (res.status === 201) report.created.push(item.email);
else if (res.status === 409) report.skipped.push(item.email);
else if (res.status === 422) {
const fields = Object.keys(body.error.fields).join("+");
report.rejected.push(`${item.email || "(blank)"} [${fields}]`);
} else {
report.aborted = `HTTP ${res.status}`;
return report;
}
break;
}
}
return report;
}
async function listAll(baseUrl, pageSize) {
const names = [];
for (let page = 1; ; page++) {
const res = await fetch(`${baseUrl}/users?page=${page}&limit=${pageSize}`);
const { data, meta } = await res.json();
names.push(...data.map((u) => u.name));
if (data.length === 0 || page * pageSize >= meta.total) return { names, pages: page };
}
}
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}/v1`;
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}/v1`;
await new Promise((resolve) => closed.close(resolve));
try {
const sleeps = [];
const items = [
{ name: "Fiona", email: "fiona@example.com" },
{ name: "Alice again", email: "alice@example.com" },
{ name: "Gus", email: "gus@example.com" },
{ name: "", email: "nope" },
{ name: "Hana", email: "hana@example.com" },
];
const report = await importUsers(base, items, { sleep: async (ms) => sleeps.push(ms) });
console.log("created: ", report.created.join(", "));
console.log("skipped: ", report.skipped.join(", "));
console.log("rejected:", report.rejected.join(", "));
console.log("aborted: ", report.aborted, "| sleeps:", sleeps.join(", "));
const all = await listAll(base, 2);
console.log(`server now has: ${all.names.join(", ")} (${all.pages} pages of 2)`);
const nothing = await importUsers(base, []);
console.log("empty input:", JSON.stringify(nothing));
const dead = await importUsers(deadBase, items.slice(0, 1));
console.log("dead server:", dead.aborted, "| created:", dead.created.length);
} finally {
server.close();
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Write the invariants first, then verify every mutation with a fresh GET, never with local variables
- Create in a sequential loop when order matters, and test the empty list, the short last page and the empty page past the end
- A 404 after DELETE proves the delete worked; 401 and 422 must not be retried, while 429 waits for Retry-After
- A bulk operation should return a report of created, skipped, rejected and aborted items instead of throwing on the first failure
OWASP API Security Project — OWASP