Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 133 ยท Networking and HTTP

Designing REST APIs

Design clean REST APIs in Node.js - resources and verbs, status codes, validation, pagination, filtering, idempotency, versioning and RFC 9457 error responses, with a full in-memory CRUD example.

An API (application programming interface) is how programs talk to your server. A REST API does it over HTTP using a few simple rules: things in your system are resources with their own URLs, standard methods (GET, POST, PUT, PATCH, DELETE) say what to do with them, and status codes report what happened. Because the rules are shared, a developer who has never seen your API can guess most of it.

REST is a style, not a law, and many "REST" APIs bend the rules. The goal of this lesson is a practical set of decisions that make APIs predictable and hard to misuse: how to name resources, which status code to return, how to validate input, how to paginate, how to make writes safe to retry, and how to format errors. You will build a complete in-memory CRUD API in plain Node.js with the tools from the previous lessons: The http Module: Servers, Request Bodies, JSON and Forms and Building a Router from Scratch.

Resources and verbs

Name URLs after nouns (things), not verbs (actions). The method is the verb.

Request Meaning Typical success
GET /books list books 200 + array
POST /books create a book 201 + new book + Location
GET /books/7 read one book 200
PUT /books/7 replace the whole book 200 (or 204)
PATCH /books/7 change some fields 200
DELETE /books/7 remove it 204
GET /books/7/reviews a sub-collection 200

Use plural nouns, lower case, hyphens for multi-word names (/book-clubs), and keep nesting shallow (/books/7/reviews is fine, four levels deep is not). Actions that do not map to CRUD can be modelled as a sub-resource that you create: POST /orders/12/cancellation or POST /payments, rather than POST /cancelOrder.

Two properties of methods matter for correctness:

  • Safe methods (GET, HEAD, OPTIONS) must not change anything. Crawlers and prefetchers call them freely.
  • Idempotent methods (GET, PUT, DELETE) give the same end state if repeated. POST is not idempotent: sending it twice may create two books. This matters when a network hiccup makes a client retry, and we come back to it below.

A complete CRUD API

Here is the whole thing: a tiny router, an in-memory store, and the five operations. The client part at the bottom plays a short story: create, read, update, list, delete. Read the handler code carefully, it demonstrates the status codes you will use constantly.

Node.js An in-memory CRUD API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last two calls show typical edge behaviour. Deleting a book twice answers 404 the second time. Some designers prefer 204 again, because the end state ("the book is gone") is the same; both are defensible, but be consistent. The final PATCH without a body returns a 400 because empty input is invalid JSON.

Choosing status codes

Pick the code that tells a client what to do next:

  • 200 OK success with a body; 201 Created after POST (add Location); 202 Accepted when the work will be done later; 204 No Content success without a body.
  • 400 Bad Request malformed syntax; 401 Unauthorized (really "unauthenticated": who are you?); 403 Forbidden (I know you, but no); 404 Not Found; 405 Method Not Allowed (include Allow); 409 Conflict (state clash, such as a duplicate or a stale update); 410 Gone; 415 wrong media type; 422 Unprocessable Content (well-formed but fails validation); 429 Too Many Requests (include Retry-After).
  • 500 Internal Server Error your bug; 502/503/504 upstream or availability problems.

Do not return 200 with { "success": false }: it breaks clients, monitoring and caches, all of which look at the status first.

Validation and the error format

Never trust input. Check required fields, types, lengths and allowed values, and report all problems at once so the client can fix them in one go. For error bodies, don't invent a format per endpoint. RFC 9457 ("Problem Details for HTTP APIs") defines a standard JSON shape with media type application/problem+json:

  • type: a URL or URI identifying the kind of problem,
  • title: a short, human-readable summary (the same for each occurrence),
  • status: the HTTP status,
  • detail: an explanation of this particular occurrence,
  • instance: identifies this occurrence (optional),
  • plus any extension members you need, such as an errors array.
Node.js Validation with problem+json errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The errors array is an extension member: RFC 9457 explicitly allows them. Validation can be written by hand like this for small APIs; larger ones use a schema library, see Validating Input. Note that the validator returns an array of problems instead of throwing on the first one, which gives clients a much better experience.

Pagination, filtering and sorting

A collection endpoint must never return "everything". Add three features from the start:

  • Pagination. Offset style: ?limit=20&offset=40 (simple, but items can shift or repeat while someone pages and slow for huge offsets). Cursor style: ?limit=20&after=<opaque cursor> (stable and fast, the right choice for feeds and big tables).
  • Filtering. Query parameters named after fields: ?author=Austen&year_gte=1900.
  • Sorting. ?sort=-year,title (a minus sign for descending).

Always cap limit on the server and return paging information, either in the body or in headers (Link with rel="next", or X-Total-Count).

