Building a REST API with Node.js · Lesson 10 of 30
Build a REST API with Node.js and Express
Time to put the design rules together into a real, structured API. We'll build a tasks API – create, list, read, update and delete tasks – with Node.js and Express 5, the most widely used Node web framework. The structure you set up here scales from a weekend project to a production service.
In this lesson
- Project setup with ES modules
- Splitting the API into a router and a data layer
- All five CRUD endpoints
- Exercising the whole API with curl
Setup
mkdir tasks-api && cd tasks-api
npm init -y
npm pkg set type=module # use import/export
npm install express
node --watch server.js # restarts on every save (Node 22+)
tasks-api
- server.js – creates the app, mounts routers, starts listening
- routes/tasks.js – HTTP layer: URLs, status codes, request/response
- data/tasks.js – data layer: in-memory now, a database later
The data layer
// data/tasks.js
// In-memory store with the same shape a database repository would have.
const tasks = new Map();
let nextId = 1;
export function listTasks({ done } = {}) {
const all = [...tasks.values()];
return done === undefined ? all : all.filter((t) => t.done === done);
}
export function getTask(id) {
return tasks.get(id) ?? null;
}
export function createTask({ title, dueDate = null }) {
const task = { id: nextId++, title, done: false, dueDate };
tasks.set(task.id, task);
return task;
}
export function updateTask(id, changes) {
const current = tasks.get(id);
if (!current) return null;
const updated = { ...current, ...changes, id };
tasks.set(id, updated);
return updated;
}
export function deleteTask(id) {
return tasks.delete(id);
}
Keeping data access behind functions means the routes never care whether tasks live in a Map, PostgreSQL or MongoDB. Swapping the store later changes one file.
The router
// routes/tasks.js
import { Router } from 'express';
import * as store from '../data/tasks.js';
const router = Router();
const parseId = (req) => Number.parseInt(req.params.id, 10);
router.get('/', (req, res) => {
const done = req.query.done === undefined ? undefined : req.query.done === 'true';
res.json({ data: store.listTasks({ done }) });
});
router.get('/:id', (req, res) => {
const task = store.getTask(parseId(req));
if (!task) return res.status(404).json({ error: 'Task not found' });
res.json(task);
});
router.post('/', (req, res) => {
if (!req.body?.title) return res.status(400).json({ error: 'title is required' });
const task = store.createTask(req.body);
res.status(201).location(`/api/tasks/${task.id}`).json(task);
});
router.patch('/:id', (req, res) => {
const { title, done, dueDate } = req.body ?? {};
const task = store.updateTask(parseId(req), Object.fromEntries(
Object.entries({ title, done, dueDate }).filter(([, v]) => v !== undefined) // only allowed fields
));
if (!task) return res.status(404).json({ error: 'Task not found' });
res.json(task);
});
router.delete('/:id', (req, res) => {
if (!store.deleteTask(parseId(req))) return res.status(404).json({ error: 'Task not found' });
res.status(204).end();
});
export default router;
The server
// server.js
import express from 'express';
import tasksRouter from './routes/tasks.js';
const app = express();
app.use(express.json()); // parse JSON request bodies
app.use('/api/tasks', tasksRouter); // everything under /api/tasks
app.get('/api/health', (req, res) => res.json({ status: 'ok' }));
const port = process.env.PORT ?? 3000;
app.listen(port, () => console.log(`Tasks API on http://localhost:${port}`));
$ curl -X POST http://localhost:3000/api/tasks -H 'Content-Type: application/json' -d '{"title":"Write API docs","dueDate":"2026-11-20"}'
HTTP/1.1 201 Created
Location: /api/tasks/1
Content-Type: application/json; charset=utf-8
{
"id": 1,
"title": "Write API docs",
"done": false,
"dueDate": "2026-11-20"
}
$ curl -X POST http://localhost:3000/api/tasks -H 'Content-Type: application/json' -d '{"title":"Add pagination"}'
HTTP/1.1 201 Created
Location: /api/tasks/2
Content-Type: application/json; charset=utf-8
{
"id": 2,
"title": "Add pagination",
"done": false,
"dueDate": null
}
$ curl -X PATCH http://localhost:3000/api/tasks/1 -H 'Content-Type: application/json' -d '{"done":true,"id":999}'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": 1,
"title": "Write API docs",
"done": true,
"dueDate": "2026-11-20"
}
$ curl 'http://localhost:3000/api/tasks?done=false'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"data": [
{
"id": 2,
"title": "Add pagination",
"done": false,
"dueDate": null
}
]
}
$ curl -X DELETE http://localhost:3000/api/tasks/2
HTTP/1.1 204 No Content
$ curl http://localhost:3000/api/tasks/2
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "Task not found"
}
$ curl -X POST http://localhost:3000/api/tasks -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{
"error": "title is required"
}- The PATCH tried to sneak in
"id": 999; only allowed fields are copied, so the id stayed 1. Never spread a request body straight into your data – that's how "mass assignment" vulnerabilities happen. - Create returns
201with aLocation; delete returns204; reading a deleted task returns404. - The validation here is minimal on purpose – the next lesson replaces it with proper schema validation.
Layers keep APIs maintainable
Routes handle HTTP (parse, validate, choose status codes); a service or data layer holds business logic and storage. When you add a database, authentication or a second API version, each change stays in its own layer.
Practice
Try it yourself
Add
GET /api/tasks/statsreturning{ total, done, open }. Where must the route go so/statsisn't treated as an id?Show solution
// server.js import express from 'express'; const app = express(); const tasks = [{ id: 1, done: true }, { id: 2, done: false }, { id: 3, done: false }]; // specific paths before parameterised ones app.get('/api/tasks/stats', (req, res) => { const done = tasks.filter((t) => t.done).length; res.json({ total: tasks.length, done, open: tasks.length - done }); }); app.get('/api/tasks/:id', (req, res) => { const task = tasks.find((t) => t.id === Number(req.params.id)); return task ? res.json(task) : res.status(404).json({ error: 'Task not found' }); }); app.listen(process.env.PORT ?? 3000);$ curl http://localhost:3000/api/tasks/stats HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "total": 3, "done": 1, "open": 2 }Define
/statsbefore/:id; Express matches routes in order.
Quick check
What does app.use('/api/tasks', router) do?
Mounts the router so its paths are relative to /api/tasks.
Why not updateTask(id, req.body)?
Clients could overwrite fields they shouldn't (id, owner, role) – copy allowed fields only.
Which middleware parses JSON bodies?
express.json().
Summary
- Structure an Express API as server → routers → data layer.
- Implement CRUD with the right methods and codes: 201 + Location, 200, 204, 404.
- Copy only allowed fields from request bodies; order specific routes before parameterised ones.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.