Every back end developer builds a CRUD API first, and interviewers still ask to see one. CRUD stands for create, read, update and delete, the four things you do with almost any kind of data. This project is small enough to finish in an evening, and complete enough to show that you know the details that separate a tutorial from real work: validation, unique emails, paging, search, the difference between PUT and PATCH, and honest status codes. All ten projects in this part of the course follow the same pattern: a short description, the code, the rules that matter, and a test that proves them.
What you will build
POST /api/userscreates a user and returns 201 with aLocationheader.GET /api/userslists users withpage,limitand a search wordq.GET,PUT,PATCHandDELETEon/api/users/:id.- Clean validation messages with 422, a duplicate email with 409, a missing user with 404, and delete with 204.
Design decisions before any code
A user has an id, a name, an email, an optional age and a creation time. Before writing code, decide the rules, because rules are the real content of an API. A name needs at least two letters. An email must look like an email, is trimmed and turned into lower case, and must be unique, so that ASHA@Example.com and asha@example.com cannot be two people. An age, if sent, must be a whole number between 0 and 120.
The shape of the code follows lesson 19. The clean function checks and cleans a body and throws an AppError with the right status code, and one error handler at the bottom turns errors into JSON replies. The shared file p-kit.js holds AppError and the handlers, and the later projects reuse it, so read it first.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express jsonwebtoken. - Copy
p-kit.js,p01-users.jsandp01.test.jsinto the folder. The sharedp-kit.jsis in Project 1. - Install the test tools with
npm install -D supertest, then runnode --test p01.test.js.
First the shared helpers. AppError carries a status code, requireAuth and requireRole protect routes, and errorHandler makes sure that a bug never shows its stack trace to the client.
// Small helpers shared by projects 2 to 9: errors, tokens, auth middleware, and the error handler.
import jwt from 'jsonwebtoken';
export class AppError extends Error {
constructor(message, status = 400) { super(message); this.status = status; }
}
export const SECRET = process.env.JWT_SECRET ?? 'dev-only-secret-change-me-please-32chars';
export const signToken = (user, secret = SECRET) =>
jwt.sign({ sub: user.id, role: user.role, name: user.name }, secret, { expiresIn: '1h' });
export const requireAuth = (secret = SECRET) => (req, res, next) => {
try {
const payload = jwt.verify((req.get('authorization') ?? '').replace(/^Bearer /, ''), secret);
req.user = { id: payload.sub, role: payload.role, name: payload.name };
next();
} catch {
next(new AppError('Log in first', 401));
}
};
export const requireRole = (...roles) => (req, res, next) =>
roles.includes(req.user?.role) ? next() : next(new AppError('You are not allowed to do this', 403));
// Wrap a handler so a thrown AppError goes to the error handler (Express 5 does this for async handlers already).
export const handle = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
export const notFoundHandler = (req, res) => res.status(404).json({ error: 'Not found' });
export const errorHandler = (err, req, res, next) => {
if (err.type === 'entity.parse.failed') return res.status(400).json({ error: 'Body is not valid JSON' });
const status = err.status ?? 500;
if (status >= 500) console.error(err);
res.status(status).json({ error: status < 500 ? err.message : 'Something went wrong' });
};
Now the project. Read clean, then createApp, and notice how short each route is, because the rules live in clean and in two small helpers.
// Project 1: a CRUD API for users, with validation, paging and clear status codes.
import express from 'express';
import { AppError, errorHandler, notFoundHandler } from './p-kit.js';
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function clean(body, { partial = false } = {}) {
const out = {};
if (!partial || 'name' in body) {
if (typeof body.name !== 'string' || body.name.trim().length < 2) throw new AppError('name needs at least 2 letters', 422);
out.name = body.name.trim();
}
if (!partial || 'email' in body) {
if (typeof body.email !== 'string' || !EMAIL.test(body.email.trim())) throw new AppError('email is not valid', 422);
out.email = body.email.trim().toLowerCase();
}
if ('age' in body) {
if (!Number.isInteger(body.age) || body.age < 0 || body.age > 120) throw new AppError('age must be a whole number from 0 to 120', 422);
out.age = body.age;
}
return out;
}
export function createApp() {
const app = express();
app.use(express.json());
const users = new Map();
let nextId = 1;
const emailTaken = (email, exceptId) => [...users.values()].some((u) => u.email === email && u.id !== exceptId);
app.post('/api/users', (req, res) => {
const data = clean(req.body ?? {});
if (emailTaken(data.email)) throw new AppError('That email is already used', 409);
const user = { id: nextId++, createdAt: new Date().toISOString(), ...data };
users.set(user.id, user);
res.status(201).location(`/api/users/${user.id}`).json(user);
});
app.get('/api/users', (req, res) => {
const page = Math.max(Number.parseInt(req.query.page, 10) || 1, 1);
const limit = Math.min(Math.max(Number.parseInt(req.query.limit, 10) || 10, 1), 50);
const q = String(req.query.q ?? '').toLowerCase();
const all = [...users.values()].filter((u) => !q || u.name.toLowerCase().includes(q) || u.email.includes(q));
res.json({ data: all.slice((page - 1) * limit, page * limit), meta: { page, limit, total: all.length } });
});
const find = (id) => users.get(Number(id)) ?? (() => { throw new AppError('User not found', 404); })();
app.get('/api/users/:id', (req, res) => res.json(find(req.params.id)));
// PUT replaces the user, PATCH changes only the fields you send.
app.put('/api/users/:id', (req, res) => {
const user = find(req.params.id);
const data = clean(req.body ?? {});
if (emailTaken(data.email, user.id)) throw new AppError('That email is already used', 409);
delete user.age; // PUT replaces: a field you leave out is removed
res.json(Object.assign(user, data));
});
app.patch('/api/users/:id', (req, res) => {
const user = find(req.params.id);
const data = clean(req.body ?? {}, { partial: true });
if (data.email && emailTaken(data.email, user.id)) throw new AppError('That email is already used', 409);
res.json(Object.assign(user, data));
});
app.delete('/api/users/:id', (req, res) => {
users.delete(find(req.params.id).id);
res.status(204).end();
});
app.use(notFoundHandler, errorHandler);
return app;
}
The test goes through the whole life of a user and checks each rule.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './p01-users.js';
test('project 1: users CRUD', async () => {
const app = createApp();
const created = await request(app).post('/api/users').send({ name: ' Asha ', email: 'ASHA@Example.com', age: 29 });
assert.equal(created.status, 201);
assert.equal(created.body.email, 'asha@example.com');
assert.equal(created.headers.location, '/api/users/1');
assert.equal((await request(app).post('/api/users').send({ name: 'Other', email: 'asha@example.com' })).status, 409);
assert.equal((await request(app).post('/api/users').send({ name: 'A', email: 'x' })).status, 422);
await request(app).post('/api/users').send({ name: 'Ravi', email: 'ravi@example.com' });
const list = await request(app).get('/api/users?q=rav');
assert.deepEqual(list.body.data.map((u) => u.name), ['Ravi']);
assert.equal((await request(app).get('/api/users?limit=1&page=2')).body.data[0].name, 'Ravi');
const patched = await request(app).patch('/api/users/1').send({ name: 'Asha K' });
assert.equal(patched.body.name, 'Asha K');
assert.equal(patched.body.age, 29); // PATCH keeps what you did not send
const put = await request(app).put('/api/users/1').send({ name: 'Asha K', email: 'asha@example.com' });
assert.equal(put.body.age, undefined); // PUT replaced the whole user
assert.equal((await request(app).delete('/api/users/1')).status, 204);
assert.equal((await request(app).get('/api/users/1')).status, 404);
assert.equal((await request(app).post('/api/users').set('Content-Type', 'application/json').send('{bad')).status, 400);
});
Rules worth understanding
PUT replaces, PATCH changes. A PUT sends the whole new version of the user, so a field that you leave out disappears. A PATCH sends only what changes, so the rest stays. The test shows this with the age field: after a PATCH it is still there, and after a PUT it is gone. Many APIs use PUT for both, and that is a common source of confusion.
Conflict is not invalid. A malformed email is 422: the data fails the rules. A duplicate email is 409: the data is fine, but it clashes with something that already exists. Telling the two apart lets a front end show the right message.
Paging and search together. The list route clamps limit to 50, falls back to defaults for bad numbers, and applies the search before slicing the page, so that total in the reply counts the matches and not all users. Front ends use that number to draw page buttons.
A missing user inside a helper. The find helper throws a 404 AppError, so every route that needs a user is a single line and none of them can forget to check.
Security and honesty notes
There is no login in this first project, so anyone can call it. In a real system these routes sit behind the authentication of Project 2. The body is never copied straight into the stored user: clean builds a new object with only the allowed fields, which protects you from a client sending extra fields such as isAdmin.
The email check here is a simple pattern. The only real proof that an address works is to send a message to it, as lesson 28 does.
Extend it
Your task
- Move the store to MongoDB with Mongoose and add a unique index on the email.
- Add sorting with an allow-list of fields.
- Write the OpenAPI file for these routes, as in lesson 21, and open it in Swagger UI.
How to check it worked
- Your test passes.
- A duplicate email returns 409 and a bad email returns 422.
- You can explain the difference between PUT and PATCH using the age field.
On your resume. A line such as "Built a REST API with Express, with validation, paging, search and automated tests with Supertest" is honest and specific. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.