Lesson 6 of 8 · 11 min · Building APIs with Express
Designing REST APIs with Express
What you will learn
- Design resource URLs and choose HTTP methods and status codes
- Paginate, filter and sort collections
- Make operations safe to retry (idempotency)
- Version, document and keep an API consistent
- Structure a complete CRUD API in Express
In simple words
A good API is predictable: a developer who has never seen yours can guess how to list orders, fetch one, create one and delete one. The conventions are simple: addresses are nouns ("orders"), the HTTP verb says what to do, the status code says what happened, and lists come in pages. The same design ideas were covered for Spring Boot; here they are in Express.
Words to know
- Resource: a thing the API exposes, such as an order or a customer.
- Idempotent: safe to repeat; doing it twice has the same effect as once.
- Pagination: returning a long list in pages.
- OpenAPI: a standard description format for HTTP APIs.
Resource-oriented URLs
| Do | Avoid |
|---|---|
GET /api/orders |
GET /api/getOrders |
GET /api/orders/101 |
POST /api/orders/get?id=101 |
POST /api/orders |
POST /api/createOrder |
PATCH /api/orders/101 |
POST /api/updateOrder |
DELETE /api/orders/101 |
GET /api/deleteOrder?id=101 |
GET /api/customers/3/orders |
deeply nested paths with five levels |
- Use plural nouns, lowercase, hyphens for multi-word names (
/order-items). - Nest at most one or two levels (
/customers/3/orders); beyond that expose/orders?customerId=3. - Verbs in the path are acceptable only for actions that are not CRUD:
POST /api/orders/101/cancel,POST /api/auth/login. - Never put secrets or personal data in URLs (they appear in logs).
Methods and status codes
| Method | Meaning | Idempotent | Success response |
|---|---|---|---|
GET |
read | yes (and safe) | 200 with the data |
POST |
create (or an action) | no | 201 with Location, or 200/202 |
PUT |
replace the whole resource | yes | 200 or 204 |
PATCH |
partial update | not guaranteed | 200 with the updated resource |
DELETE |
remove | yes | 204 (and 404, or 204 again, on repeat) |
Status codes: 200, 201, 202 accepted (async work), 204 no content, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 405 wrong method, 409 conflict, 412 precondition failed, 415 unsupported media type, 422, 429 rate limited, 500, 503 (the Spring Boot course has the full table). Use the right code and a consistent error body; do not return 200 with { "error": ... }.
A CRUD router
// src/routes/orders.js
import { Router } from "express";
import { validate } from "../middleware/validate.js";
import { createOrderSchema, patchOrderSchema, listOrdersQuery, idParam } from "../schemas/orders.js";
import * as orders from "../services/orders.js";
const router = Router();
router.get("/", validate(listOrdersQuery, "query"), async (req, res) => {
const { items, total } = await orders.list(req.validQuery);
const { page, size } = req.validQuery;
res.set("X-Total-Count", String(total));
res.json({ items, page, size, total });
});
router.get("/:id", validate(idParam, "params"), async (req, res) => {
res.json(await orders.get(req.validParams.id)); // service throws NotFoundError
});
router.post("/", validate(createOrderSchema), async (req, res) => {
const created = await orders.create(req.validBody, req.user);
res.status(201).location(`/api/orders/${created.id}`).json(created);
});
router.patch("/:id", validate(idParam, "params"), validate(patchOrderSchema), async (req, res) => {
res.json(await orders.update(req.validParams.id, req.validBody, req.user));
});
router.delete("/:id", validate(idParam, "params"), async (req, res) => {
await orders.remove(req.validParams.id, req.user);
res.status(204).end();
});
export default router;
The router handles HTTP and validation; the service applies rules (ownership, stock, state transitions) and throws domain errors; the repository talks to the database with parameterised queries. Return DTO-shaped JSON (explicit fields), never raw database rows (password hashes, internal flags).
Representations
- JSON with consistent field naming (
camelCase), ISO-8601 dates in UTC ("2025-10-31T10:30:00Z"), money as an integer in the smallest unit (paise) or a decimal string with a currency code, never floating-point numbers; booleans as booleans; enums as strings;nullfor "no value". - Use ids that are not guessable if exposure matters (UUIDs), and always check ownership.
- Return the created or updated resource from
POSTandPATCH. - Be consistent: the same envelope for lists everywhere, the same error format.
- Set
Content-Type: application/json; charset=utf-8; supportAcceptif you offer other formats. - Include hypermedia links only if clients will really use them.
Pagination, filtering and sorting
Never return an unbounded list. Two styles:
Offset pagination (simple): GET /api/orders?page=2&size=20&sort=createdAt:desc&status=paid
export async function list({ status, page, size, sort = "createdAt:desc" }) {
const [field, dir] = sort.split(":");
const allowed = new Set(["createdAt", "amount", "status"]); // allow-list sortable fields: never use raw input in SQL
if (!allowed.has(field)) throw new HttpError(400, `Cannot sort by ${field}`);
const rows = await db.query(
`SELECT id, customer_id, amount, status, created_at FROM orders
WHERE ($1::text IS NULL OR status = $1)
ORDER BY ${field === "createdAt" ? "created_at" : field} ${dir === "asc" ? "ASC" : "DESC"}, id DESC
LIMIT $2 OFFSET $3`,
[status ?? null, size, (page - 1) * size],
);
return { items: rows, total: await count(status) };
}
(Column names cannot be query parameters, so map from an allow-list; values always go through $1, $2.) Offset paging gets slow and inconsistent on large, changing tables.
Keyset (cursor) pagination for large or fast-changing data: GET /api/orders?limit=20&after=eyJpZCI6MTAxfQ, where the cursor encodes the last seen sort key (WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20) and the response returns nextCursor. It is fast and stable.
Cap size (for example 100), return total counts only when needed (a count can be expensive), and document defaults.
Idempotency and concurrency
POST is not naturally idempotent: a client that retries after a timeout may create two orders. For payment-like operations, accept an Idempotency-Key header: the server stores the key with the response, and a repeated request with the same key returns the stored result instead of acting again.
For concurrent edits, use optimistic concurrency: send a version or ETag with the resource; the client sends If-Match: "v3" on update; if the stored version changed, return 412 Precondition Failed (or 409), so one user does not silently overwrite another's work. Use database transactions for multi-step changes (the SQL transactions lesson) and unique constraints for uniqueness.
Caching: GET responses can set Cache-Control and ETag (Express adds weak ETags by default, so conditional requests return 304 Not Modified). Never cache private data in shared caches (Cache-Control: private or no-store).
Versioning and evolution
- Prefer additive, backward-compatible changes (new optional fields, new endpoints) so clients never break.
- When a breaking change is unavoidable, version it: a URL prefix (
/api/v1/orders, simple and visible) or a header. Keep the old version running with a deprecation notice (DeprecationandSunsetheaders) and a migration date. - Never remove or rename fields casually; mobile apps stay on old versions for months.
- Mount versions as routers:
app.use("/api/v1", v1Router).
Documentation and tooling
Describe your API in OpenAPI (a YAML or JSON description). Benefits: interactive documentation (Swagger UI, Redoc, Scalar), generated client libraries and types, request/response validation, contract tests, and mock servers. Write the spec first ("design first") or generate it from Zod schemas (zod-to-openapi, @asteasolutions/zod-to-openapi) or from framework decorators. Keep the spec in version control and check it in CI. Provide examples, error responses and authentication details; test with curl, Postman, Bruno or REST Client files in the repository.
Operational basics
- Health endpoints:
GET /health(liveness) andGET /ready(dependencies reachable) for load balancers and Kubernetes. - Rate limiting per client or key (
express-rate-limit, a gateway), returning429withRetry-After. - Request ids in logs and an
X-Request-Idresponse header; structured logging. - Timeouts on outgoing calls and the database; request timeouts at the proxy.
- Compression and
ETag; CORS allow-lists; HTTPS only. - Monitoring: latency percentiles, error rates, event loop lag; alert on 5xx rates.
- Security: authentication and per-object authorisation, input validation, parameterised queries, no sensitive data in logs (the next lessons).
Common mistakes
- Verbs in URLs and inconsistent naming.
GETrequests that change data.- Unbounded list endpoints with no pagination.
- Wrong or missing status codes;
200with errors in the body. - Returning raw database rows (leaking fields and coupling the API to the schema).
- Money as floating-point numbers.
- Breaking changes without versioning.
- Building SQL
ORDER BYfrom user input without an allow-list. - No idempotency for retried payments.
Try it yourself
- Build the orders router above with an in-memory repository, then swap in PostgreSQL with parameterised queries.
- Add pagination, status filter and an allow-listed sort, and cap
size. - Return
201withLocationon create and204on delete; test withcurl -i. - Add
ETag/If-Matchhandling toPATCHand test a conflicting update. - Write an OpenAPI description for two endpoints and view it in Swagger UI.
Check yourself
What makes a method idempotent, and which HTTP methods are?
Repeating the request has the same effect as doing it once; GET, PUT and DELETE are idempotent, POST is not.
Why paginate list endpoints?
Unbounded lists waste memory, bandwidth and database time and can crash clients and servers; pages bound the cost and let clients load progressively.
How do you make a payment POST safe to retry?
Accept an Idempotency-Key; store the result under that key and return the stored response for repeated requests.
What should a DELETE of an existing resource return?
204 No Content.
Interview questions
What are the REST constraints and best practices you follow when designing an API?
Resource-oriented URIs with plural nouns, correct HTTP methods and status codes, statelessness, consistent JSON representations, pagination and filtering for collections, idempotency where needed, versioning for breaking changes, security and documentation with OpenAPI.
Offset versus cursor pagination?
Offset (page/size) is simple but slow on deep pages and unstable when data changes; cursor (keyset) pagination uses the last seen key, is fast and consistent, and suits large or live data.
PUT or PATCH?
PUT replaces the whole resource (the client sends all fields) and is idempotent; PATCH changes only the supplied fields and is better for partial updates such as changing an order's status.
Summary
- Use plural noun URLs, correct methods and status codes, and a consistent JSON shape and error format.
- Paginate (offset or cursor), filter and sort with allow-lists; return DTOs, integers for money and ISO dates.
- Add idempotency keys, ETags and versioning for safe retries, concurrency and evolution.
- Document with OpenAPI, provide health endpoints, rate limits and structured logs.
Going deeper
- MDN: HTTP methods: semantics of each method.
- RFC 9110: HTTP semantics: methods, status codes and conditional requests.
- Express: Routing: routers and route handlers.
- OWASP: REST Security Cheat Sheet: securing REST APIs.
See how much of this you can explain
A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.