Structuring an API project
Overview
Small Express apps often start with everything in app.js: routes, SQL, validation, rules, all mixed together. That’s fine for a weekend project. But as an API grows, the same rule ends up copied into several handlers, a database change means editing twenty routes, and testing anything requires a real server and database.
The fix is to organise code into layers, each with one job. This isn’t about following a pattern for its own sake: it’s what lets a team keep changing an API for years without it collapsing.
The layers
| Layer | Knows about | Doesn’t know about |
|---|---|---|
| Routes | URLs, methods, which middleware to apply | business rules, SQL |
| Controllers (handlers) | req, res, status codes, validated input |
SQL |
| Services | business rules, orchestration of several repositories or external APIs | HTTP (req/res), SQL details |
| Repositories | SQL, table names, the database driver | HTTP, business rules |
Each layer calls only the one below it. A service never touches req; a controller never writes SQL.
Why it pays off
- Reuse. The “enrol a user in a course” rule lives in one service function, used by the REST API, an admin script and a background job.
- Testing. Services can be tested with a fake repository — no database, no HTTP, milliseconds per test.
- Change. Switching from Express to Fastify only touches routes and controllers. Moving from one database to another only touches repositories.
- Finding code. Everyone knows where a SQL bug or a validation bug will be.
A layered feature
// src/courses/courses.repository.js — data access only
export function makeCoursesRepo(db) {
return {
findById: (id) => db.oneOrNone('SELECT * FROM courses WHERE id = $1', [id]),
findByTitle: (title) => db.oneOrNone('SELECT * FROM courses WHERE lower(title) = lower($1)', [title]),
insert: ({ title, level }) =>
db.one('INSERT INTO courses (title, level) VALUES ($1, $2) RETURNING *', [title, level]),
};
}// src/courses/courses.service.js — business rules
import { HttpError } from '../errors.js';
export function makeCoursesService({ coursesRepo, events }) {
return {
async get(id) {
const course = await coursesRepo.findById(id);
if (!course) throw new HttpError(404, 'Course not found');
return course;
},
async create(data) {
if (await coursesRepo.findByTitle(data.title)) {
throw new HttpError(409, 'A course with that title already exists');
}
const course = await coursesRepo.insert(data);
events.emit('course:created', course);
return course;
},
};
}// src/courses/courses.routes.js — HTTP only
import { Router } from 'express';
import { validate } from '../middleware/validate.js';
import { createCourseSchema, idParams } from './courses.schemas.js';
export function makeCoursesRouter({ coursesService }) {
const router = Router();
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(`/api/v1/courses/${course.id}`).json(course);
});
return router;
}Services can throw
HttpError? Strictly, a 409 is an HTTP idea. Many teams accept this small shortcut. Others throw domain errors (DuplicateTitleError) and map them to status codes in the error handler. Either works — be consistent.
Wiring it together
Notice the make… functions: each layer receives its dependencies as arguments instead of importing them directly. This is dependency injection, and it’s what makes testing easy. One file wires the real pieces together:
// src/app.js
import express from 'express';
import { makeCoursesRepo } from './courses/courses.repository.js';
import { makeCoursesService } from './courses/courses.service.js';
import { makeCoursesRouter } from './courses/courses.routes.js';
import { notFound, errorHandler } from './middleware/errors.js';
export function createApp({ db, events }) {
const app = express();
app.use(express.json());
const coursesRepo = makeCoursesRepo(db);
const coursesService = makeCoursesService({ coursesRepo, events });
app.use('/api/v1/courses', makeCoursesRouter({ coursesService }));
app.use(notFound);
app.use(errorHandler);
return app;
}// src/server.js — the only file that touches the real world
import { createApp } from './app.js';
import { db } from './db.js';
import { config } from './config.js';
import { EventEmitter } from 'node:events';
createApp({ db, events: new EventEmitter() }).listen(config.port);In a test, you call createApp with a fake db or a test database — nothing else changes.
Folder structure
Organise by feature once you have more than a handful of resources. Everything about courses lives together:
src/
├── server.js start the HTTP server
├── app.js build the Express app
├── config.js validated configuration
├── db.js database pool
├── errors.js HttpError and friends
├── middleware/
│ ├── auth.js
│ ├── validate.js
│ └── errors.js
├── courses/
│ ├── courses.routes.js
│ ├── courses.schemas.js
│ ├── courses.service.js
│ └── courses.repository.js
└── users/
├── users.routes.js
└── …
test/
└── courses.test.jsThe alternative — folders by layer (routes/, services/, repositories/) — works for small apps but scatters each feature across the whole tree as it grows.
How much structure?
Don’t over-engineer. A 200-line internal tool doesn’t need four layers. Start simple, and introduce layers when you feel the pain: when a rule is duplicated, when tests need a database, when a file passes a few hundred lines. The structure in this topic is what most production Node APIs grow into.
A quick health check: if you can’t test a business rule without starting Express and a database, a layer is missing.
Refactor into layers
This route does everything in one place. Split it into a repository (data access), a service (the rule that a course title must be unique) and a thin route handler. The service should throw an HttpError(409, …) for duplicates.
const courses = [];
app.post('/courses', (req, res) => {
const { title } = req.body;
if (courses.some((c) => c.title.toLowerCase() === title.toLowerCase())) {
return res.status(409).json({ error: 'A course with that title exists' });
}
const course = { id: courses.length + 1, title };
courses.push(course);
res.status(201).json(course);
});// repositories/courses.repository.js
const courses = [];
export const coursesRepo = {
async findByTitle(title) {
return courses.find((c) => c.title.toLowerCase() === title.toLowerCase()) ?? null;
},
async insert(data) {
const course = { id: courses.length + 1, ...data };
courses.push(course);
return course;
},
};
// services/courses.service.js
import { HttpError } from '../errors.js';
export function makeCoursesService({ coursesRepo }) {
return {
async create({ title }) {
if (await coursesRepo.findByTitle(title)) {
throw new HttpError(409, 'A course with that title already exists');
}
return coursesRepo.insert({ title });
},
};
}
// routes/courses.routes.js
router.post('/', validate({ body: createCourseSchema }), async (req, res) => {
const course = await coursesService.create(req.validated.body);
res.status(201).json(course);
});Summary
- Separate HTTP handling, business rules and data access into layers.
- Routes/controllers deal with
reqandres; services hold rules and know nothing about HTTP; repositories contain the queries. - Group files by feature (courses, users, orders) once the app grows.
- Pass dependencies in (dependency injection) so services are easy to test with fakes.
- Keep
app.js(building the app) separate fromserver.js(starting it).