This article describes the conventions that make a REST API predictable: how to name resources, which HTTP method and status code to use when, how to report errors, and how to paginate and version. It is for developers who are designing a new API or tidying up an existing one.
Most of these conventions come from HTTP itself. An API that uses HTTP the way the specification describes works with existing clients, caches and proxies, and a developer who has used one such API can guess how yours behaves.
What REST asks for
REST (Representational State Transfer) is the architectural style Roy Fielding described in his 2000 doctoral dissertation. It defines a set of constraints, and three of them shape everyday API design.
The first is statelessness. Each request carries everything the server needs to process it, including credentials, and the server keeps no session state between requests. Any instance can then handle any request, which is what makes horizontal scaling straightforward.
The second is a uniform interface. Clients work with resources identified by URLs, through a small fixed set of methods whose meaning is the same everywhere. The URL says what is being acted on and the method says how.
The third is cacheability. Responses state whether they may be cached, so clients and intermediaries can reuse them.
Few production APIs satisfy every constraint in the dissertation, hypermedia in particular. What people usually mean by a REST API is JSON over HTTP with resource-oriented URLs and correct use of methods and status codes. That is the subject of the rest of this article.
Model resources, not actions
A resource is a thing the API exposes: a user, an order, an invoice. Name resources with nouns and let the HTTP method express the action. GET /users is preferable to /getUsers, and DELETE /users/123 to /deleteUser?id=123.
Resources come in two shapes. A collection, such as /users, is a list, and an item, such as /users/123, is one member of it. Use plural nouns for collections, and be consistent about it throughout the API.
Where one resource belongs to another, nest it. /users/123/posts reads as the posts of user 123. Keep nesting to one level. A post that has its own ID can be addressed as /posts/456, and a path such as /users/123/posts/456/comments/789 adds length without adding information.
A few naming rules prevent most inconsistencies:
- Use lowercase letters, with hyphens between words:
/shipping-addresses. - Use the path for identity and the query string for filtering, sorting and pagination:
/orders?status=shipped&sort=-created_at. - Choose one case style for JSON field names,
camelCaseorsnake_case, and use it everywhere. - Leave file extensions and trailing slashes out of URLs.
Some operations are not naturally create, read, update or delete: cancelling an order, or sending a password reset email. Where possible, model the action as a resource of its own, such as POST /orders/123/cancellation. Where that would be contrived, a POST to a verb sub-path such as /orders/123/cancel is an accepted exception. Keep such exceptions few and document them.
Use HTTP methods as defined
Each method has semantics defined in RFC 9110, and clients, proxies and libraries rely on them. Two properties matter most. A safe method does not change state on the server. An idempotent method has the same effect whether it is sent once or several times, which means a client can retry it after a timeout without risk.
| Method | Purpose | Safe | Idempotent |
|---|---|---|---|
GET | Read a resource or collection | Yes | Yes |
POST | Create a resource, or trigger an action | No | No |
PUT | Replace a resource in full | No | Yes |
PATCH | Update part of a resource | No | Not guaranteed |
DELETE | Remove a resource | No | Yes |
Applied to a users resource and a nested posts collection, the methods map onto requests like this:
GET /v1/users List users
POST /v1/users Create a user
GET /v1/users/123 Get one user
PUT /v1/users/123 Replace the user
PATCH /v1/users/123 Change some fields of the user
DELETE /v1/users/123 Delete the user
GET /v1/users/123/posts List the user's posts
POST /v1/users/123/posts Create a post for the userNever change state in response to a GET. Crawlers, link previews and caches issue GET requests freely, and an endpoint such as GET /users/123/delete will eventually be triggered by one of them.
The difference between PUT and PATCH is completeness. A PUT body is the whole new representation, so a field left out is a field removed or reset. A PATCH body lists only the changes. If the API supports partial updates only, offer PATCH and leave PUT out.
POST is not idempotent, so a client that retries after a timeout may create a duplicate. For operations where that matters, such as payments or orders, accept a client-generated Idempotency-Key header, store the result against it, and return the stored result when the same key arrives again.
Return accurate status codes
The status code is the first thing a client checks, and often the only thing its error handling branches on. Use the most specific code that applies, and never return 200 with an error described in the body: monitoring, retries and caches all treat that response as a success.
| Code | Meaning | When to use it |
|---|---|---|
200 OK | Success | A GET, PUT or PATCH that returns a body |
201 Created | Resource created | A successful POST; include a Location header with the new URL |
204 No Content | Success, no body | A successful DELETE, or an update that returns nothing |
400 Bad Request | Malformed request | Invalid JSON, or missing or invalid parameters |
401 Unauthorized | Not authenticated | Credentials are missing or invalid |
403 Forbidden | Not allowed | Credentials are valid but lack permission |
404 Not Found | No such resource | The URL does not match an existing resource |
409 Conflict | State conflict | A duplicate, or an edit based on a stale version |
422 Unprocessable Content | Semantically invalid | Well-formed input that breaks a validation rule |
429 Too Many Requests | Rate limited | The client exceeded a limit; include Retry-After |
500 Internal Server Error | Server fault | An unhandled error on the server |
503 Service Unavailable | Temporarily down | Overload or maintenance; include Retry-After if known |
The split between 4xx and 5xx is a statement about who has to act. A 4xx tells the client its request is wrong and that sending it again unchanged will not help. A 5xx tells the client the fault is on the server and a later retry may succeed. Some APIs use 400 for all validation failures and never return 422. Either choice is fine as long as it is applied consistently.
A successful creation looks like this:
HTTP/1.1 201 Created
Location: /v1/users/124
Content-Type: application/json
{"id": 124, "name": "Ada Lovelace", "email": "ada@example.com"}Make errors useful
A status code says what category of thing went wrong. The body should say exactly what, in a form a program can act on and a developer can read. Use one error format for every endpoint.
RFC 9457, Problem Details for HTTP APIs, defines a standard JSON format for this with the media type application/problem+json. It has a few fixed fields and allows extensions, such as the errors array below.
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/validation-error",
"title": "The request body is not valid",
"status": 422,
"detail": "Two fields failed validation.",
"errors": [
{"field": "email", "message": "must be a valid email address"},
{"field": "age", "message": "must be 18 or greater"}
]
}Whichever format you choose, include a stable machine-readable identifier (the type URI here) so that clients do not have to match on message text, report all validation failures at once rather than one per request, and keep internal details such as stack traces and SQL errors out of responses.
Paginate, filter and sort collections
Any collection that can grow needs pagination from the first release, because adding it later changes the response and breaks clients. Apply a default page size and enforce a maximum.
There are two common schemes. Offset pagination (?limit=20&offset=40) is easy to implement and lets a client jump to any page, but it becomes slow on large tables, and it skips or repeats items when rows are inserted while a client is paging. Cursor pagination returns an opaque token that marks where the next page starts. It stays fast and stable at any depth, at the cost of not being able to jump to an arbitrary page.
A cursor-paginated response wraps the items and tells the client how to continue:
{
"data": [
{"id": 124, "name": "Ada Lovelace"},
{"id": 123, "name": "Alan Turing"}
],
"pagination": {
"next_cursor": "eyJpZCI6MTIzfQ",
"has_more": true
}
}Returning an object rather than a bare array also leaves room to add metadata later without a breaking change.
Filtering and sorting belong in the query string. Use field names as filter parameters (?status=active), a single sort parameter with a prefix for descending order (?sort=-created_at), and reject unknown parameters with 400 so that a misspelled filter is not silently ignored.
Version from the start
Clients depend on an API's exact behaviour, so the provider needs a way to make incompatible changes without breaking them. Decide on the versioning scheme before the first release.
The most common scheme puts a major version in the path, as in /v1/users. It is visible in every request and log line, and easy to route. The alternative is a request header, either a custom one or a versioned media type in Accept, which keeps URLs stable but makes the version easy to overlook and harder to test from a browser or a quick curl command. Path versioning is the pragmatic default. APIStack's own APIs use it: the Public Holidays API, for example, is served under /api/data/public-holidays/v1.
A new version is needed only for breaking changes: removing or renaming a field, changing a type, adding a required parameter, or changing what a status code means. Adding an optional parameter, a new endpoint or a new response field is backwards compatible, provided clients are told to ignore fields they do not recognise.
Document the contract
An API is only as usable as its documentation. Describe it in OpenAPI, a machine-readable format from which reference pages, client libraries and request validators can be generated. Keeping that description in the same repository as the code, and checking responses against it in tests, stops the two drifting apart.
Good reference documentation covers, for each endpoint, the parameters with their types and constraints, a complete example request and response, every error the endpoint can return, and the authentication and rate limits that apply. A short getting-started guide that takes a new user from obtaining a key to a first successful call is worth as much as the reference.
Two cross-cutting concerns should be settled and documented alongside the design. Serve the API over HTTPS only and authenticate every request, as covered in API Security Best Practices. Apply rate limits and return 429 with Retry-After when they are exceeded, as covered in Understanding Rate Limiting and How to Handle It.
Summary
- Name resources with plural nouns, keep nesting shallow, and let the HTTP method express the action.
- Use methods as HTTP defines them:
GETnever changes state,PUTandDELETEare idempotent, andPOSTneeds an idempotency key if retries must be safe. - Return the most specific status code, never
200for a failure, and one consistent error format such as RFC 9457 problem details. - Paginate every collection from the first release, with cursors for large or frequently changing data.
- Put a major version in the path, change it only for breaking changes, and publish an OpenAPI description that is tested against the implementation.