Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 43 ยท Building REST APIs

Designing a REST API in Express

Design a clean REST API with Express: resources and verbs, status codes, pagination, filtering, sorting, versioning and one consistent JSON shape.

An API is a promise to other programmers. A good one is boring in the best way: URLs are guessable, verbs mean what they say, errors look the same everywhere, and nothing changes under your clients' feet. REST is a set of conventions for getting there on top of HTTP, and Express is a comfortable tool to apply them. This lesson is about design decisions; the code for splitting handlers into layers follows in Controllers and Services.

The real Express code is read-only because npm is not available in the browser. The runnable examples use our mini Express stand-in with an in-memory list of books, so you can try every rule.

Resources and verbs

Think in nouns. A resource is a thing your API manages (a book, an order, a user). Its URL names it with a plural noun, and the HTTP method says what to do with it:

Request Meaning Success status
GET /books List books 200
GET /books/7 Read one book 200
POST /books Create a book 201 plus Location header
PUT /books/7 Replace a book 200
PATCH /books/7 Change some fields 200
DELETE /books/7 Remove a book 204, no body

Avoid verbs in URLs (/getBook, /deleteBook?id=7). The method already carries the verb. Nest only when ownership is clear: GET /authors/3/books is fine, but do not go deeper than two levels.

JavaScript
app.get('/api/v1/books', listBooks);
app.post('/api/v1/books', createBook);
app.get('/api/v1/books/:id', getBook);
app.patch('/api/v1/books/:id', updateBook);
app.delete('/api/v1/books/:id', deleteBook);

Rules of a tidy API

Plural nouns /books, not /getBooks.
Right verb GET reads, POST creates, DELETE removes.
Real status codes Never 200 with an error inside.
One shape Same JSON envelope every time.
1 / 2

The principles behind REST

"REST" is a set of constraints, not a library. An API that follows them is easier to cache, scale and evolve:

  • Client-server: the client owns the user interface, the server owns data and rules. They talk only through the API, so each side can change independently.
  • Stateless: every request carries everything the server needs (credentials, ids, filters). The server keeps no conversation between requests, so any server instance can answer any request and you can add machines freely.
  • Cacheable: responses say whether they may be reused (Cache-Control, ETag), which takes load off your server.
  • Uniform interface: resources have stable URLs, you act on them with standard methods, and responses describe themselves (status code, Content-Type).
  • Layered system: proxies, gateways and CDNs can sit between client and server without either side noticing.

REST also has limits. Fetching one screen of data may need several calls (over-fetching or under-fetching), and chatty, real-time or strongly typed needs may fit WebSockets or GraphQL better. REST is a good default for the public CRUD-style APIs described below, such as shops, bookings or weather lookups.

Choosing status codes

The status code is the first thing a client checks, so use the precise one:

  • 200 OK for a successful read or update; 201 Created after POST, with a Location header for the new resource.
  • 204 No Content for a successful delete (no body).
  • 400 Bad Request for malformed input such as broken JSON; 422 Unprocessable Content when the JSON is fine but the values are invalid (a missing title). Many teams use 400 for both; pick one rule and keep it.
  • 401 Unauthorized when the client is not signed in; 403 Forbidden when it is signed in but not allowed.
  • 404 Not Found for a missing resource; 409 Conflict for duplicates or version clashes.
  • 429 Too Many Requests when rate limited; 500 only for your own bugs.

Never answer 200 with { "success": false }. Clients, monitors and caches all read the status code, and a lie there hides real problems.

One consistent JSON shape

Pick an envelope and use it everywhere. A simple one:

JSON
{ "data": { "id": 7, "title": "Dune" } }
JSON
{ "data": [ { "id": 7 } ], "meta": { "page": 1, "limit": 10, "total": 42 } }
JSON
{ "error": { "code": "validation_failed", "message": "title is required" } }

Successful responses always have data (plus meta for lists) and failures always have error. A machine-readable code lets clients branch without parsing the message text. A standard such as RFC 9457 "problem details" is another good option if you want something formal.

Pagination, filtering and sorting

Query strings describe which part of a collection you want:

  • ?page=2&limit=10 (or cursor-based ?after=abc123 for very large or fast-changing data)
  • ?author=Ada&year=1843 to filter
  • ?sort=year ascending, ?sort=-year descending

Always cap limit (for example at 100) and give it a default, and whitelist the fields clients may sort or filter by, so nobody can sort by a column you did not intend to expose. Parameters arrive as strings, so convert them: Route Parameters and Query Strings shows how.

Versioning

Once clients depend on your API, breaking changes (removed fields, renamed URLs, different meanings) hurt. Putting the major version in the path, /api/v1/books, is the simplest approach: you can ship /api/v2/books while v1 keeps working. Adding a new optional field is not a breaking change and needs no new version. With express.Router you mount each version as its own router.

A runnable CRUD API

This is a stand-in implementation of the whole design: an in-memory list, an envelope, status codes, Location on create, pagination with a capped limit, filtering, whitelist sorting, and a versioned prefix. The JSON body parsing is a tiny middleware written for this example (real code uses express.json()).

Node.js A small CRUD API with pagination and sorting

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.

Walk through the output. The list calls return data and meta with the total count, so a client knows how many pages exist. A missing book gives 404 in the same error envelope; invalid input gives 422; DELETE gives 204 with an empty body; and a sort field outside the whitelist is rejected instead of silently ignored. The final call shows the Location header for the new book.

What the stand-in leaves out

Real handlers should also validate types more strictly (Validating Input), authenticate callers, and talk to a database rather than an array. The stand-in's PATCH copies any field from the body, which a real API must restrict to a known list of properties. Error handling can also be centralized, as described in Error Handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which URL follows REST naming conventions for listing books?

    A plural noun names the collection, and the HTTP method (GET) names the action.
  2. 2. What should a successful POST that creates a resource return?

    201 Created, usually with Location and the new resource, tells the client exactly what happened.
  3. 3. Why cap the limit parameter of a list endpoint?

    Without a cap, a single request can load enormous result sets and hurt performance for everyone.
  4. 4. Which change is safe to ship without a new API version?

    Existing clients ignore fields they do not know, so additions are backward compatible. Renames, removals and changed meanings break them.

Summary

  • Name resources with plural nouns and let the HTTP method be the verb.
  • Use precise status codes: 201 plus Location for creates, 204 for deletes, 4xx for client mistakes.
  • Use one JSON envelope for successes (data, meta) and one for errors (error.code, error.message).
  • Paginate with a default and a maximum, and whitelist filter and sort fields.
  • Version in the path (/api/v1) and treat additive changes as non-breaking.

Next: Controllers and Services.