By Gaurav · · 25 min read
- rest
- api-design
- http
- architecture
- web
The first thing most teams learn about REST is a naming rule: put nouns in URLs, not verbs. The second is a status-code chart. Neither is the idea.
REST is an architectural style described by Roy Fielding in his 2000 dissertation as a set of constraints on network-based software. The constraints are the design. Nouns in URLs and 201 Created are consequences of applying some of them. An API can follow every URL convention in the style guide and still miss what makes REST useful. Another API can ignore half the conventions and accidentally capture the properties that matter.
This article takes the constraints seriously: what each one actually requires, what property it buys, what it costs, and how the choices show up in a real API. The goal is not purity. The goal is to know which levers you are pulling.
REST is a style, not a protocol
REST stands for Representational State Transfer. The name is often read as "transfer state," which is wrong in an important way. The client transfers a representation of a resource's state. The server remains the authority on the resource itself.
REST is not an RFC. There is no standards body that certifies an endpoint as RESTful. HTTP is a protocol that happens to provide the generic interface REST needs: methods, status codes, media types, cache directives, and conditional requests. JSON is a representation format. Neither is REST.
That distinction matters because "REST API" is used in industry to mean "HTTP API that returns JSON and uses nouns in paths." That is a useful shorthand, but it is not the architectural style. A REST API is one that accepts the constraints. An HTTP JSON API is one that uses HTTP as a transport. Both can be good. They are not the same claim.
The constraints are the part worth learning because they explain the tradeoffs:
- Why a stateless API scales horizontally more easily, and why every request pays for it.
- Why a cacheable
GETcan absorb enormous read traffic, and why aPOSTused for reads cannot. - Why a layered network makes retries and idempotency unavoidable.
- Why hypermedia keeps clients from hardcoding state transitions, and why most teams stop short of it.
[!NOTE] Three shortcuts cause most of the confusion: REST is not JSON, statelessness is not "no database," and
PUTis not "update the fields I sent." Each shorthand drops a constraint the rest of the design depends on.
The six constraints and the properties they buy
Fielding defines REST as an architectural style derived from a set of constraints. The exact list is often presented as six constraints, with code-on-demand as optional.
| Constraint | What it requires | What it buys | What it costs |
|---|---|---|---|
| Client-server | Separate the user interface from data storage and business logic | Independent evolution; a server can change without shipping a new client | A network boundary and a contract to maintain |
| Stateless | Each request carries the context needed to understand it | Horizontal scaling, simple failover, visible requests, easier retries | Bigger requests, repeated authentication, harder revocation |
| Cacheable | Responses declare whether they can be reused and for how long | Read traffic absorbed by caches; lower latency and backend load | Invalidation complexity and stale-data risk |
| Uniform interface | One generic interface for all resources: identification, representations, self-describing messages, hypermedia | Simpler clients, visible interactions, independent evolvability | Less hand-optimized than a purpose-built protocol |
| Layered system | Clients cannot assume they are talking directly to the origin | Proxies, gateways, CDNs, and load balancers can be inserted | More places to misconfigure caching, auth, and retries |
| Code-on-demand (optional) | Servers may send executable code to clients | Extensibility without shipping a new client | Security and trust complexity |
The constraints interact. Statelessness makes layering practical because any layer can route a request without knowing what happened in the previous one. Cacheability depends on the uniform interface because a cache needs to understand the method and the response metadata without knowing the application. The uniform interface makes independent evolution possible because clients depend on media types and links rather than private implementation details.
Drop one constraint and you do not lose a badge. You lose a property.
Client-server
The client owns the user experience. The server owns the data and the rules. The boundary lets each side evolve independently: a web client, a mobile client, and a partner integration can share one API without sharing one release cycle.
The cost is the contract. Once the boundary exists, every change to the contract has to be planned. That is why versioning, deprecation, and error semantics are not afterthoughts; they are the price of independent evolution.
Stateless
In a stateless interaction, the server does not need to remember anything about the client between requests to interpret the next request. The request carries its own context: the identity token, the resource identifier, the conditional version, the cursor, the idempotency key.
Statelessness is not "the server stores no data." It stores resources. It may store sessions as resources. The constraint is that the request must not depend on a hidden conversation that only the server remembers. If a request succeeds only because it arrived on the same machine that handled the previous request, the interaction is stateful.
Cacheable
Every response should say, explicitly or by protocol default, whether it can be reused. A response that is cacheable can be served by a browser, a shared proxy, or a CDN without touching the origin. A response that is not cacheable forces every client to ask again.
Caching is not a performance feature bolted on after the API works. It is part of the API's meaning. A GET that changes state is not a fast endpoint; it is a broken one, because caches, prefetchers, and retry layers are allowed to repeat it.
Uniform interface
The uniform interface is the constraint people underestimate. It says that all resources are manipulated through the same generic interface rather than through application-specific operations. In HTTP that means methods, URIs, headers, status codes, and media types.
The uniformity is what lets a cache, a proxy, or a browser understand a request without understanding your domain. It is also what makes APIs feel repetitive: every resource uses the same verbs and the same status-code vocabulary. That repetition is the point.
Layered system
A client should behave correctly whether it is talking to the origin, a reverse proxy, an API gateway, a CDN, or a service mesh. Each layer may cache, authenticate, rate-limit, retry, or transform a message. The client cannot assume a direct connection, and the server cannot assume the request arrived unmodified.
Layering is why absolute URLs, forwarded headers, trust boundaries, and idempotency matter. It is also why a request that works in development can fail behind a proxy that retries a POST.
Code-on-demand
Code-on-demand is the optional constraint: a server can send executable code to a client, such as JavaScript in a browser. It extends the client without a new release, but it introduces a trust problem. Most APIs ignore this constraint; it is not required for REST.
The uniform interface is four constraints in a trench coat
The uniform interface is often summarized as "use HTTP methods and status codes." That is only the second half. The full constraint has four parts:
- Identification of resources. Every interesting thing is identified by a stable URI. A resource can be a document, a row, a collection, a job, a search result, or a singleton such as the current user's cart.
- Manipulation of resources through representations. Clients do not mutate the resource directly. They send a representation that describes the desired state, and the server decides what that means.
- Self-descriptive messages. Each message carries enough metadata to be processed: method, URI, media type, status code, cache directives, and any conditional headers.
- Hypermedia as the engine of application state. Clients move between states by following links supplied in representations, rather than by hardcoding every transition.
Most production APIs implement the first three and a small part of the fourth. That is a legitimate design choice, but it is not full REST. It is closer to what the Richardson Maturity Model calls Level 2: resources and HTTP verbs, without hypermedia controls.
Resources are nouns; representations are snapshots
A resource is a concept that can be named. A representation is a byte sequence that describes the resource's current state. The URI identifies the resource; the representation is what travels over the wire.
GET /orders/ord_1 HTTP/1.1
Accept: application/json
{
"id": "ord_1",
"status": "open",
"totalCents": 4200,
"_links": {
"self": "/orders/ord_1",
"items": "/orders/ord_1/items",
"cancel": "/orders/ord_1/cancel"
}
}
The same resource can have several representations. A browser might ask for HTML, a mobile app for JSON, and a reporting job for CSV. The server chooses a representation through content negotiation. The resource does not become a different thing because the format changed.
This is also why "the API returns the database row" is a dangerous mental model. A resource is a contract, not a table. It can combine fields from several tables, omit internal columns, include computed values, and expose links that have no database counterpart. If the representation mirrors the schema, every schema migration becomes an API migration.
Modelling resources that survive contact with clients
Resource modelling is where most of the design work happens. A few rules cover most cases:
| Need | Shape | Example |
|---|---|---|
| A collection | Plural noun | GET /orders |
| One item | Collection plus identifier | GET /orders/ord_1 |
| A child collection | Sub-resource, sparingly | GET /customers/c_1/orders |
| A state transition | Action sub-resource or explicit state field | POST /orders/ord_1/cancel |
| A singleton | Singular noun | GET /me, GET /settings |
| A long-running job | Job resource with status | POST /imports, GET /imports/imp_1 |
| A search result | Query resource | GET /orders?status=open&sort=-createdAt |
A few practical rules:
- Use nouns for things, not verbs for operations.
POST /orderscreates an order.GET /getOrdersis an RPC call wearing a REST costume. - Do not mirror the database. Deep nesting that follows foreign keys produces brittle URLs. Two levels are usually enough; beyond that, use top-level resources with filters.
- Model actions explicitly when they are not CRUD.
POST /orders/{id}/cancelis clearer than forcing aPATCH statusthat hides the domain rule. A state change with side effects deserves a named operation. - Make identifiers opaque and stable. UUIDs, ULIDs, or prefixed IDs are safer than sequential integers when enumeration is a risk. Never change the identifier format within a version.
- Prefer client-generated identifiers for idempotent creates.
PUT /orders/{clientId}lets a client retry a create without creating a duplicate. - Do not expose internal identifiers or storage details. The resource ID is part of the public contract; the primary key is not.
Resource design is contract design. A bad URL is easy to change before launch and expensive to change after clients depend on it.
A worked example: checkout
A checkout flow shows how the constraints fit together. The resource model is not the database schema; it is the sequence of things a client can name and act on.
| Step | Request | Design reason |
|---|---|---|
| Browse products | GET /products?category=books |
Safe and cacheable; the catalog is shared |
| Create a cart | POST /carts → 201 + Location: /carts/cart_1 |
Creates a new resource; not idempotent without a key |
| Add an item | POST /carts/cart_1/items |
Creates a sub-resource; use PUT /carts/cart_1/items/{sku} if the operation is naturally idempotent |
| Read the cart | GET /carts/cart_1 |
User-specific; mark it private or no-store, not public |
| Place the order | POST /orders with Idempotency-Key |
The write is not idempotent, but a retry must not create two orders |
| Track the order | GET /orders/ord_1 |
The order is the resource; its status is part of the representation |
| Cancel the order | POST /orders/ord_1/cancel |
A state transition with side effects; return 409 if it already shipped |
Each row answers a constraint question. Is the operation safe? Is it idempotent? Can the response be cached? Who owns the state? The URL follows from those answers, not from the table names in the database.
HTTP is the uniform interface in practice
HTTP supplies the generic vocabulary REST needs; the semantics are defined in RFC 9110. The vocabulary is small, but the precision matters.
Methods have meaning, not just mechanics
| Method | Safe | Idempotent | Cacheable | Typical use |
|---|---|---|---|---|
GET |
Yes | Yes | Yes | Read a representation |
HEAD |
Yes | Yes | Yes | Read headers without a body |
OPTIONS |
Yes | Yes | No | Discover communication options |
PUT |
No | Yes | No | Replace a resource with a complete representation |
DELETE |
No | Yes | No | Remove a resource |
POST |
No | No | Only with explicit freshness (rare) | Create a subordinate resource, or perform a non-idempotent action |
PATCH |
No | Not guaranteed | No | Apply a partial modification |
Two definitions are worth keeping exact:
- Safe means the request is not intended to change server state, and a correct server must not change state in response to it. Safe methods can be repeated, prefetched, or crawled;
GETandHEADare also cacheable. - Idempotent means that repeating the request has the same intended effect on the server as making it once. The response can differ: the first
DELETEmight return204and the second404, but the resource ends up in the same state.
PUT replaces the resource. If a client sends only the fields it wants to change and calls it PUT, the omitted fields may be erased. PATCH is for partial modifications, but it is not automatically idempotent. A patch that says "increment the counter" is not idempotent even though it uses PATCH. The media type defines the patch semantics: JSON Merge Patch, JSON Patch, or a domain-specific format.
Using POST for reads is a common shortcut. It breaks caching, safety, and retry semantics all at once. If a query is too complex for a URL, consider a POST-based search resource with an explicit Cache-Control: no-store, or move the query into a dedicated read API. Do not silently turn a read into a state-changing method.
Status codes are the response contract
Status codes are not decoration. They tell caches, proxies, clients, and humans what happened. A useful subset:
| Code | Meaning | Notes |
|---|---|---|
200 OK |
Success with a body | The default for a successful read |
201 Created |
A new resource exists | Include a Location header |
202 Accepted |
Work is queued | Return a job resource to poll |
204 No Content |
Success without a body | Common for DELETE and empty updates |
304 Not Modified |
The cached representation is still valid | Used with conditional requests |
400 Bad Request |
Malformed request | Not a substitute for every validation error |
401 Unauthorized |
Authentication is missing or invalid | The name is historical; it means authentication is missing or failed |
403 Forbidden |
The caller is not allowed | The caller may be known or anonymous; do not conflate with 401 |
404 Not Found |
The resource does not exist, or should not be revealed | Security-sensitive resources often return this instead of 403 |
405 Method Not Allowed |
The method is not supported for this resource | Include an Allow header |
409 Conflict |
The request conflicts with the resource's current state | Common for duplicate keys and state transitions |
412 Precondition Failed |
A conditional header did not match | Used with If-Match for lost-update protection |
415 Unsupported Media Type |
The request body's media type is not accepted | Be explicit about what you accept |
422 Unprocessable Entity |
The syntax is valid but the semantics are not | Defined by WebDAV and widely used; pick one validation convention and document it |
429 Too Many Requests |
The caller exceeded a quota | Include Retry-After |
500 Internal Server Error |
An unexpected server failure | Do not leak stack traces |
503 Service Unavailable |
Temporary overload or maintenance | Include Retry-After when possible |
A 200 with { "error": ... } inside it is not a success. It hides failures from every generic HTTP component and forces every client to parse the body to know whether the call worked.
Self-descriptive messages
A message should be understandable without out-of-band knowledge. In HTTP that means:
- a meaningful method and URI,
- an accurate
Content-Type, - an
Acceptheader that states what the client can handle, - cache directives that describe reuse,
- conditional headers that describe preconditions,
- a request ID for support and tracing,
- a response body whose shape matches its media type.
This is also where custom media types earn their keep. application/vnd.acme.order+json is more descriptive than application/json when the representation has domain-specific semantics. Most teams do not need custom media types, but they should not pretend that application/json says anything about the schema.
Statelessness does not mean no state
Statelessness is one of the most misunderstood constraints. It does not mean the server cannot store data. It means the server must not require hidden per-client conversational state to interpret a request.
There are three different things people call "state":
- Resource state. The order is open, the user's email is verified, the inventory count is 42. This belongs on the server and is usually in a database.
- Client state. The current screen, the selected tab, the draft in a form. This belongs on the client.
- Session state. "This user authenticated five minutes ago and is midway through a checkout." This is the tricky one. If the server stores it under a session ID and the client sends only a cookie, the interaction still carries a reference to server-side state. That can be acceptable, but it is not the same as a stateless request, and it changes how you scale and recover.
A stateless request carries its context: an access token, a resource version, a cursor, an idempotency key. Any server instance can handle it. A load balancer does not need sticky sessions. A failed instance does not take a user's session with it.
The costs are real:
- Tokens are larger than a session cookie and may need to be verified on every request.
- Revoking a stateless token before it expires requires a denylist or short expiry plus refresh.
- Every request repeats authentication and authorization work.
- Some interactions are naturally stateful, such as multi-step negotiations or long-lived connections.
The answer is not to hide state in a server-side session and call it REST. The answer is to decide which state belongs in the resource, which belongs in the client, and which belongs in a short-lived token or a session resource with an explicit lifecycle.
[!NOTE] A session store is not automatically a violation of REST. A session can be modelled as a resource: create it, read it, expire it. What breaks the constraint is a request that only works because the server remembers an earlier request on the same connection or the same process.
Caching is part of the API, not the CDN's problem
Caching is where the uniform interface pays for itself. A cache does not need to understand your domain. It needs to know the method, the URI, the response status, and the cache metadata. For the full lifecycle of freshness, validation, and invalidation, see HTTP Caching Is a Correctness Problem.
There are two ways to avoid sending a full response:
- Freshness. The response says it is valid for some time.
Cache-Control: max-age=60means a client may reuse it for 60 seconds without asking the origin.s-maxageapplies to shared caches.privatekeeps it out of shared caches.no-storeforbids storage. - Validation. The client stores a validator such as an
ETagorLast-Modifiedand asks the server whether it is still current. If it is, the server returns304 Not Modifiedwith no body.
const order = {
version: 7,
body: { id: "ord_1", status: "open", totalCents: 4200 },
};
const etag = () => `"v${order.version}"`;
function getOrder(ifNoneMatch) {
const current = etag();
if (ifNoneMatch === current) {
return { status: 304, headers: { ETag: current } };
}
return {
status: 200,
headers: {
ETag: current,
"Cache-Control": "private, max-age=60",
Vary: "Accept-Encoding",
},
body: order.body,
};
}
const first = getOrder(null);
console.log("first GET:", first.status, first.headers.ETag);
const revalidated = getOrder(first.headers.ETag);
console.log("revalidation:", revalidated.status);
order.version += 1;
order.body.status = "shipped";
const changed = getOrder(first.headers.ETag);
console.log(
"after update:",
changed.status,
changed.headers.ETag,
changed.body.status,
);
The first request returns a body and an ETag. The second returns 304, which saves bandwidth but still costs a round trip. The third returns a new representation because the version changed. That is the whole validation loop.
Several details decide whether caching is correct or merely present:
Varymust list the request headers that select a representation. A response that changes withAccept-EncodingneedsVary: Accept-Encoding; otherwise a shared cache can hand a compressed body to a client that asked for identity. Authentication is separate: responses to requests withAuthorizationare not shared-cacheable by default, and tenant data needsprivateor a correct cache key, not just a header.- Unsafe methods invalidate the URI. A successful
PUT,PATCH, orDELETEshould invalidate cached representations of that resource, and often of related collections. GETmust be safe. Caches and prefetchers are allowed to repeat it. AGETthat writes is a data-corruption bug waiting for a crawler.- Cache keys must include the tenant.
privateandVarymatter, but a multi-tenant CDN also needs a cache key that distinguishes tenants. TheAuthorizationheader is not a substitute for a correct key. - Invalidation is a design problem, not a purge button. Versioned URLs work for immutable assets. For mutable resources, short freshness plus validators is usually safer than aggressive invalidation.
[!WARNING] A cache that serves a stale authorization decision, a stale price, or another tenant's data is not a performance problem. It is a security incident. Treat caching as part of the correctness contract.
Layering means the network can change under you
The layered-system constraint says a client cannot assume it is talking directly to the origin. Requests may pass through TLS terminators, reverse proxies, API gateways, CDNs, service meshes, and sidecars. Each layer may authenticate, authorize, cache, retry, rate-limit, or transform the message.
This is not an edge case. It is the normal production path. The consequences show up in several places:
- Do not build security on network position. "Only the internal network can call this" is not authorization. Internal traffic can be compromised, and a gateway can be misconfigured. Authenticate and authorize at the service boundary.
- Do not assume a request is executed once. A proxy may retry a request after a timeout. An idempotent operation survives that; a non-idempotent one does not. The retry layer is often invisible to the application.
- Propagate identity and request IDs. A request ID should survive every hop so a trace can be reconstructed. Forwarded headers need a defined trust boundary; do not blindly trust
X-Forwarded-For. - Use URLs that work behind a proxy. Relative or well-formed absolute URLs avoid host and scheme confusion. If you emit absolute links, derive them from a configured public base URL, not from the incoming
Hostheader alone. - Expect caching at more than one layer. A browser cache, a CDN, and a service mesh may all make different decisions. The origin's cache headers are the contract they should follow.
The retry article covers the failure side of this in detail: The Retry Is the Outage. The REST-specific lesson is that layering is why idempotency and safe methods are not academic. The network will repeat, reorder, and cache requests whether the API is ready or not.
Hypermedia and the maturity model
HATEOAS stands for Hypermedia as the Engine of Application State. The idea is simple and frequently skipped: the server includes links in the representation, and the client follows those links to discover what it can do next.
{
"id": "ord_1",
"status": "open",
"totalCents": 4200,
"_links": {
"self": { "href": "/orders/ord_1" },
"items": { "href": "/orders/ord_1/items" },
"cancel": { "href": "/orders/ord_1/cancel", "method": "POST" },
"payment": { "href": "/payments?orderId=ord_1" }
}
}
When the order ships, the cancel link can disappear. When a payment is required, a pay link can appear. The client does not need a hardcoded table of which states allow which operations. It reads the representation.
That is a real benefit for long-lived public APIs with many clients. It reduces coupling to URL templates and makes state-dependent affordances discoverable. It also gives pagination a natural home: the response includes next, prev, and first links instead of asking the client to construct query strings.
Why do most APIs stop short? Because full hypermedia is a significant design commitment:
- Clients and SDKs must actually follow links instead of hardcoding paths.
- Documentation must explain link relations, not just endpoints.
- Tooling and testing need to understand media types and link semantics.
- Teams often optimize for a small number of known clients, where hardcoded URLs are simpler and faster to ship.
The Richardson Maturity Model describes a common progression:
| Level | Name | What it adds |
|---|---|---|
| 0 | The Swamp of POX | One endpoint, one verb, usually POST |
| 1 | Resources | Individual URIs for individual things |
| 2 | HTTP verbs | Methods and status codes used semantically |
| 3 | Hypermedia controls | Links drive state transitions |
It is a useful vocabulary, not a scorecard. Fielding has criticized the model because it can imply that Level 2 is "almost REST" when the hypermedia constraint is central to his definition. The pragmatic reading is this: Level 2 is a perfectly good HTTP JSON API. Level 3 is a different set of tradeoffs. Do not claim Level 3 unless clients can actually navigate by links.
A middle path works well for many teams:
- Include links for pagination and for actions whose availability depends on state.
- Use stable link relations such as
self,next,prev,first,last,create,cancel. - Keep the URL structure documented and stable for clients that ignore links.
- Version the link relations and the action semantics as part of the contract.
That is not full HATEOAS, but it captures most of the practical value without pretending the client is a generic hypermedia browser.
Writes, concurrency, and the license to retry
REST's read path is mostly about identity and caching. The write path is about correctness under concurrency and retries.
Two clients read the same order at version 7. Both edit it. Without a precondition, the second write silently overwrites the first. This is the lost update problem, and it is a property of the API contract, not of the database.
The HTTP fix is optimistic concurrency:
GET /orders/ord_1
ETag: "v7"
PATCH /orders/ord_1
If-Match: "v7"
Content-Type: application/merge-patch+json
{ "shippingAddressId": "addr_9" }
If the resource is still at version 7, the update succeeds and the server returns a new ETag. If another client already changed it, the server returns 412 Precondition Failed, and the client re-reads before deciding what to do. 409 Conflict is appropriate when the request conflicts with the resource's state in a domain sense, such as trying to cancel an order that has already shipped. 412 is specifically about a failed precondition.
Idempotency is the other half. A retry is safe when repeating the operation has the same effect as doing it once. PUT and DELETE are defined as idempotent. POST is not, so a create needs an explicit idempotency key when the client may retry.
const responses = new Map();
let charges = 0;
function createCharge(key, amountCents) {
if (responses.has(key)) {
return { replayed: true, ...responses.get(key) };
}
charges += 1;
const response = {
id: `ch_${charges}`,
amountCents,
status: "captured",
};
responses.set(key, response);
return { replayed: false, ...response };
}
console.log(createCharge("checkout-91f3", 4200));
console.log(createCharge("checkout-91f3", 4200));
console.log(createCharge("checkout-4a07", 4200));
console.log({ actualCharges: charges });
The second call with the same key returns the stored response instead of charging again. The third call uses a new key and performs new work.
The implementation details matter:
- Store the key and the response durably. A key kept only in memory disappears on restart and the duplicate comes back.
- Scope the key to the caller and the operation. Two different users can use the same key string without colliding.
- Use a unique constraint or lock on the key. A read-then-write check races. The first insert owns the work; the second waits or returns the stored response.
- Set a retention window longer than the maximum retry window. If the key expires before the client stops retrying, the operation can run twice.
- Return the same status and body for a replay. A client that retries should not have to handle a different success shape.
This is the same lesson as the retry article from the other direction: idempotency is the license to retry, and retries are how the network turns a single client intention into multiple requests.
Errors, evolution, and versioning
An error is a representation too. It should be machine-readable, stable, and safe to show to a developer without leaking internals.
RFC 9457 defines Problem Details for HTTP APIs:
{
"type": "https://api.example.com/problems/insufficient-funds",
"title": "Insufficient funds",
"status": 409,
"detail": "The account has 1200 cents available but the transfer requires 5000.",
"instance": "/transfers/tr_123",
"code": "insufficient_funds",
"requestId": "req_01H..."
}
The useful parts are the stable code or type, the actionable detail, and the requestId that connects the error to a trace. Field-level validation errors belong in an extension field, not in a prose message that clients have to parse.
Evolution is where REST's promises are tested. Within a version:
- Add fields; do not remove or rename them without a deprecation plan.
- Do not change a field's type or meaning.
- Tolerate unknown fields in responses so additive changes do not break clients.
- Treat enum values as open unless the contract says otherwise; a new value can break a strict client.
- Keep error codes stable; humans can read messages, machines branch on codes.
- Test against real clients, not just against the server's own schema.
Versioning is a tool, not a strategy. A path version (/v2/orders) is easy to understand and route. A media-type version (application/vnd.acme.v2+json) is closer to REST's content-negotiation model. A header version can work but is easy to miss in logs and caches. Whichever you choose, define the deprecation policy: overlap window, Deprecation and Sunset headers, migration guide, and usage telemetry that tells you when it is safe to remove the old version.
The best versioning strategy is the one that makes most changes additive. REST does not remove the need for compatibility discipline. It gives you a vocabulary for evolving representations without breaking every client at once.
Security and operations are part of the contract
REST's constraints create a network boundary, and every boundary is a security boundary. A production API needs more than resource names and status codes:
- Authentication identifies the caller. Authorization decides what that caller may do, per object, not just per route. A user who can read their own order should not be able to read someone else's by changing an ID.
- Validate input at the boundary. Reject malformed fields, enforce size limits, and never pass user input directly into a query or shell. Decide explicitly whether unknown input fields are ignored for forward compatibility or rejected as a typo.
- Rate-limit per caller and per operation. Return
429withRetry-After, and document the quota. Protect expensive endpoints separately from cheap reads. - Use TLS everywhere. A REST API that travels over plaintext is not a contract; it is a leak.
- Handle CORS and CSRF deliberately. CORS is a browser permission model, not authentication. Cookie-based APIs need CSRF protection; token-based APIs need careful token storage.
- Log the contract, not the secrets. Record method, route, status, latency, caller, and request ID. Do not log tokens, passwords, or full payment data.
- Publish the operational contract. Latency expectations, rate limits, retry guidance, idempotency behavior, pagination limits, and deprecation policy belong in the docs, not in a support ticket.
Observability is part of the same story. Trace one logical request from the edge to the database. Record the route, the status, the resource ID, and the version. Without that, a cache hit, a retry storm, and a client bug all look like "more traffic."
When REST is the wrong tool
REST is a strong default for resource-oriented APIs with broad clients and cacheable reads. It is not the only good design, and forcing every interaction into resources produces worse APIs.
| Need | Better fit | Why |
|---|---|---|
| Client-shaped aggregate reads | GraphQL | One request can fetch a graph of fields the screen needs |
| Low-latency service-to-service calls with streaming | gRPC | Typed contracts, binary encoding, streaming, generated clients |
| Server push for feeds or presence | SSE or WebSockets | Long-lived connections are the point |
| Event fan-out to many consumers | Webhooks or queues | Delivery is asynchronous and decoupled from the request |
| Complex transactional commands | RPC-style command endpoint | The operation is an action, not a resource state change |
The choice is not "REST versus RPC" as a purity test. Most real systems mix styles: REST for the public resource API, gRPC between internal services, webhooks for events, and a command endpoint for an operation that does not fit a resource lifecycle. The important thing is to be explicit about which contract each surface offers.
A review checklist
If you are designing or reviewing a REST API, these are the questions that catch most of the expensive mistakes:
- Are resources named as nouns, with identifiers that are stable and opaque?
- Do methods match their semantics:
GETsafe,PUT/DELETEidempotent,POSTfor non-idempotent creates or actions? - Are status codes accurate, and does every error have a stable machine-readable code?
- Do representations have explicit media types, and do error bodies follow a documented shape?
- Is every collection paginated with a bounded page size and a stable sort?
- Are cache headers and validators present on cacheable reads, with
Varywhere the representation depends on request headers? - Does each request carry the context it needs, without hidden server-side session state?
- Do writes define concurrency behavior with
ETag/If-Matchor a version field? - Do non-idempotent creates accept an idempotency key with a durable, correctly scoped store?
- Are changes additive within a version, with a real deprecation plan for breaking ones?
- Are authentication, object-level authorization, rate limits, and request IDs enforced at the boundary?
- Do responses include links for pagination and state-dependent actions where clients benefit?
- Is the API documented as a contract, not just a list of endpoints?
The constraints are the design
REST is not a badge you earn by using plurals and 201 Created. It is a set of constraints that buy specific properties: independent evolution, cacheability, visibility, and the ability to put intermediaries between a client and a server without breaking the contract.
Those properties are not free. Statelessness costs per-request work. Caching costs invalidation discipline. A uniform interface costs some hand-optimization. Layering costs trust boundaries. Hypermedia costs client complexity. The point is to choose the constraints you need and know what you are giving up.
If you implement resources, HTTP methods, and status codes but skip hypermedia, you have built a good HTTP JSON API. That is a legitimate outcome. Call it what it is. The trouble starts when a team says "REST" and assumes it has bought the properties without paying for the constraints.
The next time you design an endpoint, ask which constraint it is exercising. If the answer is only "it has a noun in the path," you have designed a URL, not an architecture.
Distributed systems, databases, and the craft of shipping software.