Lesson 196 of 296
REST API design: naming, errors and versioning
What you will learn
- What REST means in practice
- Naming resources and URLs
- Nested resources and actions
- Request and response bodies
- A consistent error format (Problem Details)
- Versioning strategies
- Documentation with OpenAPI
- REST vs GraphQL vs gRPC
On this page
What is REST?
REST (Representational State Transfer) is a style for designing HTTP APIs around resources (things: users, orders, products) identified by URLs, manipulated with HTTP methods, and represented usually as JSON. Each request is stateless: it carries everything the server needs (such as the auth token), so any server instance can handle it.
Naming rules
| Rule | Good | Bad |
|---|---|---|
| Use nouns, not verbs: the method is the verb | GET /orders | GET /getOrders |
| Plural collections | /orders, /orders/123 | /order/123 |
| Lower case, hyphens for multiple words | /order-items | /OrderItems, /order_items |
| Nest only for clear ownership, max one or two levels | /orders/123/items | /customers/9/orders/123/items/4/notes |
| Filters in the query string | /orders?status=paid | /orders/paid |
| No file extensions | /orders/123 | /orders/123.json |
The standard operations:
| Operation | Request | Response |
|---|---|---|
| List | GET /orders | 200 with a list (paginated, Lesson 197) |
| Read one | GET /orders/123 | 200 or 404 |
| Create | POST /orders | 201 with Location and the new resource |
| Replace | PUT /orders/123 | 200 |
| Update part | PATCH /orders/123 | 200 |
| Delete | DELETE /orders/123 | 204 |
Actions that are not simple CRUD (cancel an order, resend an email): either model them as a state change (PATCH /orders/123 with {"status":"cancelled"}) or as a sub-resource action: POST /orders/123/cancel. Both are accepted; be consistent.
Bodies
- Use JSON with consistent naming: camelCase (common in JavaScript APIs) or snake_case (Stripe, many Python APIs). Pick one.
- Dates in ISO 8601 UTC:
"2026-11-23T16:45:00Z"(Lesson 70). - Money in minor units as integers plus a currency:
{ "amountPence": 1999, "currency": "GBP" }, never floating point (Lesson 30). - IDs as strings (they may not stay numeric; big numbers lose precision in JavaScript).
- Do not return internal fields (password hashes, internal flags). Map database rows to response DTOs (Lesson 210).
- Validate every input (Lesson 114) and ignore or reject unknown fields, which prevents mass assignment (a user sending
"role":"admin"in a profile update).
A consistent error format
Every error should have the same shape, so clients can handle errors in one place. The standard is Problem Details (RFC 9457), with content type application/problem+json:
{
"type": "https://api.example.com/problems/validation-error",
"title": "Your request has invalid fields",
"status": 422,
"detail": "2 fields failed validation",
"instance": "/api/orders",
"errors": [
{ "field": "quantity", "message": "Must be at least 1" },
{ "field": "email", "message": "Enter a valid email address" }
],
"requestId": "req_8f2a"
}Rules:
- A machine-readable code or type (clients branch on it) and a human-readable message.
- Field-level details for validation errors.
- A request ID to find the logs.
- Never leak stack traces, SQL or internal details in production (Lesson 263).
A central Express error handler that produces this format:
import type { Request, Response, NextFunction } from "express";
import { ZodError } from "zod";
export class HttpError extends Error {
constructor(
public readonly status: number,
public readonly type: string,
message: string
) {
super(message);
this.name = "HttpError";
}
}
export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
const requestId = String(res.locals.requestId ?? "unknown");
if (err instanceof ZodError) {
res.status(422).type("application/problem+json").json({
type: "validation-error",
title: "Your request has invalid fields",
status: 422,
errors: err.issues.map((i) => ({ field: i.path.join("."), message: i.message })),
requestId
});
return;
}
if (err instanceof HttpError) {
res.status(err.status).type("application/problem+json").json({ type: err.type, title: err.message, status: err.status, requestId });
return;
}
console.error({ requestId, path: req.path, err });
res.status(500).type("application/problem+json").json({
type: "internal-error",
title: "Something went wrong",
status: 500,
requestId
});
}In Express 5, errors thrown in async route handlers (rejected promises) are passed to the error handler automatically. In Express 4 you had to wrap handlers or call next(err) yourself.
Versioning
APIs change, but existing clients (mobile apps that users never update!) must keep working.
Non-breaking changes (safe without a new version): adding a new endpoint, adding an optional field to a request, adding a field to a response.
Breaking changes (need a new version): removing or renaming a field, changing a type, making an optional field required, changing error formats or status codes.
| Strategy | Example | Notes |
|---|---|---|
| URL path | /v1/orders, /v2/orders | Most common, simple, visible, easy to route and cache |
| Header | Accept: application/vnd.example.v2+json or Api-Version: 2 | Cleaner URLs, harder to test in a browser |
| Date-based | Stripe-Version: 2026-10-01 | Stripe's approach: each account pinned to a version |
When retiring a version: announce it, add Deprecation and Sunset headers, monitor who still calls it, then remove it.
Documentation: OpenAPI
OpenAPI (formerly Swagger) is the standard format (YAML or JSON) for describing an API: endpoints, parameters, request and response schemas, auth. From it you get interactive docs (Swagger UI, Redoc), generated client SDKs and contract tests. Generate it from code (NestJS decorators, Zod schemas) so docs never drift from reality.
REST vs GraphQL vs gRPC
| REST | GraphQL | gRPC | |
|---|---|---|---|
| Shape | Many endpoints, fixed responses | One endpoint; client asks for exactly the fields it needs | Remote procedure calls defined in .proto files |
| Format | JSON over HTTP | JSON over HTTP | Binary Protocol Buffers over HTTP/2 |
| Strengths | Simple, HTTP caching, universal | No over-fetching or under-fetching, great for complex UIs | Very fast, strongly typed, streaming; service-to-service |
| Weaknesses | Over-fetching, many round trips | Caching harder, N+1 queries on the server (Lesson 221), complexity | Not directly usable from browsers |
How to say it in an interview
"I design REST APIs around plural noun resources with HTTP methods as verbs, shallow nesting, filters in the query string and ISO dates, integer minor units for money and string IDs. I validate input with schemas, map to DTOs and reject unknown fields to prevent mass assignment. Errors use one consistent format like RFC 9457 Problem Details with a machine-readable type, field errors and a request ID, without leaking internals. Additive changes are non-breaking; for breaking ones I version, usually in the URL, and deprecate with Sunset headers. I document with OpenAPI generated from code, and I choose GraphQL for complex client-driven data needs or gRPC between internal services."
Key words
| Word | Meaning |
|---|---|
| REST | An API style built on resources, URLs and HTTP methods |
| Resource | A thing exposed by the API, like an order |
| Stateless | Each request carries everything needed to handle it |
| Mass assignment | Clients setting fields they should not, by sending extra properties |
| Problem Details | The RFC 9457 standard JSON error format |
| Breaking change | A change that can break existing clients |
| OpenAPI | A standard format for describing HTTP APIs |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.