Skip to main content

Search

Search problems, hooks, and pages

REST API Design Best Practices

A practical refresher on designing REST APIs well: choosing the right HTTP verb and status code, structuring resource paths, idempotency, pagination, versioning, and the mistakes that come up constantly in interviews.

0 viewsintermediateRESTAPI DesignHTTP

What "REST" actually constrains

REST (Representational State Transfer) is a set of architectural constraints, not a protocol or a library. The core idea is that a resource (a book, a user, an order) has a URL, and you interact with it using the standard HTTP verbs that already describe an action on that resource, instead of inventing a new verb-shaped URL for every operation (like /getBook or /deleteUserById). Most APIs that call themselves "REST APIs" are really "HTTP APIs that follow REST-like conventions", and interviewers almost always mean that pragmatic version, not the strict academic one.

Note

The strict version has a name too: HATEOAS

The full academic definition of REST includes HATEOAS (Hypermedia As The Engine Of Application State): a response should include links telling the client what it can do next, so a client barely needs to know any URLs in advance. Almost no production API actually does this, and interviewers rarely expect it, but knowing the term and being able to explain why most APIs skip it is itself a useful answer.

HTTP verbs and idempotency

Idempotency means calling an operation once has the same effect as calling it many times in a row. This matters enormously in practice: if a client's request times out and it retries, an idempotent operation is safe to retry blindly, while a non-idempotent one might duplicate work (charge a card twice, create two orders).

Verb
Meaning
Idempotent?
Typical status on success
GET
read a resource or collection, no side effects
yes
200 OK
POST
create a new resource (or trigger a non-idempotent action)
no
201 Created
PUT
replace a resource entirely with the given representation
yes
200 OK (or 204 No Content)
PATCH
partially update a resource, only the given fields
not guaranteed, but usually treated as yes
200 OK
DELETE
remove a resource
yes
204 No Content

Example

PUT vs PATCH is a favorite interview question

PUT means "here is the complete new state of this resource, replace it entirely": fields you omit are implicitly cleared. PATCH means "here are just the fields I want to change": fields you omit are left untouched. Sending a PUT with only 2 of a resource's 5 fields is a common bug: a naive PUT handler will wipe the other 3 fields to their defaults.

Note

In practice, plenty of real APIs implement PUT as a merge anyway

A spec-conformant PUT handler treats the whole body as the resource's new state, so an omitted field should be cleared. Many real-world APIs deliberately don't do this: they check each field for presence and only touch the ones that were sent, leaving the rest alone, which is really PATCH semantics running under the PUT verb. The usual reason is safety, not carelessness. If a client fetches a resource, the API later adds a new field, and that client's stale PUT payload doesn't include it, a truly conformant PUT would silently wipe that field for every user who saves from the outdated client. Merge-style PUT avoids that data loss at the cost of no longer being a "real" PUT. It's worth recognizing this as a deliberate, common tradeoff some teams make, not a mistake, while still knowing that the strictly correct answer (full replacement) is what most interviewers and API style guides expect.

Status codes: the vocabulary a client actually relies on

A REST API's status code is not decoration, it's the primary signal a client's error-handling code branches on, often before it even looks at the response body. Picking the right one (and picking it consistently) is one of the highest-leverage things you can get right in an API's design.

Code
Meaning
When to use it
200 OK
Success
a GET, PUT, or PATCH that succeeded and returns a body
201 Created
Success, new resource
a POST that created something new (often includes a Location header)
204 No Content
Success, no body
a DELETE, or a PUT/PATCH where returning the updated resource isn't needed
400 Bad Request
Client error, malformed
the request itself couldn't be parsed or is structurally invalid
401 Unauthorized
Client error, not authenticated
no credentials, or invalid/expired credentials, were presented
403 Forbidden
Client error, not authorized
valid credentials, but this identity isn't allowed to do this
404 Not Found
Client error, missing
no resource exists at this URL/id
409 Conflict
Client error, state conflict
the request conflicts with the resource's current state (e.g. a duplicate unique value)
422 Unprocessable Entity
Client error, semantic validation
well-formed request, but the data fails business-rule validation
429 Too Many Requests
Client error, rate limited
the client is being throttled; often paired with a Retry-After header
500 Internal Server Error
Server error
something broke on the server that the client could not have prevented

Warning

401 vs 403 is one of the most commonly confused pairs

401 means "I don't know who you are" (missing or invalid credentials), so the correct response is to log in. 403 means "I know exactly who you are, and you're not allowed to do this", so logging in again won't help. Returning 401 for a permissions problem (or vice versa) sends the client down the wrong recovery path.

