Show contents
Chapter 6 of 7 · 25 min
Project: a club's registration API
By the end of this chapter, you'll be able to
- Design an API's routes from a real need
- Handle business rules: limited seats, duplicates, cancellation
- Write automated tests for each route and each error
- Plug the API into a real Node.js server
The need and the routes
| Need | Route | Success | Possible errors |
|---|---|---|---|
| see the workshops and remaining seats | GET /api/workshops | 200 | — |
| register | POST /api/workshops/:id/registrations | 201 | 404 workshop, 422 data, 409 full or already registered |
| cancel | DELETE /api/workshops/:id/registrations/:email | 204 | 404 |
The 409 Conflict code signals a correct request that conflicts with the current state of the data: the workshop is full, or the student is already registered.
The registration is saved; the next request will get 409 Full.
Text description of the animation
- We first check that the requested workshop exists.
- The name is present and the e-mail address has a plausible form.
- At least one seat is left.
- The same student cannot take two seats.
- The registration is saved; the next request will get 409 Full.
The API's code
function createApi() {
const workshops = [
{ id: 1, title: "Python: a hangman game", seats: 3, registered: [] },
{ id: 2, title: "Build your web page", seats: 1, registered: [] },
];
const find = (id) => workshops.find((w) => w.id === Number(id));
const validEmail = (e) => typeof e === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
return {
list() {
return { status: 200, body: workshops.map((w) => ({ id: w.id, title: w.title, remaining: w.seats - w.registered.length })) };
},
register({ id }, data) {
const workshop = find(id);
if (!workshop) return { status: 404, body: { error: "unknown workshop" } };
const errors = [];
if (typeof data.name !== "string" || !data.name.trim()) errors.push("name: required");
if (!validEmail(data.email)) errors.push("email: invalid address");
if (errors.length) return { status: 422, body: { errors } };
const email = data.email.toLowerCase();
if (workshop.registered.some((r) => r.email === email)) return { status: 409, body: { error: "already registered" } };
if (workshop.registered.length >= workshop.seats) return { status: 409, body: { error: "workshop full" } };
const registration = { name: data.name.trim(), email };
workshop.registered.push(registration);
return { status: 201, body: { workshop: workshop.id, ...registration } };
},
cancel({ id, email }) {
const workshop = find(id);
const index = workshop ? workshop.registered.findIndex((r) => r.email === decodeURIComponent(email).toLowerCase()) : -1;
if (index === -1) return { status: 404, body: { error: "unknown registration" } };
workshop.registered.splice(index, 1);
return { status: 204, body: null };
},
};
}
const api = createApi();
console.log(api.register({ id: "2" }, { name: "Awa", email: "awa@example.ml" }).status);
console.log(api.register({ id: "2" }, { name: "Kofi", email: "kofi@example.gh" }).body);
console.log(api.list().body);
201
{"error":"workshop full"}
[{"id":1,"title":"Python: a hangman game","remaining":3},{"id":2,"title":"Build your web page","remaining":0}]
createApi() returns a new object with its own data on each call: each test can start from a clean state. The e-mail address is saved in lowercase, so that Awa@Example.ml and awa@example.ml are recognised as the same student.
Testing the API
An automated test calls a function and checks that the result is the expected one. We write a small test function; real projects use a tool like Node.js's built-in test runner (node --test) or Vitest, which work the same way.
Plugging the API into Node.js
Once tested, the API is plugged into a server with the router from chapter 2. Only this part touches the network:
import { createServer } from "node:http";
const api = createApi();
const routes = [
{ method: "GET", pattern: "/api/workshops", handle: () => api.list() },
{ method: "POST", pattern: "/api/workshops/:id/registrations", handle: (p, d) => api.register(p, d) },
{ method: "DELETE", pattern: "/api/workshops/:id/registrations/:email", handle: (p) => api.cancel(p) },
];
createServer(async (req, res) => {
let text = "";
for await (const chunk of req) text += chunk;
let data = {};
try { if (text) data = JSON.parse(text); }
catch { res.writeHead(400).end('{"error":"invalid JSON"}'); return; }
// router from chapter 2, extended to also pass the data: route.handle(params, data)
const { status, body } = router(req.method, req.url, data);
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
res.end(status === 204 ? undefined : JSON.stringify(body));
}).listen(3000, () => console.log("Club API on http://localhost:3000"));
Test it from a terminal with curl:
curl -X POST http://localhost:3000/api/workshops/1/registrations \
-H "Content-Type: application/json" \
-d '{"name":"Awa","email":"awa@example.ml"}'
Your turn
Worked exercise
Project: the club API's tests
Write a test(name, check) function that prints ✓ name if the check returns true and ✗ name otherwise, then write at least five tests, each with its own API: successful registration, unknown workshop, invalid e-mail, duplicate (even with uppercase letters), cancellation then re-registration.
Hint 1
const api = createApi();: no test sees another's registrations.Hint 2
() => api.register(...).status === 201.Show the solution and common mistakes
function createApi() {
const workshops = [{ id: 1, title: "Python", seats: 2, registered: [] }];
const find = (id) => workshops.find((w) => w.id === Number(id));
const validEmail = (e) => typeof e === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
return {
register({ id }, d) {
const workshop = find(id);
if (!workshop) return { status: 404 };
if (typeof d.name !== "string" || !d.name.trim() || !validEmail(d.email)) return { status: 422 };
const email = d.email.toLowerCase();
if (workshop.registered.some((r) => r.email === email)) return { status: 409, body: { error: "already registered" } };
if (workshop.registered.length >= workshop.seats) return { status: 409, body: { error: "workshop full" } };
workshop.registered.push({ name: d.name.trim(), email });
return { status: 201 };
},
cancel({ id, email }) {
const workshop = find(id);
const i = workshop ? workshop.registered.findIndex((x) => x.email === email.toLowerCase()) : -1;
if (i === -1) return { status: 404 };
workshop.registered.splice(i, 1);
return { status: 204 };
},
};
}
function test(name, check) {
console.log(check() ? "✓" : "✗", name);
}
const awa = { name: "Awa", email: "awa@example.ml" };
test("successful registration", () => createApi().register({ id: "1" }, awa).status === 201);
test("unknown workshop → 404", () => createApi().register({ id: "9" }, awa).status === 404);
test("invalid e-mail → 422", () => createApi().register({ id: "1" }, { name: "Awa", email: "awa" }).status === 422);
test("uppercase duplicate → 409", () => {
const api = createApi();
api.register({ id: "1" }, awa);
return api.register({ id: "1" }, { name: "Awa", email: "AWA@example.ml" }).status === 409;
});
test("cancel then register again", () => {
const api = createApi();
api.register({ id: "1" }, awa);
return api.cancel({ id: "1", email: "awa@example.ml" }).status === 204
&& api.register({ id: "1" }, awa).status === 201;
});
✓ successful registration
✓ unknown workshop → 404
✓ invalid e-mail → 422
✓ uppercase duplicate → 409
✓ cancel then register again
Common mistakes:
- Testing only the case that works: errors (404, 409, 422) are what breaks most often when code changes.
- Only checking a duplicate's status: also check that the workshop did not lose a seat along the way.
- Forgetting uppercase letters in the e-mail: without
toLowerCase(), the same student can take two seats.
Summary
- 1An API is designed by listing the needs, then the routes, the successes and the errors of each.
- 2409 Conflict signals a valid request that contradicts the state of the data: full or duplicate.
- 3A factory like createApi() gives each test its own data.
- 4An automated test also checks error cases, not only the case that works.
- 5Only a small piece of code touches the network; everything else is made of testable functions.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.