Node.js Filtering, sorting and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The client asked for limit=999 and got 10: the cap protects the server. If your data is large and changes often, switch to cursors: the cursor is usually the last row's sort key (encoded as base64url so clients treat it as opaque), and the query becomes WHERE (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT ?. See SQLite with node:sqlite for a database you can try this against.

Idempotency and safe retries

Networks fail. If a client sends POST /payments and the connection drops before the answer arrives, it cannot know whether the payment happened. Retrying blindly could charge twice. The fix is an idempotency key: the client generates a unique value per intended operation and sends it in an Idempotency-Key header. The server stores the first result under that key; a repeat with the same key returns the stored response instead of doing the work again.

Node.js Idempotency keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A production version must handle two more cases: a repeat that arrives while the first is still running (return 409 or wait for the same promise), and a repeat with the same key but a different body (reject with 422). Keys expire after a day or so. Scalability and Reliability Patterns takes this further.

PUT and DELETE are naturally idempotent, which is one reason to prefer PUT /orders/{client-generated-id} over POST when the client can choose the ID.

Concurrent updates: ETag and If-Match

Two users load the same book, both edit it, both save: the second silently overwrites the first ("lost update"). Optimistic concurrency fixes this: send an ETag (or a version number) with each read, require the client to send it back in If-Match on writes, and answer 412 Precondition Failed when it no longer matches. Headers, Cookies and Caching shows ETags; here they protect writes instead of saving bandwidth. For a missing header, 428 Precondition Required is the matching code.

Versioning and evolving an API

Published APIs are promises. Prefer additive changes (new optional fields, new endpoints): clients should ignore fields they do not know. When you must break something, version it:

  • In the URL: /v1/books, /v2/books. Easiest to understand, to route and to cache. Most public APIs do this.
  • In a header or media type: Accept: application/vnd.example.v2+json. Cleaner URLs, harder to test with a browser.

Whichever you choose, announce deprecations early with the Deprecation and Sunset headers, and keep the old version running until usage drops.

Pure REST ("HATEOAS") says responses should contain links telling the client what it can do next, so clients do not hard-code URLs. In practice, full hypermedia is rare, but a few cheap habits pay off: return Location after creation, include an id and a url/self link in resources, give paginated results a next link, and describe the API with an OpenAPI document. That gives most of the benefit without a heavy format.

Design your API from the consumer's side first: write the requests a client would send for the main tasks, then implement. If a task takes five calls and the client must stitch results together, the resources are probably too fine-grained. Keep response shapes consistent across endpoints (same names, same date format such as ISO 8601 2026-01-31T10:00:00Z, same casing).

Common mistakes

  • Verbs in URLs (/getBooks), or one POST /api endpoint for everything.
  • Returning 200 for errors, or 500 for bad client input.
  • Unbounded lists, with no maximum limit.
  • Leaking internals: database IDs that expose counts, stack traces, SQL errors.
  • Ignoring Content-Type and happily parsing anything.
  • Changing field names or types without a new version.
  • Forgetting Allow on 405, Location on 201, or Retry-After on 429/503.
  • No authentication on write endpoints. Authentication and rate limits belong in middleware; the whole API is assembled step by step in Project: A REST API from Scratch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL and method follow REST conventions for creating a new book?

    The collection is named with a plural noun, and POST on the collection creates a member. The server replies 201 with a Location header.
  2. 2. A request body is well-formed JSON but the title field is missing. Which status code fits best?

    The syntax is fine, so 400 is not wrong but 422 describes it best because the server understood the request and it failed validation. Never use 5xx for client input.
  3. 3. Why should a list endpoint enforce a maximum limit?

    Without a cap a client (or attacker) can request the whole table in one call, consuming memory, bandwidth and database time.
  4. 4. What problem does an Idempotency-Key header solve?

    The server remembers the result of the first request with that key and returns it for repeats, so retries are safe.
  5. 5. Two users edit the same record. How does If-Match with an ETag help?

    The ETag identifies the version the client read. If the stored version differs, the write is refused instead of silently overwriting the other change.

Summary

  • Model your API around plural-noun resources and let the HTTP method be the verb; keep nesting shallow.
  • Use status codes honestly: 201 + Location on create, 204 for empty success, 400/422 for bad input, 404, 405 + Allow, 409, 429 + Retry-After, and 5xx only for server faults.
  • Validate everything and report all problems at once, in the standard RFC 9457 application/problem+json format.
  • Lists need pagination (cap limit; prefer cursors for large data), filtering and sorting.
  • Make unsafe operations safe to retry with idempotency keys, and prevent lost updates with ETag plus If-Match.
  • Evolve additively, version breaking changes (/v1/...), and announce deprecations.
  • Keep responses consistent and never leak internals.

Next: Server-Sent Events and Streaming Responses