Resource naming and URL structure

  • Use plural nouns for collections: /books, not /book or /getBooks, since the verb is already carried by the HTTP method.
  • Nest resources to express real ownership: /states/2/districts for "districts belonging to Andhra Pradesh", but avoid nesting more than one level deep before it becomes unwieldy.
  • Use query parameters for filtering, sorting, and pagination, not for identifying a specific resource: /books?genre=sci-fi is filtering; /books/41823 is identifying one specific book.
  • Keep URLs lowercase and hyphen-separated for multi-word segments (/published-books, not /publishedBooks or /published_books): this is a convention, not a hard rule, but consistency within one API matters more than which convention you pick.

Example

Try it in the playground

The REST API Playground's "state's districts" tab runs this exact example: GET /api/v1/states/2/districts returns the real districts belonging to Andhra Pradesh, one level of nesting deep, exactly as far as this convention should go.

Pagination: never return an unbounded list

Returning every row of a collection in one response works fine with 10 rows and becomes a production incident at 10 million. Pagination is not optional for any collection endpoint that could grow without bound, and there are two common shapes worth knowing.

Style
How it works
Tradeoff
Offset/limit (page-based)
?page=3&limit=20, the server skips (page-1)*limit rows and returns the next limit
Simple and intuitive, but a row inserted or deleted while paging through can shift results (an item appears twice or gets skipped)
Cursor-based
?after=<opaque-cursor>&limit=20, the cursor encodes a stable position, usually derived from a sort key like an id or timestamp
Stable even as the underlying data changes, and scales better on very large tables, but you lose the ability to jump directly to "page 7"

Example

Always return pagination metadata alongside the data

A paginated response should tell the client what it needs to fetch the next page without guessing: something like { data: [...], pagination: { page, limit, total } } for offset-based, or { data: [...], nextCursor } for cursor-based. A bare array with no metadata forces the client to infer whether there are more pages, which it usually gets wrong.

Note

Sorting: several conventions, one idea (field + direction)

Unlike offset vs. cursor pagination, which are genuinely different algorithms with different tradeoffs, sorting conventions are just different ways to spell the same two pieces of information: which field, and which direction. JSON:API's convention is ?sort=-population (a bare field name sorts ascending, a leading - flips it to descending, and a comma-separated list like ?sort=-population,name gives a tiebreaker). GitHub and Elasticsearch instead suffix the direction, like ?sort=population:desc. Plenty of hand-rolled APIs skip both and just use two separate params, ?sortBy=population&sortOrder=desc, which is more verbose but never ambiguous about which part is the field and which is the direction. None of these is more "correct"; the only real mistake is picking one and then being inconsistent about it across endpoints in the same API. The REST API Playground's ?sort= field on every GET_LIST request uses JSON:API's prefix convention.

Versioning: how to change an API without breaking existing clients

Once an API has real clients, you can't just change a field's shape or remove an endpoint; someone's code will break. Versioning is how an API evolves without pulling the ground out from under whoever already integrated with it.

  • URL versioning (/api/v1/books, /api/v2/books): the most common approach in practice, simple to route, trivially visible in logs and browser tabs, and easy for a client to pin to a specific version.
  • Header versioning (a custom header like Api-Version: 2, or an Accept header with a version-specific media type): keeps URLs stable across versions, but is easier for clients to get wrong or forget entirely.
  • Whichever style you pick, the real discipline is additive-first evolution: prefer adding new optional fields over changing or removing existing ones, and only cut a new version when a genuinely breaking change is unavoidable.

Authentication and authorization on every request

REST APIs are stateless by convention: the server should not need to remember anything about a client between requests (no server-side session tied to a specific request). That means every request needs to carry its own credentials, almost always as a bearer token in an Authorization header (Authorization: Bearer <token>), which the server validates independently on every single call.

Note

Try it with a real token

The QuickRecall API Playground takes this further than most demos: paste a real JWT (build one for free at jwt.io) and the playground genuinely verifies its HS256 signature and a required "aud" claim in your browser, no server involved. An empty, malformed, wrongly-signed, or claim-missing token is rejected exactly like a real API would reject it with a 401, and the playground shows you exactly which check failed.

A consistent error response shape

Every error response across an entire API should follow the same JSON shape, so client code can write one generic error handler instead of a special case per endpoint. A common, simple shape looks like:

{
  "error": {
    "code": 422,
    "message": "Validation failed",
    "fields": {
      "title": "required",
      "price": "must be a number"
    }
  }
}

The exact shape matters less than picking one and using it everywhere. A field-level error map (as above) is especially useful for 422 responses, since it lets a form on the client highlight the specific inputs that failed, instead of just showing one generic "something went wrong" message.

Practice these ideas hands-on

Reading about status codes and idempotency is one thing; seeing them happen is another. QuickRecall's REST API Playground (in the Node.js section of the sidebar) lets you send real GET/POST/PUT/PATCH/DELETE requests against a simulated zodiac signs/states/articles API, deliberately trigger any of the status codes from the table above, and, on its custom-resource tab, define your own field schema and get REAL 422/409/404 responses backed by real validation, persisted in your browser.