Project: a CRUD API
Overview
Time to combine everything from the last two chapters into a real, working API. You’ll build a courses API with five endpoints, input validation, layered structure and consistent errors. It stores data in memory for now; in the next chapter you’ll replace one file — the repository — to store data in PostgreSQL instead, without touching anything else.
| Method | Path | Does |
|---|---|---|
GET |
/api/v1/courses?level=&search=&page=&limit= |
list, filter and paginate |
GET |
/api/v1/courses/:id |
read one |
POST |
/api/v1/courses |
create |
PATCH |
/api/v1/courses/:id |
update some fields |
DELETE |
/api/v1/courses/:id |
delete |
Setup
mkdir courses-api && cd courses-api
npm init -y
npm install express zod
npm pkg set type=module scripts.dev="node --watch src/server.js" scripts.start="node src/server.js"Errors and middleware
// src/errors.js
export class HttpError extends Error {
constructor(status, message, details) {
super(message);
this.status = status;
this.details = details;
}
}// src/middleware.js
import { HttpError } from './errors.js';
export const validate = (schemas) => (req, res, next) => {
const details = [];
req.validated = {};
for (const part of ['params', 'query', 'body']) {
if (!schemas[part]) continue;
const result = schemas[part].safeParse(req[part] ?? {});
if (result.success) req.validated[part] = result.data;
else result.error.issues.forEach((i) => details.push({ in: part, path: i.path.join('.'), message: i.message }));
}
if (details.length) return next(new HttpError(400, 'Validation failed', details));
next();
};
export const notFound = (req, res, next) =>
next(new HttpError(404, `No route for ${req.method} ${req.originalUrl}`));
export function errorHandler(err, req, res, next) {
if (res.headersSent) return next(err);
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: { message: 'Body must be valid JSON' } });
}
if (err instanceof HttpError) {
return res.status(err.status).json({ error: { message: err.message, details: err.details } });
}
console.error(err);
res.status(500).json({ error: { message: 'Something went wrong' } });
}Schemas
// src/courses/courses.schemas.js
import { z } from 'zod';
const title = z.string().trim().min(3).max(120);
const description = z.string().trim().max(2000);
const level = z.enum(['Beginner', 'Intermediate', 'Advanced']);
export const createCourseSchema = z.object({
title,
description: description.default(''),
level: level.default('Beginner'),
});
// No defaults here: a PATCH must only change the fields that were sent
export const updateCourseSchema = z
.object({ title, description, level })
.partial()
.refine((d) => Object.keys(d).length > 0, 'Send at least one field');
export const idParams = z.object({ id: z.coerce.number().int().positive() });
export const listQuery = z.object({
level: level.optional(),
search: z.string().trim().max(100).optional(),
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(50).default(10),
});The repository (in memory, for now)
// src/courses/courses.repository.memory.js
export function makeMemoryCoursesRepo() {
const rows = new Map();
let nextId = 1;
return {
async list({ level, search, page, limit }) {
let items = [...rows.values()];
if (level) items = items.filter((c) => c.level === level);
if (search) items = items.filter((c) => c.title.toLowerCase().includes(search.toLowerCase()));
const total = items.length;
items = items.sort((a, b) => b.id - a.id).slice((page - 1) * limit, page * limit);
return { items, total };
},
async findById(id) {
return rows.get(id) ?? null;
},
async findByTitle(title) {
return [...rows.values()].find((c) => c.title.toLowerCase() === title.toLowerCase()) ?? null;
},
async insert(data) {
const now = new Date().toISOString();
const course = { id: nextId++, status: 'draft', ...data, createdAt: now, updatedAt: now };
rows.set(course.id, course);
return course;
},
async update(id, changes) {
const course = { ...rows.get(id), ...changes, updatedAt: new Date().toISOString() };
rows.set(id, course);
return course;
},
async remove(id) {
return rows.delete(id);
},
};
}All methods are async even though a Map doesn’t need it — so the PostgreSQL version can have exactly the same interface.
The service
// src/courses/courses.service.js
import { HttpError } from '../errors.js';
export function makeCoursesService({ coursesRepo }) {
return {
async list(query) {
const { items, total } = await coursesRepo.list(query);
return {
data: items,
page: { page: query.page, limit: query.limit, total, pages: Math.ceil(total / query.limit) },
};
},
async get(id) {
const course = await coursesRepo.findById(id);
if (!course) throw new HttpError(404, `Course ${id} not found`);
return course;
},
async create(data) {
if (await coursesRepo.findByTitle(data.title)) {
throw new HttpError(409, 'A course with this title already exists');
}
return coursesRepo.insert(data);
},
async update(id, changes) {
await this.get(id); // 404 if missing
if (changes.title) {
const other = await coursesRepo.findByTitle(changes.title);
if (other && other.id !== id) throw new HttpError(409, 'A course with this title already exists');
}
return coursesRepo.update(id, changes);
},
async remove(id) {
if (!(await coursesRepo.remove(id))) throw new HttpError(404, `Course ${id} not found`);
},
};
}The routes
// src/courses/courses.routes.js
import { Router } from 'express';
import { validate } from '../middleware.js';
import { createCourseSchema, updateCourseSchema, idParams, listQuery } from './courses.schemas.js';
export function makeCoursesRouter({ coursesService }) {
const router = Router();
router.get('/', validate({ query: listQuery }), async (req, res) => {
res.json(await coursesService.list(req.validated.query));
});
router.get('/:id', validate({ params: idParams }), async (req, res) => {
res.json(await coursesService.get(req.validated.params.id));
});
router.post('/', validate({ body: createCourseSchema }), async (req, res) => {
const course = await coursesService.create(req.validated.body);
res.status(201).location(`${req.baseUrl}/${course.id}`).json(course);
});
router.patch('/:id', validate({ params: idParams, body: updateCourseSchema }), async (req, res) => {
res.json(await coursesService.update(req.validated.params.id, req.validated.body));
});
router.delete('/:id', validate({ params: idParams }), async (req, res) => {
await coursesService.remove(req.validated.params.id);
res.sendStatus(204);
});
return router;
}The app and server
// src/app.js
import express from 'express';
import { makeCoursesRouter } from './courses/courses.routes.js';
import { makeCoursesService } from './courses/courses.service.js';
import { notFound, errorHandler } from './middleware.js';
export function createApp({ coursesRepo }) {
const app = express();
app.use(express.json({ limit: '100kb' }));
app.get('/health', (req, res) => res.json({ status: 'ok' }));
const coursesService = makeCoursesService({ coursesRepo });
app.use('/api/v1/courses', makeCoursesRouter({ coursesService }));
app.use(notFound);
app.use(errorHandler);
return app;
}// src/server.js
import { createApp } from './app.js';
import { makeMemoryCoursesRepo } from './courses/courses.repository.memory.js';
const port = Number(process.env.PORT ?? 3000);
createApp({ coursesRepo: makeMemoryCoursesRepo() }).listen(port, () => {
console.log(`Courses API on http://localhost:${port}`);
});Try it
npm run dev
curl -X POST localhost:3000/api/v1/courses \
-H 'Content-Type: application/json' \
-d '{"title":"Node.js","level":"Intermediate"}'
# 201 {"id":1,"status":"draft","title":"Node.js",…}
curl "localhost:3000/api/v1/courses?level=Intermediate&limit=5"
curl -X PATCH localhost:3000/api/v1/courses/1 -H 'Content-Type: application/json' -d '{"title":"Node.js in practice"}'
curl -X POST localhost:3000/api/v1/courses -H 'Content-Type: application/json' -d '{"title":"x"}'
# 400 {"error":{"message":"Validation failed","details":[{"in":"body","path":"title",…}]}}
curl -X DELETE -i localhost:3000/api/v1/courses/1 # 204
curl -i localhost:3000/api/v1/courses/1 # 404GUI clients such as Bruno, Insomnia, Postman or VS Code’s REST Client extension make this more comfortable, and let you save requests for later.
What you’ve built
A small API — but with the same architecture as large production systems: validated input, a business-rules layer, swappable storage, consistent errors and pagination. In the coming chapters you’ll give it a real database, authentication, tests and a Docker image.
Notice what didn’t happen: no handler contains SQL, no service touches
req, and every error response looks the same. That’s what makes the next steps easy.
Add a publish action
Extend the courses API with POST /api/v1/courses/:id/publish. It should set status to 'published' and publishedAt to the current time, return the updated course, and respond 409 if the course is already published.
// courses.service.js — add a publish(id) method
// courses.routes.js — add the route// courses.service.js
async publish(id) {
const course = await this.get(id);
if (course.status === 'published') {
throw new HttpError(409, 'Course is already published');
}
return coursesRepo.update(id, { status: 'published', publishedAt: new Date().toISOString() });
},
// courses.routes.js
router.post('/:id/publish', validate({ params: idParams }), async (req, res) => {
res.json(await coursesService.publish(req.validated.params.id));
});Summary
- A complete endpoint set: list, read, create, update and delete, each with validation.
- The service holds the rules; the repository can be swapped from memory to PostgreSQL without other changes.
- Lists support filtering and pagination with a capped page size.
- Errors from anywhere become consistent JSON responses.
- Test it manually with curl or an HTTP client before writing automated tests.