Skip to the content

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

RuleGoodBad
Use nouns, not verbs: the method is the verbGET /ordersGET /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:

OperationRequestResponse
ListGET /orders200 with a list (paginated, Lesson 197)
Read oneGET /orders/123200 or 404
CreatePOST /orders201 with Location and the new resource
ReplacePUT /orders/123200
Update partPATCH /orders/123200
DeleteDELETE /orders/123204

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:

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:

TypeScript
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.

StrategyExampleNotes
URL path/v1/orders, /v2/ordersMost common, simple, visible, easy to route and cache
HeaderAccept: application/vnd.example.v2+json or Api-Version: 2Cleaner URLs, harder to test in a browser
Date-basedStripe-Version: 2026-10-01Stripe'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

RESTGraphQLgRPC
ShapeMany endpoints, fixed responsesOne endpoint; client asks for exactly the fields it needsRemote procedure calls defined in .proto files
FormatJSON over HTTPJSON over HTTPBinary Protocol Buffers over HTTP/2
StrengthsSimple, HTTP caching, universalNo over-fetching or under-fetching, great for complex UIsVery fast, strongly typed, streaming; service-to-service
WeaknessesOver-fetching, many round tripsCaching harder, N+1 queries on the server (Lesson 221), complexityNot 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

WordMeaning
RESTAn API style built on resources, URLs and HTTP methods
ResourceA thing exposed by the API, like an order
StatelessEach request carries everything needed to handle it
Mass assignmentClients setting fields they should not, by sending extra properties
Problem DetailsThe RFC 9457 standard JSON error format
Breaking changeA change that can break existing clients
OpenAPIA standard format for describing HTTP APIs

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.