CRUD API
CRUD — Create, Read, Update, Delete — is what most API endpoints do. In this lesson you'll build a complete CRUD API for a todos resource, backed by an in-memory store. Swapping the store for a real database later only changes one module.
Step 1: a store with a clean interface
Keep data access out of your route handlers. A small store object with async methods mimics what a database layer looks like:
function createTodoStore() {
const todos = new Map();
let nextId = 1;
return {
async list() { return [...todos.values()]; },
async get(id) { return todos.get(id) ?? null; },
async create({ title }) {
const todo = { id: nextId++, title, done: false };
todos.set(todo.id, todo);
return todo;
},
async update(id, changes) {
const todo = todos.get(id);
if (!todo) return null;
Object.assign(todo, changes);
return todo;
},
async remove(id) { return todos.delete(id); },
};
}Because the methods are async, your routes already await them — exactly the code you'd write against PostgreSQL or MongoDB.
Step 2: the routes
const express = require('express');
function createTodoStore() {
const todos = new Map();
let nextId = 1;
return {
async list() { return [...todos.values()]; },
async get(id) { return todos.get(id) ?? null; },
async create({ title }) {
const todo = { id: nextId++, title, done: false };
todos.set(todo.id, todo);
return todo;
},
async update(id, changes) {
const todo = todos.get(id);
if (!todo) return null;
Object.assign(todo, changes);
return todo;
},
async remove(id) { return todos.delete(id); },
};
}
const store = createTodoStore();
const app = express();
app.use(express.json());
app.get('/todos', async (req, res) => res.json(await store.list()));
app.get('/todos/:id', async (req, res) => {
const todo = await store.get(Number(req.params.id));
if (!todo) return res.status(404).json({ error: 'Todo not found' });
res.json(todo);
});
app.post('/todos', async (req, res) => {
const title = req.body?.title;
if (typeof title !== 'string' || !title.trim()) {
return res.status(400).json({ error: 'title is required' });
}
const todo = await store.create({ title: title.trim() });
res.status(201).location(`/todos/${todo.id}`).json(todo);
});
app.patch('/todos/:id', async (req, res) => {
const changes = {};
if (typeof req.body?.title === 'string') changes.title = req.body.title;
if (typeof req.body?.done === 'boolean') changes.done = req.body.done;
const todo = await store.update(Number(req.params.id), changes);
if (!todo) return res.status(404).json({ error: 'Todo not found' });
res.json(todo);
});
app.delete('/todos/:id', async (req, res) => {
const removed = await store.remove(Number(req.params.id));
res.sendStatus(removed ? 204 : 404);
});
// --- a small client that exercises every endpoint ---
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const call = async (method, path, body) => {
const res = await fetch(base + path, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
console.log(`${method} ${path}`.padEnd(17), res.status, text);
};
await call('POST', '/todos', { title: 'Learn routing' });
await call('POST', '/todos', { title: 'Write tests' });
await call('POST', '/todos', { title: ' ' });
await call('GET', '/todos');
await call('PATCH', '/todos/1', { done: true });
await call('DELETE', '/todos/2');
await call('GET', '/todos/2');
await call('GET', '/todos');
server.close();
});POST /todos 201 {"id":1,"title":"Learn routing","done":false}
POST /todos 201 {"id":2,"title":"Write tests","done":false}
POST /todos 400 {"error":"title is required"}
GET /todos 200 [{"id":1,"title":"Learn routing","done":false},{"id":2,"title":"Write tests","done":false}]
PATCH /todos/1 200 {"id":1,"title":"Learn routing","done":true}
DELETE /todos/2 204
GET /todos/2 404 {"error":"Todo not found"}
GET /todos 200 [{"id":1,"title":"Learn routing","done":true}]
What each handler teaches
| Endpoint | Detail worth copying |
|---|---|
GET /todos/:id |
convert the id, return 404 with a JSON error when missing |
POST /todos |
validate before storing, trim strings, reply 201 + Location |
PATCH /todos/:id |
copy only known fields with the right types (never Object.assign(todo, req.body)) |
DELETE /todos/:id |
204 with no body, 404 if it didn't exist |
Note:
Object.assign(todo, req.body)is a classic security hole called mass assignment: a client could send{ "id": 99, "ownerId": 1, "isAdmin": true }and overwrite fields it should never control. Always pick allowed fields explicitly.
Step 3: a reusable id parser
The Number(req.params.id) dance repeats in every route. router.param centralises it — invalid ids get a 400 before any handler runs:
const express = require('express');
const router = express.Router();
router.param('id', (req, res, next, raw) => {
const id = Number(raw);
if (!Number.isSafeInteger(id) || id < 1) return res.status(400).json({ error: `invalid id "${raw}"` });
req.todoId = id;
next();
});
router.get('/:id', (req, res) => res.json({ lookingFor: req.todoId }));
const app = express();
app.use('/todos', router);
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/todos/`;
for (const id of ['5', 'abc', '0']) {
const res = await fetch(base + id);
console.log(id.padEnd(4), res.status, await res.text());
}
server.close();
});5 200 {"lookingFor":5}
abc 400 {"error":"invalid id \"abc\""}
0 400 {"error":"invalid id \"0\""}
From memory to a database
The in-memory store disappears when the process restarts, and it isn't shared between multiple server instances. For real projects, replace createTodoStore() with a module that talks to a database:
| Need | Popular choice |
|---|---|
| relational, SQL | PostgreSQL with pg, or an ORM such as Prisma, Drizzle or TypeORM |
| document store | MongoDB with the official driver or Mongoose |
| embedded / local | SQLite (node:sqlite in Node 22+, or better-sqlite3) |
| cache / sessions | Redis |
Because the routes only call store.list(), store.create() and so on, none of them have to change.
Test yourself
Why is Object.assign(todo, req.body) dangerous in an update handler?
- It is slow
- Clients can overwrite fields they shouldn't control (mass assignment)
- It fails on nested objects
- It changes the status code
What should DELETE /todos/2 return after successfully deleting the todo?
- 200 with the deleted todo or 204 with no body
- 201
- 404
- 302 redirect
What is the benefit of wrapping data access in a store object with async methods?
- It makes requests faster
- Routes don't change when you swap the in-memory store for a database
- It removes the need for validation
- Express requires it