TExcelTAD
Home › Express & NestJS › REST API Design

REST API Design

REST (Representational State Transfer) is a style for designing HTTP APIs around resources — nouns like books, users and orders — that clients manipulate with the standard HTTP methods. Express doesn't enforce any of this; good design is up to you. This lesson collects the conventions most public APIs follow.

Resources and URLs

Use plural nouns for collections and an id for a single item. Let the HTTP method express the action:

Method + URL Action Success code
GET /books list books 200
GET /books/42 read one book 200
POST /books create a book 201
PUT /books/42 replace book 42 entirely 200
PATCH /books/42 change some fields of book 42 200
DELETE /books/42 delete book 42 204
GET /authors/7/books books of author 7 (nested resource) 200

Avoid verbs in paths: POST /createBook or GET /getBooks?id=1 repeat what the method already says.

Tip: Some actions don't map to CRUD — "publish a draft", "cancel an order". A common, readable compromise is a sub-resource: POST /orders/12/cancellation or POST /posts/5/publish.

Safe and idempotent methods

Method Safe (no changes)? Idempotent (repeat = same result)?
GET, HEAD yes yes
PUT no yes
DELETE no yes
PATCH no not necessarily
POST no no

Idempotency matters for retries: a client that times out can safely repeat a PUT or DELETE, but repeating a POST may create a duplicate.

A consistent JSON shape

Pick one shape for success and one for errors and use it everywhere. A popular choice:

json
{ "data": { "id": 42, "title": "Dune" } }

{ "data": [ ... ], "meta": { "page": 1, "limit": 20, "total": 87 } }

{ "error": { "code": "VALIDATION_FAILED", "message": "title is required", "fields": { "title": "required" } } }

Small helper functions keep the shape consistent:

node · try it yourself
const express = require('express');

const ok = (res, data, meta) => res.json(meta ? { data, meta } : { data });
const fail = (res, status, code, message) => res.status(status).json({ error: { code, message } });

const app = express();
const books = [{ id: 1, title: 'Dune' }, { id: 2, title: 'Kindred' }];

app.get('/books', (req, res) => ok(res, books, { total: books.length }));
app.get('/books/:id', (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  if (!book) return fail(res, 404, 'NOT_FOUND', 'Book not found');
  ok(res, book);
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const p of ['/books', '/books/2', '/books/3']) {
    const res = await fetch(base + p);
    console.log(res.status, await res.text());
  }
  server.close();
});
200 {"data":[{"id":1,"title":"Dune"},{"id":2,"title":"Kindred"}],"meta":{"total":2}}
200 {"data":{"id":2,"title":"Kindred"}}
404 {"error":{"code":"NOT_FOUND","message":"Book not found"}}

PUT vs PATCH

PUT sends the whole resource; missing fields are reset. PATCH sends only what changes. This tiny model shows the difference:

ts · try it yourself
type Book = { title: string; year: number | null; tags: string[] };

const stored: Book = { title: 'Dune', year: 1965, tags: ['sf'] };

function put(body: Partial<Book>): Book {
  // replace: anything not sent goes back to its default
  return { title: body.title ?? '', year: body.year ?? null, tags: body.tags ?? [] };
}

function patch(current: Book, body: Partial<Book>): Book {
  // merge: only the sent fields change
  return { ...current, ...body };
}

console.log('PUT  ', put({ title: 'Dune Messiah' }));
console.log('PATCH', patch(stored, { title: 'Dune Messiah' }));
PUT   { title: 'Dune Messiah', year: null, tags: [] }
PATCH { title: 'Dune Messiah', year: 1965, tags: [ 'sf' ] }

Naming and formatting conventions

Topic Convention
URL case lowercase, hyphens: /order-items, not /orderItems
JSON keys pick one style (camelCase is common in JS APIs) and never mix
Dates ISO 8601 strings in UTC: "2025-03-01T12:00:00Z"
IDs strings or integers, but always the same type for a resource
Booleans isActive, hasChildren — avoid "yes"/"no" strings
Empty list [], never null or 404

Versioning

Clients break when you change a response shape. Plan for it from day one:

Strategy Example Notes
URL prefix /api/v1/books simplest, very common, easy to route with express.Router
Header Accept: application/vnd.shop.v2+json cleaner URLs, harder to test in a browser
Query /books?version=2 easy, but mixes versioning with filtering

Additive changes — new optional fields, new endpoints — don't need a new version. Removing or renaming fields does.

Documenting the API

An API is only as good as its documentation. The industry standard is OpenAPI (formerly Swagger): a YAML/JSON description of every endpoint, from which tools generate interactive docs, client SDKs and tests. NestJS can generate OpenAPI documents from your code automatically (@nestjs/swagger).

yaml
paths:
  /books/{id}:
    get:
      summary: Read one book
      responses:
        '200': { description: The book }
        '404': { description: Not found }

Test yourself

Which URL follows REST conventions for deleting order 9?

  1. POST /deleteOrder?id=9
  2. GET /orders/9/delete
  3. DELETE /orders/9
  4. DELETE /order?id=9

A client resends a request after a timeout. Which method is NOT idempotent and may create duplicates?

  1. PUT
  2. DELETE
  3. GET
  4. POST

What should GET /books?author=nobody return when nothing matches?

  1. 404 Not Found
  2. 200 with an empty list
  3. 204 No Content
  4. 500