Build a REST API for a Todo App With Node.js
Build a REST API for a todo app with node:http, a tiny router, validation, correct status codes and tests that use node:test and fetch.

A todo API is the standard exercise for a reason: it has every verb, every status code you will use for years, and a data shape small enough to hold in your head. It is also where habits form. Return 200 for everything and you will do it in the real service too. This post builds the API on Node.js 26 with only node:http, writes a 30-line router so you see what a framework does for you, validates input, uses the right status codes and finishes with tests that run on node:test and the built-in fetch. Nothing here needs npm install.
The routes
A todo has an id, a title, a done flag and a creation time. The API follows the usual resource shape.
| Method and path | Purpose | Success status |
|---|---|---|
GET /todos | list, optionally ?done=true | 200 |
POST /todos | create | 201 |
GET /todos/:id | read one | 200 |
PATCH /todos/:id | change title or done | 200 |
DELETE /todos/:id | remove | 204 |
Anything that targets a missing todo answers 404, and a body that fails validation answers 422. Many APIs use 400 for both, but 422 says "I understood the request and the content is wrong", which lets a client tell a malformed JSON body (400) from a valid one with a bad field.
A tiny router
Frameworks give you routing as a feature, and it is easy to write the part you need. The router below stores a list of routes, each with a method, a pattern and a handler. A pattern like /todos/:id is compiled into a regular expression once, not on every request.
export function createRouter() {
const routes = [];
function add(method, path, handler) {
const names = [];
const source = path.replace(/:(\w+)/g, (_, name) => {
names.push(name);
return "([^/]+)";
});
routes.push({ method, regex: new RegExp(`^${source}$`), names, handler });
}
function match(method, pathname) {
let pathMatched = false;
for (const route of routes) {
const m = route.regex.exec(pathname);
if (!m) continue;
pathMatched = true;
if (route.method !== method) continue;
const params = Object.fromEntries(route.names.map((n, i) => [n, m[i + 1]]));
return { handler: route.handler, params };
}
return { notAllowed: pathMatched };
}
return { add, match };
}match tracks whether the path matched any route with a different method. That lets the server answer 405 Method Not Allowed for PUT /todos instead of a misleading 404. It is a small thing, and it is the difference between an API that explains itself and one that makes you read the source.
The store
Persistence is not the point of this post, so the todos live in a Map behind a few functions. The functions are the interface, and swapping in a database later means rewriting this one file.
import { randomUUID } from "node:crypto";
const todos = new Map();
export function list({ done } = {}) {
const all = [...todos.values()];
return done === undefined ? all : all.filter((t) => t.done === done);
}
export function find(id) {
return todos.get(id);
}
export function create({ title }) {
const todo = { id: randomUUID(), title, done: false, createdAt: new Date().toISOString() };
todos.set(todo.id, todo);
return todo;
}
export function update(id, changes) {
const todo = todos.get(id);
if (!todo) return undefined;
Object.assign(todo, changes);
return todo;
}
export function remove(id) {
return todos.delete(id);
}randomUUID comes from node:crypto and gives ids that cannot be guessed, which matters the moment a todo is private. Sequential integers invite a client to try the next one.
Validation
Validate at the edge and keep the rules in one function, so handlers can trust what they receive. The function returns an object of problems, which becomes the response body.
export function validateNew(body) {
const problems = {};
if (typeof body.title !== "string" || body.title.trim() === "") {
problems.title = "must be a non-empty string";
} else if (body.title.length > 200) {
problems.title = "must be 200 characters or fewer";
}
return problems;
}
export function validatePatch(body) {
const problems = {};
const keys = Object.keys(body);
if (keys.length === 0) problems.body = "send title or done";
if ("title" in body && (typeof body.title !== "string" || body.title.trim() === "")) {
problems.title = "must be a non-empty string";
}
if ("done" in body && typeof body.done !== "boolean") {
problems.done = "must be true or false";
}
for (const key of keys) {
if (key !== "title" && key !== "done") problems[key] = "is not a todo field";
}
return problems;
}The last loop is worth keeping. Rejecting unknown fields stops a client from sending {"id": "..."} or {"createdAt": ...} and quietly overwriting something it should not own. The pattern has a name, mass assignment, and it has caused real breaches in frameworks that copy a request body onto a model.
The server
Now wire it together. The handler reads the body, finds the route, runs it and turns whatever comes back into a response. Handlers return a [status, body] pair, which keeps them free of res and easy to test.
import { createServer } from "node:http";
import { createRouter } from "./router.js";
import * as store from "./store.js";
import { validateNew, validatePatch } from "./validate.js";
const router = createRouter();
router.add("GET", "/todos", ({ query }) => {
const done = query.get("done");
return [200, store.list({ done: done === null ? undefined : done === "true" })];
});
router.add("POST", "/todos", ({ body }) => {
const problems = validateNew(body);
if (Object.keys(problems).length) return [422, { errors: problems }];
return [201, store.create(body)];
});
router.add("GET", "/todos/:id", ({ params }) => {
const todo = store.find(params.id);
return todo ? [200, todo] : [404, { error: "todo not found" }];
});
router.add("PATCH", "/todos/:id", ({ params, body }) => {
const problems = validatePatch(body);
if (Object.keys(problems).length) return [422, { errors: problems }];
const todo = store.update(params.id, body);
return todo ? [200, todo] : [404, { error: "todo not found" }];
});
router.add("DELETE", "/todos/:id", ({ params }) => {
return store.remove(params.id) ? [204, null] : [404, { error: "todo not found" }];
});
async function readBody(req) {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const text = Buffer.concat(chunks).toString();
return text ? JSON.parse(text) : {};
}
export function createApp() {
return createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const found = router.match(req.method, url.pathname);
let status = 404;
let payload = { error: "not found" };
try {
if (found.handler) {
const body = ["POST", "PATCH"].includes(req.method) ? await readBody(req) : {};
[status, payload] = found.handler({ params: found.params, query: url.searchParams, body });
} else if (found.notAllowed) {
[status, payload] = [405, { error: "method not allowed" }];
}
} catch (err) {
[status, payload] = err instanceof SyntaxError
? [400, { error: "invalid JSON" }]
: [500, { error: "server error" }];
}
res.writeHead(status, { "content-type": "application/json" });
res.end(payload === null ? undefined : JSON.stringify(payload));
});
}
if (import.meta.main) {
createApp().listen(3000, () => console.log("listening on 3000"));
}Two details need a note. A 204 response must not carry a body, which is why DELETE returns null and the code passes undefined to res.end. And createApp returns the server without starting it, so a test can listen on a random port while the real entry point listens on 3000. The import.meta.main guard, available in current Node.js releases, runs the listener only when the file is the entry point, which replaces the old require.main === module check.
Trying it by hand
Start the server and create a todo.
node app.js
curl -si -X POST localhost:3000/todos -d '{"title":"Write the post"}'HTTP/1.1 201 Created
content-type: application/json
{"id":"6f0a9c1e-3b52-4c1c-9d3e-1f6f6a2f7a10","title":"Write the post","done":false,"createdAt":"2026-11-20T10:00:00.000Z"}The id and timestamp will differ on your machine. Now a bad request, which shows the validation shape.
curl -s -X PATCH localhost:3000/todos/6f0a9c1e-3b52-4c1c-9d3e-1f6f6a2f7a10 -d '{"done":"yes","id":"x"}'{"errors":{"done":"must be true or false","id":"is not a todo field"}}Tests with node:test and fetch
The runner and fetch are both built in, so the tests need no libraries. Each test file starts the app on port 0, which asks the operating system for any free port, and reads the real port back from the server.
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { createApp } from "./app.js";
let server;
let base;
before(async () => {
server = createApp();
await new Promise((resolve) => server.listen(0, resolve));
base = `http://localhost:${server.address().port}`;
});
after(() => server.close());
test("creates and reads a todo", async () => {
const created = await fetch(`${base}/todos`, {
method: "POST",
body: JSON.stringify({ title: "Buy milk" }),
});
assert.equal(created.status, 201);
const todo = await created.json();
assert.equal(todo.done, false);
const read = await fetch(`${base}/todos/${todo.id}`);
assert.equal(read.status, 200);
assert.equal((await read.json()).title, "Buy milk");
});
test("rejects an empty title with 422", async () => {
const res = await fetch(`${base}/todos`, { method: "POST", body: JSON.stringify({ title: " " }) });
assert.equal(res.status, 422);
assert.deepEqual(await res.json(), { errors: { title: "must be a non-empty string" } });
});
test("answers 404 for a missing todo and 405 for a bad method", async () => {
assert.equal((await fetch(`${base}/todos/nope`)).status, 404);
assert.equal((await fetch(`${base}/todos`, { method: "PUT" })).status, 405);
});Run them with node --test.
✔ creates and reads a todo (12.4ms)
✔ rejects an empty title with 422 (3.1ms)
✔ answers 404 for a missing todo and 405 for a bad method (2.7ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0Timings in parentheses vary from run to run. The shape is what to check.
What this version leaves out
An honest list helps more than a claim of completeness. The router reads no query-string types beyond what you parse by hand. There is no authentication, so every client sees every todo. The body reader has no size limit, so a large request will be buffered whole, and you should cap it as the URL shortener post does. There is no pagination, so GET /todos returns everything. And the data disappears on restart.
If you outgrow the router, a framework such as Hono or Fastify gives you schema validation, hooks and better error handling, and the handler shape you wrote here ports over almost unchanged. Writing it once by hand is how you learn which of those features you actually need.
Habits worth keeping from this exercise
A few decisions in this small API carry over to every service you will write. First, keep handlers free of the response object. A handler that returns a status and a body can be called from a test with no server at all, and the one place that touches res is the place that handles headers, serialization and errors. When you later add a header such as x-request-id, you change one function instead of fifty.
Second, decide what your error body looks like on day one and never change its shape. Here every error is an object with either error or errors, and clients can rely on that. APIs that return a string in one place, an array in another and an HTML page from a crashed proxy force every client to defend against all three.
Third, treat IDs as opaque. A client should never build a todo address by hand or assume it is a number, and returning a UUID makes that assumption impossible. If you later move to a database that assigns its own keys, nothing a client stored breaks.
Fourth, separate what the client may change from what the server owns. The validation here accepts only title and done, and that single rule means createdAt and id are server facts. The day you add an owner field, you will be glad the allow-list is already there, because the default for a new field becomes "not writable" and you have to opt in deliberately.
Finally, write the test before you write the second route. The first test tells you whether the server is testable at all. In this design it was, because createApp returned a server without listening, and that one choice is what made every later check a few lines long.


