Eleven lessons of loose pieces: the event loop, promises, files, bare HTTP, Express taken apart, errors and shutdown. Here they meet in one thing that starts, answers, and shuts down without losing requests.
The API is small on purpose: one resource, books, with its CRUD, data in memory and no database. Five endpoints and six files. What you learn isn't the size, it's the shape: every piece sits where it sits for a reason, and by the end you'll be able to say which.
Design before writing
Before the first import, the table. What resource there is, which routes, what each returns and with which code. That's the "OpenAPI-lite" the plan asks for: not a hundred-line document, just the contract in a table.
| Method | Path | Body | Response |
|---|---|---|---|
| GET | /api/books | — | 200 list |
| GET | /api/books/:id | — | 200 one · 404 |
| POST | /api/books | title, author, pages | 201 created · 400 |
| PATCH | /api/books/:id | whichever fields change | 200 updated · 404 |
| DELETE | /api/books/:id | — | 204 · 404 |
And the data model, which is the resource's contract: id (string, assigned by the server), title and author (non-empty text) and pages (positive integer). pages arrives as a string over HTTP, so it gets coerced. Nothing else: every field that isn't here is a field somebody will have to guess.
That five-minute exercise saves an afternoon. The 404s above, for instance, are the ones people forget: the table forces you to decide what happens when the id doesn't exist, instead of finding out on the first test.
The structure
Six code files and one directory per concept:
src/ ├── app.js builds the app, doesn't listen ├── server.js starts it and handles signals ├── config.js validates configuration at startup ├── errors.js AppError, NotFoundError, ValidationError ├── middleware/ │ ├── requestId.js identifier and log per request │ └── errors.js closing 404 and central handler └── books/ ├── routes.js which URL calls which ├── controller.js HTTP ↔ service, and validation ├── service.js rules, unaware that HTTP exists └── repository.js storage, today a Map in memory And three files that aren't code but decide whether the repository is any use:
.env.example the keys you need, with fake values .gitignore node_modules/ and .env README.md how to start it and which endpoints it has The .gitignore isn't optional. Without it, the first commit uploads the whole node_modules and, if you're not careful, the .env with the secrets. And .env.example is the contract from the files lesson: whoever clones the repository knows what they have to create without asking you.
If Git is something you've heard of and you've been copying the same three commands, or if you use it daily and never understood what a rebase does underneath, the Git from scratch course starts at what a repository is and goes as far as rewriting history without breaking it, through branches, remotes and team workflows.
The rule that orders everything: each layer knows only the one inside it. Routes call the controller, the controller the service, the service the repository. The repository doesn't know Express exists, so tomorrow it can be Postgres without touching anything else.
And app.js separate from server.js isn't fussiness: app.js returns the application without opening a port, so a test can import it and throw requests at it. server.js is the only thing that listens and the only thing that knows about signals.
Configuration and startup
// src/config.js const port = Number(process.env.PORT ?? 3000); if (!Number.isInteger(port) || port < 1 || port > 65535) { console.error("invalid PORT:", process.env.PORT); process.exit(1); } export const config = { port }; Validate at startup, like in the files lesson: if the configuration is wrong, the process dies before there's anything to break. And server.js with both signals:
// src/server.js const server = app.listen(config.port, () => logger.info(`listening on ${config.port}`)); for (const signal of ["SIGTERM", "SIGINT"]) { process.on(signal, () => { logger.info({ signal }, "closing"); server.close(() => process.exit(0)); }); } And the scripts, which are the project's interface for whoever runs it:
{ "scripts": { "start": "node src/server.js", "dev": "node --watch src/server.js" } } --watch ships with the runtime: no nodemon to install.
Errors, in one place
errors.js defines the vocabulary, and every domain error carries its HTTP code and its business code:
// src/errors.js export class NotFoundError extends AppError { constructor(resource) { super(`No such ${resource}`, 404, "not_found"); } } The controller validates and, when something doesn't add up, throws ValidationError with the list of problems. The service throws NotFoundError when the id doesn't exist. Nobody picks HTTP codes outside the central handler, and that's what makes twenty routes behave the same.
The resource, layer by layer
The repository is a Map today and something else tomorrow; its contract is five functions:
// src/books/repository.js export function createRepository() { const books = new Map(); let nextId = 1; return { list: () => [...books.values()], find: (id) => books.get(id), create: (data) => { const book = { id: String(nextId++), ...data }; books.set(book.id, book); return book; }, update: (id, data) => { const book = { ...books.get(id), ...data, id }; books.set(id, book); return book; }, remove: (id) => books.delete(id), }; } The service adds the only rule there is: if it doesn't exist, it's an error.
// src/books/service.js get: (id) => { const book = repository.find(id); if (!book) throw new NotFoundError(`book ${id}`); return book; }, The controller translates and validates. And here you can see what Zod was for:
// src/books/controller.js const BookSchema = z.object({ title: z.string().min(1), author: z.string().min(1), pages: z.coerce.number().int().positive(), }); const PatchSchema = BookSchema.partial(); Two schemas, not one: the create one demands all three fields, the PATCH one accepts any of them because partial() makes them optional. It's the difference between "don't send me an empty book" and "change only the pages".
And it's PATCH, not PUT, for that same reason: PUT means "replace the whole resource with this", so a partial body would leave half-written books. PATCH says "change what I send you", which is what the controller does.
And the routes, seven lines:
// src/books/routes.js const routes = Router(); routes.get("/", controller.list); routes.get("/:id", controller.get); routes.post("/", controller.create); routes.patch("/:id", controller.update); routes.delete("/:id", controller.remove); Testing it end to end
With the server running, the full battery. First the heartbeat, which is what the orchestrator asks to know whether the process is alive:
curl -s http://localhost:3000/health {"ok":true} Then the empty resource and creation:
curl -s http://localhost:3000/api/books curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "Content-Type: application/json" -d '{"title":"Emma","author":"Austen","pages":"474"}' http://localhost:3000/api/books curl -s -X POST -H "Content-Type: application/json" -d '{"title":"Dracula","author":"Stoker","pages":418}' http://localhost:3000/api/books {"data":[]} 201 {"data":{"id":"2","title":"Dracula","author":"Stoker","pages":418}} Look at "pages":"474": it arrived as a string and came out as a number. That's z.coerce, and it's exactly what HTTP does to everything.
Now the case that breaks other people's APIs: invalid data.
curl -s -w "\n%{http_code}\n" -X POST -H "Content-Type: application/json" -d '{"title":"","pages":-3}' http://localhost:3000/api/books {"error":"invalid_input","message":"Invalid input","details":[{"field":"title","message":"Too small: expected string to have >=1 characters"},{"field":"author","message":"Invalid input: expected string, received undefined"},{"field":"pages","message":"Too small: expected number to be >0"}]} 400 Three problems, each with its field, in one response. Whoever consumes that API can paint the error next to the right input without guessing.
And the rest of the cycle:
curl -s http://localhost:3000/api/books curl -s -X PATCH -H "Content-Type: application/json" -d '{"pages":480}' http://localhost:3000/api/books/1 curl -s -o /dev/null -w "%{http_code}\n" -X DELETE http://localhost:3000/api/books/2 curl -s -w " %{http_code}\n" http://localhost:3000/api/books/2 curl -s -w " %{http_code}\n" http://localhost:3000/api/nope {"data":[{"id":"1","title":"Emma","author":"Austen","pages":474},{"id":"2","title":"Dracula","author":"Stoker","pages":418}]} {"data":{"id":"1","title":"Emma","author":"Austen","pages":480}} 204 {"error":"not_found","message":"No such book 2"} 404 {"error":"not_found","path":"/api/nope"} 404 Five responses, five decisions taken before writing code: 204 with no body when deleting, 404 with a message when the resource doesn't exist, and a different 404 — with path instead of message — when what doesn't exist is the route. Behind it, every request leaves a log line with the same identifier the x-request-id header returns.
What this API is missing
It's an honest API and an incomplete one, and knowing what's missing is part of the job:
- A real database. The
Mapempties on restart. Swapping the repository for Postgres doesn't touch the controller or the routes: that's what the layer split bought. - Authentication. Right now anyone can delete anything. API keys, JWT and permissions are their own chapter.
- Tests. There isn't a single test, and with
node:testnothing needs installing. ThecreateAppfactory exists precisely for that. - Types. This project is plain JavaScript. Types don't change what it does, they change what your editor warns you about before running it.
- Deployment. Containers, real environment variables, a proxy in front.
All of that has a course of its own. This API is the starting material for two roads:
- Database, authentication, tests and production on top of an API like this one: the Backend APIs course, once it ships.
- Types on what you just built, without changing its behaviour: the TypeScript course, once it ships.
What you take from this lesson
- An API is designed in a table before it's written: routes, bodies, codes.
- Each layer knows only the one inside it; the repository doesn't know HTTP exists.
-
app.jsbuilds without listening,server.jslistens and handles signals: that's what makes the project testable. - Configuration is validated at startup, just like data at the boundary.
- Domain errors carry their code; the central handler is the only one deciding HTTP.
- Two Zod schemas per resource: a complete one and a partial one for
PATCH. -
z.coerceturns"474"into474, which is what arrives over HTTP. -
204when deleting,201when creating,400with per-field details. - Every request leaves a log with the same identifier as the
x-request-idheader. - A project pushed to GitHub needs
.gitignore,.env.exampleand a README; without the first one, the first commit uploads secrets. - Git isn't explained here: the Git course covers it from what a repository is to rewriting history.
-
/healthso the orchestrator knows whether the process is still alive. - You know what it's missing: database, authentication, tests, types and deployment.
Two lessons left, and neither touches the API again: one is everything the runtime gives you that you keep installing anyway — the test runner, watch mode, environment files, command-line arguments and threads — and the other is the half of the job you haven't done yet: calling other services. Because a backend that only talks to its own database isn't a backend.
Never stop coding!

