Skip to content

REST API Design: Constraints, Resources, Idempotency, Versioning ​

"The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components." — Roy T. Fielding, Architectural Styles and the Design of Network-based Software Architectures, chapter 5, 2000

Summary: REST is a set of constraints, not a URL style; an HTTP API earns its benefits (caches, safe retries, generic tooling, independent evolution) only when it uses resources, methods, status codes and headers with the meaning HTTP gives them. Focus: Fielding's six constraints, resources and URI design, method semantics (safe, idempotent), JSON Patch vs JSON Merge Patch, precise status codes, content negotiation, HATEOAS and the Richardson maturity model, cursor/keyset pagination, filtering, sorting and sparse fieldsets, RFC 9457 Problem Details, the Idempotency-Key contract, ETag/If-Match optimistic concurrency, caching and RateLimit headers, bulk endpoints, long-running operations, a versioning summary, OpenAPI 3.1 contract-first, security basics and the big style guides, with a Go 1.22 net/http service and a Laravel 13 API. Learning goal: Given a domain, design its HTTP API on paper (resources, URIs, methods, codes, headers, pages, errors, concurrency, idempotency), write it down as an OpenAPI 3.1 contract, implement it in Go and Laravel, and defend every status code and header in a design review.

This chapter sits in the Networking & Protocols group after HTTP/1.1, HTTP/2, HTTP/3 (the wire) and before GraphQL, gRPC & Protocol Buffers and API Versioning & Evolution. It owns the design of one HTTP API: its resources, its contract and the HTTP semantics it relies on. It does not re-teach the neighbours: framing and connection reuse live in HTTP evolution; key storage, TTLs and crash recovery for idempotency live in API Idempotency; the SQL behind keyset pages lives in Pagination: Offset vs Keyset; version columns and retry loops in Optimistic vs Pessimistic Locking; token buckets in Rate Limiting; cache tiers in Caching and CDNs; deprecation and breaking-change policy in API Versioning; which style to use between services in Service Communication; the DDD view of REST resources in API Realization; and the Go router itself in net/http: Server, Client, 1.22 Routing.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why REST is constraints, not URLsWhy it exists, Where it comes from
Client-server, stateless, cacheable, uniform interface, layered, code on demandConstraints
Resource, collection, sub-resource, URI design, nestingResources and URIs
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS; safe vs idempotentMethods
JSON Patch vs JSON Merge PatchPATCH formats
Which status code, exactlyStatus codes
Accept, Content-Type, media types, 406/415Representations
HATEOAS, Richardson maturity modelHypermedia
Offset, cursor, keyset pagesPagination
Filtering, sorting, sparse fieldsetsQuery design
RFC 9457 error bodiesProblem Details
Idempotency-Key on POSTIdempotency keys
ETag, If-Match, 412, 428Optimistic concurrency
Cache-Control, 304, VaryCaching headers
RateLimit, RateLimit-Policy, 429, Retry-AfterRate-limit headers
Batch create, partial successBulk endpoints
202 Accepted and a status resourceLong-running operations
URI vs header vs media-type versionsVersioning summary
OpenAPI 3.1, contract-first, codegenOpenAPI
Auth, scopes, 401 vs 403 vs 404Security basics
Google AIP, Microsoft, ZalandoStyle guides
Knobs, header grammar, exact messagesMechanics
CodeGo, Laravel
Classic API bugs and their fixesSolving the classic problems
What to pickChoosing
Monolith to distributed systemIn architecture
curl against the Go serverLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The constraints (Fielding, chapter 5.1). Each one buys a property and costs something.

ConstraintIn plain wordsWhat it buysWhat it costs
Client-serverUI and data storage are separate programsEach side evolves and scales aloneA network between them
StatelessEvery request carries everything needed to understand itAny server can answer; easy scaling, retries, crash recoveryRepeated data per request (tokens, context)
CacheableResponses say whether they may be reusedFewer requests, lower latencyStaleness to manage
Uniform interfaceSame methods, codes and media types for every resourceGeneric clients, proxies, caches, toolingLess efficient than a tailor-made protocol
Layered systemA component sees only the next layerCDNs, gateways, load balancers can sit in betweenExtra hops and latency
Code on demand (optional)Server may send code the client runsThinner clientsLess visibility; optional for that reason

The methods (RFC 9110, section 9).

MethodSafeIdempotentCacheableTypical useTypical success
GETYesYesYesRead a resource or collection200, 206, 304
HEADYesYesYesHeaders only (size, ETag, existence)200
OPTIONSYesYesNoCapabilities, CORS preflight204 or 200
POSTNoNoOnly with explicit freshness, rarely usedCreate in a collection, run a process201, 202, 200
PUTNoYesNoReplace or create at a known URI200, 201, 204
PATCHNoNo (can be made so)NoPartial update with a patch document200, 204
DELETENoYesNoRemove204, 202, 200

The status codes you actually need.

CodeUse it whenNever use it for
200 OKSuccess with a bodyErrors with "ok": false inside
201 CreatedA new resource exists; send LocationUpdates
202 AcceptedWork queued; send a status URIWork that already finished
204 No ContentSuccess, nothing to return (DELETE)Responses that have a body
304 Not ModifiedConditional GET, client copy still validAnything but conditional requests
400 Bad RequestMalformed syntax, bad query parameter, missing required headerBusiness-rule failures
401 UnauthorizedNo or invalid credentials; send WWW-AuthenticateAuthenticated but not allowed
403 ForbiddenAuthenticated, not allowed, and existence is not secretHiding existence (use 404)
404 Not FoundNo such resource for this callerEmpty collections (that is 200 with [])
409 ConflictRequest conflicts with current state (bad transition, duplicate)Stale ETag (that is 412)
412 Precondition FailedIf-Match / If-Unmodified-Since evaluated falseMissing precondition (428)
422 Unprocessable ContentWell-formed JSON that breaks validation rulesBroken JSON (400)
428 Precondition RequiredServer demands a conditional writeStale ETag
429 Too Many RequestsRate limit hit; send Retry-AfterServer overload (503)
503 Service UnavailableServer overloaded or in maintenance; Retry-AfterClient mistakes

The header toolkit.

HeaderDirectionJobSection
LocationResponseURI of the created resource or status monitorStatus codes
Accept / Content-TypeBothContent negotiation and media typeRepresentations
ETag / If-None-MatchBothCheap revalidation, 304Caching
If-MatchRequestLost-update protection, 412Concurrency
Idempotency-KeyRequestSafe retry of POSTIdempotency
LinkResponseNext page, related resourcesPagination
Cache-ControlResponseWho may store, for how longCaching
RateLimit-Policy / RateLimitResponseQuota and what is leftRate limits
Retry-AfterResponseWhen to try again (429, 503, 202)Rate limits
Accept-PatchResponseWhich patch formats are acceptedPATCH
Null styleno constraintsClient-serverseparation ofconcerns: UI vsdata storageStatelesseach request carriesall it needs; noserver sessionvisibility, reliability,scalabilityCacheableresponses labelledcacheable or notefficiency, fewerround tripsUniform interface1 identificationof resources (URI)2 manipulation viarepresentations3 self-descriptivemessages (methods,media types, codes)4 hypermedia as theengine of app stateevolvability; costssome efficiencyCode on demand(optional)Layered systemeach layer sees onlythe next oneCDN, reverse proxy,gateway, loadbalancer in betweenEach step adds one constraint and the property it buysFielding 2000, chapter 5.1: REST derived from the null style

The picture is Fielding's derivation: start from a style with no constraints and add one at a time. The uniform interface is the tallest step because it is four constraints in one, and code on demand is drawn dashed because it is the only optional one.

Why it exists ​

Before REST had a name, the Web already scaled to millions of servers that had never met their clients. Fielding's dissertation explains why: every request is self-contained, every response says whether it may be cached, and every component speaks the same small vocabulary, so caches, proxies and browsers can work without knowing the application. An API that tunnels procedure calls through POST /api throws all of that away: no cache can store it, no proxy can retry it, no client library knows what failed.

RPC tunnelled over HTTPResource-oriented HTTP (REST-ish, level 2+)
One endpoint, verbs in the bodyOne URI per resource, verbs are HTTP methods
Always 200, error flag insideStatus code tells every intermediary what happened
Nothing cacheableGET is cacheable, ETag gives 304
Retries unsafe for everythingGET, PUT, DELETE retryable by definition; POST with a key
Client must read docs for every callGeneric clients, OpenAPI codegen, curl
Freedom to model anything as a callMust find the noun (cancellation, not cancelOrder)
Lowest effort on day oneSome design effort up front, much less later

The everyday picture. A public library. Every book has a shelf mark (the URI). There are a handful of standard forms everyone uses: borrow, return, reserve (the methods). The desk answers with a short set of stamps everybody understands: "on loan", "no such book", "come back tomorrow" (status codes). The catalogue card carries a "last updated" mark so you know whether your photocopy is still current (ETag), and a reservation slip has a number so handing it in twice does not reserve two copies (Idempotency-Key). Branch libraries can answer from their own copy of the catalogue without calling the central one (layered system and caching). The analogy returns throughout the page.

Three common misunderstandings, up front ​

  1. "REST means JSON over HTTP with nice URLs." REST is an architectural style with six constraints; JSON and pretty URLs are neither required nor sufficient. Most JSON APIs are Richardson level 2, which is useful but not what Fielding calls REST (Hypermedia).
  2. "POST is for create, PUT is for update." PUT means "store this representation at this URI" and is idempotent; it can create. POST means "process this according to your own rules" and is the right tool when the server picks the URI (Methods).
  3. "Idempotent means the same response every time." It means the same intended effect on the server. A second DELETE may answer 404 or 410 instead of 204 and still be idempotent (Methods).

Where it comes from ​

YearEventSource
1996–1999HTTP/1.0 (RFC 1945) and HTTP/1.1 (RFC 2068, then RFC 2616 in 1999); Fielding co-authors bothRFC 9110 lists the lineage
2000Fielding's PhD dissertation, chapter 5 "Representational State Transfer (REST)"ics.uci.edu
2008Fielding, "REST APIs must be hypertext-driven"roy.gbiv.com
2008Leonard Richardson's QCon talk; Fowler writes it up as the Richardson Maturity Model on 18 March 2010martinfowler.com
March 2010RFC 5789 defines PATCHrfc-editor.org
April 2012RFC 6585: 428, 429, 431, 511rfc-editor.org
April 2013RFC 6902 JSON Patchrfc-editor.org
October 2014RFC 7396 JSON Merge Patch (obsoletes RFC 7386)rfc-editor.org
March 2016RFC 7807 Problem Details for HTTP APIsrfc-editor.org
26 July 2017OpenAPI 3.0.0 published by the OpenAPI Initiative (the successor of Swagger 2.0)spec.openapis.org
October 2017RFC 8288 Web Linking (the Link header)rfc-editor.org
2010s–2020sGoogle AIP, Microsoft REST API Guidelines and Zalando RESTful API Guidelines published openly; the Azure guidelines changelog runs to 2024each guide
15 February 2021OpenAPI 3.1.0: Schema Object becomes a superset of JSON Schema 2020-12spec.openapis.org
June 2022RFC 9110 HTTP Semantics and RFC 9111 HTTP Caching replace RFC 7230–7235rfc-editor.org
July 2023RFC 9457 Problem Details obsoletes RFC 7807rfc-editor.org
2024-02-06Go 1.22: method and wildcard patterns in net/http.ServeMuxgo.dev
2026IETF HTTPAPI drafts: Idempotency-Key header (-09), RateLimit header fields (-12), still Internet-Draftsdatatracker.ietf.org

Two points matter for the rest of the page. First, the dissertation describes the Web's architecture after the fact; it was never a specification for JSON APIs. Second, almost every rule in today's style guides (Google AIP, Microsoft, Zalando) is a pragmatic subset of RFC 9110 semantics plus conventions for what RFCs leave open (pagination, filtering, errors, long-running work).

The concept catalogue ​

Every block follows the same order: plain words, the usual wrong belief, a definition, a request flow, real scenarios, how products and guides treat it, and the fix.

Fielding's constraints and statelessness Must-know ​

In plain words: REST is what you get when you take a client and a server and keep adding rules: keep them separate, forbid server-side session state, label responses as cacheable or not, make every resource speak the same interface, allow layers in between, and optionally let the server ship code.

Common misunderstanding: "Stateless means the server has no database." Statelessness is about session (application) state between requests, not resource state. Orders, users and carts in a database are resource state and are fine. What is ruled out is "remember what page this connection was on" in server memory, so request 2 only works on the server that saw request 1.

Definition: Fielding: "each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client." The uniform interface is four constraints: "identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state." Code on demand is "the only optional constraint" of the set.

text
     Client                  Load balancer            api-1           api-2
1    GET /orders?cursor=c1   ->                       answers page 2
     Authorization: Bearer t
2    GET /orders?cursor=c2   ->                                       answers page 3
     (cursor and token travel with every request; api-2 never saw request 1)
3    api-1 crashes           ->  no session lost, the client just retries the GET

Real scenario: an autoscaling group adds ten instances during a sale and none needs sticky sessions; a deploy kills pods mid-traffic and clients retry GETs transparently; a CDN serves GET /products/42 from an edge without asking the origin; an API gateway adds auth and rate limiting without the service changing (layered system).

What provides it / breaks it:

PracticeConstraint it supports or breaksProduct example
Bearer token or signed cookie on every requestSupports statelessOAuth 2.0 access tokens, Laravel Sanctum tokens
Server-side session in process memoryBreaks stateless (needs sticky sessions)Default PHP file sessions on one box
Session in Redis keyed by cookieShared state, still not REST-stateless; scalesLaravel SESSION_DRIVER=redis
Cache-Control, ETag on GETSupports cacheableNGINX proxy_cache, Cloudflare, Fastly
POST /api for readsBreaks cacheable and uniform interfaceJSON-RPC, SOAP
CDN, reverse proxy, API gatewayLayered systemCloudflare, AWS CloudFront, Envoy, Kong
JavaScript shipped to the browserCode on demandAny single-page app

Fix / how to use it: carry identity in a token or cookie, carry position in a cursor, keep workflow state in resources (/carts/9, /checkouts/3) instead of server memory; see Scaling Strategies for stateless services and Web Sessions & Cookies for the browser side.

Resources, collections, sub-resources and URI design Must-know ​

In plain words: a resource is anything worth naming: an order, a customer, a collection of orders, "today's exchange rate", even a cancellation. Each gets a URI. Collections are plural nouns; items sit under them; things that only exist inside a parent are sub-resources.

Common misunderstanding: "Every database table is a resource and every resource is a table." Resources are the API's nouns, chosen for clients. /orders/7/cancellation or /payouts/3/approval may not be tables at all, while a join of three tables may be a single resource. Fielding: "Any information that can be named can be a resource."

Definition: a resource is the target of a URI; a collection resource lists and creates members (/orders); an item resource is one member (/orders/ord_01h...); a sub-resource is reachable only through its parent (/orders/{id}/items/{n}); a singleton sub-resource has exactly one instance per parent (/users/{id}/settings). Good URI design uses lowercase plural nouns, no verbs, no file extensions, no trailing slash, stable opaque ids, and at most one or two levels of nesting.

text
     Client                                              Orders API
1    GET  /orders?status=paid                       ->   200 collection page
2    POST /orders            {customer, total}      ->   201 Location: /orders/ord_7
3    GET  /orders/ord_7                             ->   200 item, ETag "ord_7-v1"
4    GET  /orders/ord_7/items                       ->   200 sub-collection
5    POST /orders/ord_7/cancellation                ->   200 the state change is a resource
6    GET  /customers/c_42/orders                    ->   200 the same orders, filtered view

Real scenario: a shop exposing /products, /carts/{id}/lines, /orders/{id}/shipments; a bank exposing /accounts/{id}/transactions with no PUT or DELETE (append-only); an admin action "approve payout" as POST /payouts/{id}/approval; a file API where /files/{id}/content is the binary and /files/{id} is the metadata.

How the guides name things:

RuleGoogle AIP-122Microsoft Azure guidelinesZalando
Collection namesPlural, concise American English ("Collection identifiers must be concise American English terms")Plural nouns"MUST pluralize resource names"
Case in path"Collection identifiers must be in camelCase", e.g. publishers/123/books"DO use kebab-casing (preferred) or camel-casing for URL path segments""MUST use kebab-case for path segments"
Query parameters and JSON fieldssnake_case in proto, camelCase in JSON"DO use camel case for query parameter names" and for JSON fields"MUST use snake_case (never camelCase) for query parameters"
Actions that are not CRUDCustom method with a colon: POST /v1/{name=publishers/*/books/*}:archive (AIP-136).../collection/id:action pattern for actionsModel as sub-resource where possible
NestingResource names encode the parent chainCollection, id and action segments"MUST identify resources and sub-resources via path segments"

Fix / how to use it: name the nouns first (orders, lines, payments, refunds, cancellations); expose opaque public ids (ord_01hx..., ULID or UUID) instead of auto-increment keys; keep nesting to one level and offer flat lookups (/orders/{id} works even if /customers/{c}/orders/{id} exists); in Laravel, Route::apiResource('orders', ...) gives the five collection/item routes and ->shallow() keeps nested routes short; in Go 1.22, mux.HandleFunc("GET /orders/{id}", h) and r.PathValue("id").

Methods and their semantics: safe and idempotent Must-know ​

In plain words: a method tells everyone on the path what kind of action this is. Safe methods only read. Idempotent methods can be repeated with the same effect as once. Caches, browsers, proxies and retry libraries act on these two properties without knowing your API.

Common misunderstanding: "GET must never write anything." RFC 9110 allows a GET to log, count or warm a cache; what makes it safe is that "the client does not request, and does not expect, any state change on the origin server". A GET that charges a card or deletes a row is a bug; a GET that increments a view counter is acceptable but surprising.

Definition: RFC 9110 section 9.2.1: methods are safe "if their defined semantics are essentially read-only"; "the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe." Section 9.2.2: a method is idempotent "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent." RFC 5789: "PATCH is neither safe nor idempotent". POST "requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics."

text
     Client                         API                          Effect
1    PUT /users/7/avatar  (bytes)   -> 201 Created               avatar stored
2    (timeout, retry) PUT again     -> 200 OK                    same avatar, same state
3    DELETE /orders/ord_9           -> 204                       deleted
4    (retry) DELETE /orders/ord_9   -> 410 Gone                  still deleted: idempotent
5    POST /payments {amount: 50}    -> timeout
6    (retry) POST /payments         -> 201                       second payment! not idempotent

Real scenario: a mobile client on a flaky network retries a PUT of profile settings safely; a reverse proxy retries a GET on another upstream after a connection reset (NGINX proxy_next_upstream: "normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server" once sent; Envoy retry policies are configured per route); a browser re-sends a GET after a back button but warns before re-sending a POST form; a payment POST without an idempotency key double-charges after a gateway timeout.

What each method is for:

MethodRequest bodyResponse bodyWho chooses the URIRetry by default inNotes
GETNo meaning (avoid)Representation—Browsers, proxies, Envoy, NGINXCacheable
HEADNoNone, headers as GET—Same as GETGo ServeMux: a GET pattern also matches HEAD
OPTIONSRareCapabilities (Allow)——CORS preflight; see CORS
POSTYesResult or created resourceServerNobody (unsafe)Add Idempotency-Key
PUTFull representationOptionalClientSafe to retryMissing fields mean "remove", not "keep"
PATCHPatch documentUsually the new state—Not by defaultIdempotent if it carries If-Match or only sets values
DELETEShould notUsually none—Safe to retry204 then 404/410

Fix / how to use it: pick the method by semantics, not by habit: client-chosen URI and full replacement is PUT, server-chosen id is POST to the collection, partial change is PATCH, an action is POST to a sub-resource; make POST retry-safe with an Idempotency-Key; make PATCH retry-safe with If-Match; answer a wrong method with 405 and an Allow header (Go's 1.22 mux does it for you).

PATCH formats: JSON Merge Patch vs JSON Patch Important ​

In plain words: PATCH sends a description of changes, and the Content-Type says which language that description is written in. Merge Patch is "here is a partial object, merge it in; null means delete". JSON Patch is "here is a list of operations: test, replace, add, remove, move, copy".

Common misunderstanding: "PATCH with application/json and a partial object is standard." It is a common convention, but the standardized partial-object format is application/merge-patch+json (RFC 7396). With plain application/json there is no agreed meaning for null, arrays or missing fields.

Definition: RFC 5789: "The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI." RFC 7396 merge patch: members present replace values, null removes the member, arrays are replaced whole. RFC 6902 JSON Patch: an array of operations, each with exactly one "op" (add, remove, replace, move, copy, test) and a JSON Pointer "path"; the document is applied atomically, so a failed test aborts everything.

text
     Merge Patch (application/merge-patch+json)      JSON Patch (application/json-patch+json)
1    {"status": "paid", "note": null}                 [{"op":"test","path":"/status","value":"pending"},
2                                                      {"op":"replace","path":"/status","value":"paid"},
3                                                      {"op":"remove","path":"/note"}]
4    note removed, status set                         same result, but only if status was still pending
5    cannot say "append to array" or "only if"        can: test is a per-field precondition

Real scenario: a settings page saving only changed fields (merge patch); a collaborative editor that must change a field only if it still has the old value (JSON Patch test); inserting one element into a large array without resending it (JSON Patch add at /tags/-); Kubernetes accepting both plus its own strategic merge patch for lists.

FormatMedia typeCan delete a fieldArray editsConditional per fieldWho uses it
JSON Merge Patchapplication/merge-patch+jsonYes, with nullReplace whole arrayNoMicrosoft Azure guidelines ("DO create and update resources using PATCH [RFC 5789] with JSON Merge Patch"), Laravel apps by convention
JSON Patchapplication/json-patch+jsonremoveadd, remove, move by indextestKubernetes API ("JSON Patch, as defined in RFC6902")
Strategic merge patchapplication/strategic-merge-patch+jsonDirectivesMerge lists by keyNoKubernetes only
Field maskupdate_mask field (AIP-134)By listing it with no valueReplaceNoGoogle APIs (google.protobuf.FieldMask)
Plain partial JSONapplication/jsonUndefinedUndefinedNoMany APIs, ambiguous

Fix / how to use it: accept application/merge-patch+json by default, add application/json-patch+json when clients need test or array operations, advertise both with Accept-Patch, answer 415 for anything else, and still require If-Match. Laravel parses +json bodies because isJson() checks for /json or +json; sometimes + nullable rules give merge-patch semantics. The Go example implements both formats in applyMerge and applyJSONPatch.

Status codes with precise use Must-know ​

In plain words: the status code is the one part of the response every intermediary understands. Pick the code that tells a generic client what to do next: use the body, follow a link, fix the request, authenticate, wait, or retry.

Common misunderstanding: "400 for every client error is fine, the body explains." A client library, an API gateway, a retry policy and a monitoring dashboard all branch on the code. 409 vs 412 vs 422 vs 429 lead to four different correct reactions (resolve, re-read, fix input, wait).

Definition: RFC 9110 section 15 groups codes into 1xx informational, 2xx successful, 3xx redirection, 4xx client error, 5xx server error, plus RFC 6585 for 428 and 429. Precise meanings used on this page: 202 "the request has been accepted for processing, but the processing has not been completed"; 303 "the server is redirecting the user agent to a different resource ... intended to provide an indirect response to the original request"; 412 "one or more conditions given in the request header fields evaluated to false"; 422 the server "understands the content type of the request content ... and the syntax of the request content is correct, but it was unable to process the contained instructions"; 428 "the origin server requires the request to be conditional"; 429 "the user has sent too many requests in a given amount of time".

text
     Request                                             Code  Client's next move
1    POST /orders  (Content-Type: text/plain)            415   send JSON
2    POST /orders  {"customer": ""}                      422   fix field customer
3    POST /orders  no Idempotency-Key                    400   add the header
4    PATCH /orders/7 no If-Match                         428   GET, then send If-Match
5    PATCH /orders/7 If-Match: "7-v1" (now v2)           412   GET again, reapply, retry
6    PATCH /orders/7 {"status":"pending"} from shipped   409   show the user; do not retry
7    GET /orders (101st request this minute)             429   wait Retry-After seconds
8    GET /orders (database down)                         503   retry with backoff

Real scenario: a mobile client that retries on 5xx but not 4xx; an API gateway (Kong, AWS API Gateway) that turns upstream 502/504 into alerts; a CDN that caches 404 for a short time and 200 for longer; a payment client that must treat 409 "in flight" differently from 422 "key reused".

The full table with precise use:

CodeName (RFC 9110)Precise useHeadersRetry?
200OKSuccess with representationETag—
201CreatedNew resource; body is itLocation, ETag—
202AcceptedQueued; body is the status resourceLocation, Retry-AfterPoll
204No ContentSuccess without bodyETag optional—
206Partial ContentRange request answeredContent-Range—
301Moved PermanentlyURI moved forever; clients may change POST to GETLocationFollow
302FoundTemporary; same method change ambiguityLocationFollow
303See OtherResult lives elsewhere; always GET itLocationFollow with GET
304Not ModifiedConditional GET matchedETag, Cache-ControlUse cache
307Temporary RedirectTemporary, method and body preservedLocationFollow, same method
308Permanent RedirectPermanent, method and body preservedLocationFollow, same method
400Bad RequestSyntax, query parameter, header problems—No, fix
401UnauthorizedMissing or invalid credentialsWWW-AuthenticateAfter auth
403ForbiddenKnown caller, not allowed—No
404Not FoundUnknown, or hidden from this caller—No
405Method Not AllowedPath exists, method does notAllow (required)No
406Not AcceptableCannot produce any type in Accept—No
409ConflictState conflict, duplicate, idempotency key in flight—After resolving
410GoneExisted, deliberately removed—No
412Precondition FailedIf-Match false—After re-read
415Unsupported Media TypeBody format not acceptedAccept or Accept-PatchNo, fix
422Unprocessable ContentSemantic validation failed—No, fix
428Precondition RequiredConditional request demanded—After adding If-Match
429Too Many RequestsRate limitedRetry-After, RateLimitAfter delay
500Internal Server ErrorUnexpected bug—Maybe, idempotent only
502Bad GatewayProxy got a bad upstream answer—Yes, idempotent only
503Service UnavailableOverload, maintenanceRetry-AfterYes, after delay
504Gateway TimeoutProxy's upstream did not answer in time—Idempotent only; the work may have happened

Fix / how to use it: write the table for your API into the OpenAPI contract per operation; never return 200 with an error flag; reserve 5xx for your faults so 5xx rate is an honest SLI (SLOs); for redirects of non-GET requests use 307/308, not 301/302.

Representations and content negotiation Important ​

In plain words: the client never gets "the order", it gets a representation of it: JSON, CSV, a PDF, an older JSON shape. The client says what it can read with Accept; the server says what it sent with Content-Type.

Common misunderstanding: "Content-Type on a GET request matters." On a request, Content-Type describes the request body; a GET has none. What the client wants back is Accept. Mixing them up produces 415 on writes and wrong formats on reads.

Definition: a representation is a snapshot of resource state in a media type (application/json, application/problem+json, text/csv, vendor types such as application/vnd.api+json). Content negotiation (RFC 9110 section 12) is proactive: the server picks using Accept, Accept-Language, Accept-Encoding, and should send Vary listing the headers it used so caches keep variants apart. No acceptable type gives 406; an unreadable request body gives 415.

text
     Client                                            API / CDN
1    GET /orders/7/invoice  Accept: application/pdf    -> 200 Content-Type: application/pdf, Vary: Accept
2    GET /orders/7/invoice  Accept: text/csv           -> 200 Content-Type: text/csv (separate cache entry)
3    GET /orders/7/invoice  Accept: image/png          -> 406 Not Acceptable
4    POST /orders  Content-Type: application/xml       -> 415 Unsupported Media Type, Accept: application/json

Real scenario: an export endpoint offering CSV and JSON Lines; errors as application/problem+json while successes are application/json; a JSON:API server answering application/vnd.api+json (Laravel 13's JsonApiResource "sets the Content-Type header to application/vnd.api+json"); a Zalando-style API versioning by media type.

ProductNegotiation helperDefault
Go net/httpNone built in; parse Accept yourself, mime.ParseMediaType for Content-Typehttp.DetectContentType sniffs if you do not set it
Laravel 13$request->expectsJson(), wantsJson(), accepts(), prefers(); error rendering picks JSON vs HTML "based on the Accept header"JSON for api/* when the client accepts JSON
NGINX / CloudflareCache key must include Accept if you negotiate on itCache key is URL only unless configured
JSON:APIapplication/vnd.api+jsonRequired media type

Fix / how to use it: default to one JSON media type; negotiate only where clients really need several formats; always send Vary: Accept when you do; validate Content-Type on writes (Go: mime.ParseMediaType; Laravel: isJson()), answer 415 with what you accept.

HATEOAS and the Richardson maturity model Important ​

In plain words: HATEOAS ("hypermedia as the engine of application state") means the client discovers what it can do next from links in the response, like a person clicking through a website, instead of building URLs from documentation. The Richardson maturity model is a four-step ladder that shows how far an HTTP API has come toward that.

Common misunderstanding: "Level 3 is the only proper REST, so level 2 APIs are wrong." Fielding does say an API not driven by hypertext "cannot be RESTful and cannot be a REST API. Period." But Fowler is explicit that the model is "a tool to help us learn about the concepts and not something that should be used in some kind of assessment mechanism". Level 2 already gives caching, safe retries and tooling; level 3 pays off when clients are long-lived and many, or when the server wants to change URIs and workflows without client releases.

Definition: the model (Leonard Richardson, written up by Fowler on 18 March 2010): level 0 one endpoint and one method, HTTP as a tunnel ("the swamp of POX"); level 1 separate resources; level 2 HTTP verbs and status codes used as defined; level 3 hypermedia controls. Fielding 2008: "A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types".

text
     Level 0  POST /api {"action":"cancelOrder","id":7}          -> 200 {"ok":false}
     Level 1  POST /orders/7 {"action":"cancel"}                  -> 200
     Level 2  POST /orders/7/cancellation                         -> 200, or 409 if shipped
     Level 3  GET /orders/7 -> {"status":"paid","links":{"cancel":"/orders/7/cancellation"}}
              the client shows a Cancel button only when the link is present
Level 0: the swamp of POXPOST /api {"action":"getOrder","id":7}; always 200Level 1: resourcesPOST /orders/7 {"action":"cancel"}; one URI per thingLevel 2: HTTP verbs and status codesGET /orders/7, PATCH, DELETE; 201, 404, 409, 412Level 3: hypermedia controls"links": {"cancel": "/orders/7/cancellation"}Fielding: required for RESTrare in JSON APIs; JSON:API,HAL, Siren, PayPal linksMost public APIs stop here:caches, retries and toolingalready work at this levelNames, but verbs hide inbodies; caches see littleHTTP as a tunnel: SOAP,JSON-RPC, many internal APIsRichardson maturity model (Fowler, 2010): a learning ladder, not a definition of REST

Why most APIs stop at level 2: clients are written against an OpenAPI document and generated SDKs, not discovered at runtime; JSON has no standard link format (HAL, JSON:API, Siren and RFC 8288 Link headers compete); the cost of adding links is small but the payoff needs clients that actually follow them. The pragmatic middle is "level 2 plus a few links": Link: rel="next" for pages, Location for created resources, and state-dependent action links such as cancel so the UI does not duplicate the server's state machine.

FormatWhere links liveUsed by
RFC 8288 Link headerResponse headerPagination: GitHub's REST API ("You can use the link header from the response to request additional pages"), this page's Go server
HAL (application/hal+json)_links objectAn Internet-Draft format, common in hypermedia-first APIs
JSON:APIlinks and relationshipsLaravel 13 JsonApiResource
Sirenactions with method and fieldsFew, but the richest
Ad hoc links objectBodyThis page's Laravel OrderResource

Fix / how to use it: add self, pagination and state-transition links where clients branch on state; keep URIs stable anyway, because most clients will hard-code them.

Pagination: offset, cursor and keyset Must-know ​

In plain words: never return an unbounded list. Offset pagination says "skip 400, give me 20"; cursor pagination says "give me 20 after this bookmark". The bookmark is usually built from the sort key (keyset), so the database jumps straight to it.

Common misunderstanding: "Cursor pagination is just a different spelling of page numbers." Offset pages shift when rows are inserted or deleted (you see duplicates or miss rows), and OFFSET 100000 makes the database read and discard 100,000 rows. A keyset cursor is stable under concurrent writes and costs the same on page 1 and page 10,000. What you lose is "jump to page 37" and, usually, an exact total count.

Definition: offset pagination: ?page=3&per_page=20 or ?offset=40&limit=20, SQL LIMIT 20 OFFSET 40. Keyset pagination: WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 21, where the unique id makes the order total. Cursor pagination: the API wraps the keyset values (plus filters) in an opaque cursor string, returned as next_cursor and/or a Link: rel="next" header. Laravel's docs say it directly: "cursor pagination works by constructing "where" clauses that compare the values of the ordered columns". Deep SQL and index design: Pagination: Offset vs Keyset.

text
     Offset under concurrent insert                    Keyset under the same insert
1    GET ?page=1 -> ids 20..11                          GET ?limit=10 -> ids 20..11, cursor(11)
2    new order 21 inserted                              new order 21 inserted
3    GET ?page=2 -> ids 11..2   (11 shown twice)        GET ?cursor(11) -> ids 10..1 (no duplicate)
4    a delete of id 15 instead would skip id 10         a delete changes nothing for later pages

Real scenario: an infinite-scroll feed; a sync job pulling every order changed since yesterday; an admin table that needs page numbers and a total (offset is fine there, under a few thousand rows); an export of 50 million rows (keyset or a long-running export, never offset).

Product or guideStyleField names
Google AIP-158Opaque tokenpage_size, page_token, next_page_token; "The page_token field must not be required"
Microsoft AzureOpaque linkvalue array plus nextLink absolute URL; "DO NOT return the nextLink field at all when returning the last page"
ZalandoCursor preferred"SHOULD prefer cursor-based pagination, avoid offset-based pagination"
Laravel 13paginate() offset with total, simplePaginate() offset without total, cursorPaginate() keysetcursor query string, next_cursor in JSON
This page's Go serverKeyset cursor (base64url JSON of last id and filter)limit, cursor, next_cursor, Link: rel="next"

Fix / how to use it: default limit 20–50, cap at 100; return a cursor, not a page number, for anything that grows; include filters in the cursor or reject a cursor reused with different filters (the Go server answers 400 "invalid-cursor"); index (filter columns, sort column, id); if clients need totals, return an estimate or a separate /orders/count.

sql
-- Keyset page for GET /orders?status=paid&limit=20, newest first.
-- Index: (customer_id, status, created_at, id) as in the Laravel migration.
SELECT public_id, status, total_cents, created_at, id
FROM orders
WHERE customer_id = $1
  AND status = 'paid'
  AND (created_at, id) < ($2, $3)        -- values decoded from the cursor
ORDER BY created_at DESC, id DESC
LIMIT 21;                                -- one extra row tells you if there is a next page

Filtering, sorting and sparse fieldsets Important ​

In plain words: let clients narrow a collection (?status=paid), order it (?sort=-created_at) and ask for fewer fields (?fields=id,status), but only through an allow-list you can index and support forever.

Common misunderstanding: "Pass the sort and filter straight into the query builder, it is flexible." It is also SQL injection by column name, unindexed full scans and a contract you can never change. Every filter and sort you accept is a promise and an index.

Definition: filtering: query parameters per field (status=paid, created_after=...) or a small expression language (Google AIP-160 filter string, OData $filter). Sorting: a field list with direction (sort=-created_at,id; AIP-132 order_by, where "users append a " desc" suffix; for example: "foo desc, bar""). Sparse fieldsets: the client chooses returned fields (fields=id,status; JSON:API fields[orders]=...; Google field masks; Zalando "SHOULD support partial responses via filtering").

text
     Client                                                    API
1    GET /orders?status=paid&sort=-created_at&fields=id,total_cents&limit=50
2                                                              validate: status in enum, sort in allow-list,
3                                                              fields subset of schema, limit <= 100
4                                                              SELECT ... WHERE status='paid' ORDER BY created_at DESC, id DESC
5    <- 200 {"data":[{"id":"ord_9","total_cents":4999}, ...], "next_cursor":"..."}
6    GET /orders?sort=password_hash                            -> 400 invalid-parameter

Real scenario: a mobile list screen that needs only id, title, thumbnail_url (sparse fieldsets cut payloads); a back-office search with ten filters (consider a search system instead of SQL); a partner integration syncing updated_after=... (needs an index on updated_at, id).

FeatureGoogle AIPMicrosoft AzureJSON:API / Laravel
FilterAIP-160 filter string with a defined grammarfilter query optionfilter[status]=paid (Spatie Laravel Query Builder is suggested by the Laravel docs)
SortAIP-132 order_byorderbysort=-created_at
Sparse fieldsField masks / read_maskselectfields[orders]=id,status; Laravel JsonApiResource handles sparse fieldsets
Combined with paginationToken must encode filtersnextLink includes them ("DO include any query parameters required by the service")withQueryString() on the paginator

Fix / how to use it: validate against allow-lists (Laravel Rule::in, Go map[string]bool), map public names to columns explicitly, add an index per supported combination, and put filters into the cursor so next links stay consistent.

Errors: Problem Details (RFC 9457) Must-know ​

In plain words: every error body has the same small shape: a type URI clients can switch on, a human title, the status, an optional detail and the instance it happened on, plus any extra fields you document.

Common misunderstanding: "Problem Details replaces status codes." The code still carries the class of failure; the body adds the specific reason. And title is for humans and may be translated, so clients branch on type, never on text.

Definition: RFC 9457 (July 2023, "This document obsoletes RFC 7807") defines "a "problem detail" to carry machine-readable details of errors in HTTP response content", serialized as application/problem+json, with members type, status, title, detail, instance, and extension members such as errors for field-level validation.

text
     Client                                     API
1    POST /orders {"customer":"","total_cents":0}
2                                               422 Content-Type: application/problem+json
3                                               {"type":"https://api.example.com/problems/validation",
4                                                "title":"Validation failed","status":422,"instance":"/orders",
5                                                "errors":[{"pointer":"#/customer","detail":"is required"}, ...]}
6    client maps pointer #/customer to the form field and shows "is required"

Real scenario: a mobile app showing per-field validation; a partner SDK raising OutOfCreditError because type ends in out-of-credit; support staff searching logs by instance; an API gateway (Kong, Envoy) emitting its own 429 in the same format so clients have one parser.

Product or guideError format
RFC 9457application/problem+json, type/title/status/detail/instance
Zalando"MUST support problem JSON"
Microsoft AzureOwn envelope: {"error": {"code", "message", "target", "details", "innererror"} } plus x-ms-error-code header ("values are part of your API contract")
Google AIP-193google.rpc.Status with code, message, details
Laravel 13 default{"message": ..., "errors": {...} } with 422; no Problem Details built in, so this page renders it in bootstrap/app.php
Go net/httphttp.Error writes text/plain; write your own helper (writeProblem here)

Fix / how to use it: one helper in each stack; type URIs that resolve to documentation; never put stack traces or SQL in detail for 5xx; set Cache-Control: no-store on errors; keep the same shape at the gateway.

Idempotency keys for POST Must-know ​

In plain words: the client invents a unique key for one logical operation ("pay invoice 9, attempt group A") and sends it on every retry. The server remembers the key with the result, so the second, third and tenth try return the first result instead of doing the work again.

Common misunderstanding: "A unique constraint on the order table is enough." It stops a duplicate row, but the retry gets a 409 or 500 instead of the original 201, the client cannot tell success from failure, and side effects outside that table (the card charge, the email) still run twice. The key must cover the whole operation and its response.

Definition: the IETF draft (draft-ietf-httpapi-idempotency-key-header-09): "An idempotency key is a unique value generated by the client which the resource uses to recognize subsequent retries of the same request." The value is a structured-field String (Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"); "It is RECOMMENDED that a UUID [RFC9562] or a similar random identifier be used". The contract: missing key on an operation that requires it gives 400; a key reused "with a different request payload" gives 422; a retry "while the original request is still being processed" gives 409; a retry after completion gets "a response consistent with the request being completed". Servers detect payload reuse with an idempotency fingerprint and "SHOULD define such expiration policy and publish it". Stripe's API documents the same shape: keys "up to 255 characters long", pruned "after they're at least 24 hours old".

text
     Client                               API                                 Store
1    POST /payments  Idempotency-Key: "k1"   claim k1 (INSERT ... PK)          k1 = in flight
2                                         charge card, 201 {id: pay_5}       k1 = 201 + body
3    (response lost, client times out)
4    POST /payments  Idempotency-Key: "k1"   k1 exists, same fingerprint        -> replay 201 {id: pay_5}
5    POST /payments  "k1", amount changed   fingerprint differs               -> 422
6    two retries race while 2 is running    second sees in flight             -> 409, Retry-After: 1
POST + Idempotency-KeyKey present and valid?Key seen for this client?400 Bad RequestNew: insert row (in flight),run handler, save response422: fingerprint differs409 + Retry-After: in flightCompleted: replay savedstatus, headers, bodyHandler failed (4xx/5xx):delete row, retry allowednoyesnoyesdraft-ietf-httpapi-idempotency-key-header-09

Real scenario: card payments and payouts; order submission from a mobile app that retries on reconnect; webhook senders that redeliver; an internal service calling another with a retry policy (Service Communication).

ProductHow POST is made retry-safe
IETF draftIdempotency-Key request header; 400 / 409 / 422 contract
StripeIdempotency-Key; saves "the status code and body of the first request" (API v1) and replays them, "including 500 errors"
Google AIP-155request_id field (UUID4) on the request message; "This request is only idempotent if a request_id is provided"
Microsoft AzureRepeatability-Request-ID and Repeatability-First-Sent headers; guidelines say "all HTTP methods are idempotent", POST included
Zalando"MAY consider to support Idempotency-Key header", or a secondary key in the payload
Laravel 13No built-in middleware; this page's RequireIdempotencyKey uses a table whose primary key is the lock
GoNo built-in; this page's IdempotencyStore.Middleware

Fix / how to use it: require the key on every non-idempotent POST that has side effects; scope keys per client; fingerprint method, path and body; store the response, not just "seen"; do not pin 4xx/5xx results to the key (this page deletes the row so a corrected request can reuse it; Stripe v1 chooses the opposite and replays 500s, so document your choice). Storage engines, TTL sweeps, crash between charge and save, and multi-region keys are in API Idempotency.

Concurrency control: ETag, If-Match and optimistic locking Must-know ​

In plain words: when you read a resource, the server gives you its version tag. When you write, you send the tag back: "only apply this if it is still the version I saw". If someone changed it in between, you get 412 and must re-read, instead of silently overwriting their work.

Common misunderstanding: "Our database transaction protects us." A transaction protects one request. The lost update here spans two requests minutes apart: Alice reads, Bob reads, Alice writes, Bob writes the old state back. Only a precondition that travels with the request (or a version in the body) catches it.

Definition: an ETag is an opaque validator for a representation; strong ETags must match byte for byte, weak ones (W/"...") mean semantically equivalent. If-Match makes a write conditional on a strong match; failure gives 412. If-None-Match on GET returns 304 when the tag still matches; If-None-Match: * on PUT means "create only if absent". RFC 6585 adds 428 for servers that require conditional writes, "to avoid the "lost update" problem". On the server this is optimistic concurrency: UPDATE ... SET version = version + 1 WHERE id = ? AND version = ? and check the affected-row count; mechanics in Optimistic vs Pessimistic Locking.

text
     Alice                              API + DB                               Bob
1    GET /orders/7 -> ETag "7-v1"                                              GET /orders/7 -> ETag "7-v1"
2    PATCH If-Match "7-v1" {status:paid}  UPDATE ... WHERE version=1 (1 row)
3    <- 200 ETag "7-v2"
4                                         UPDATE ... WHERE version=1 (0 rows)  <- PATCH If-Match "7-v1" {note:x}
5                                         412 Precondition Failed              -> Bob re-reads v2, reapplies, PATCH "7-v2"
6                                         200 ETag "7-v3"
AliceOrders API + DBBobGET /orders/7200, ETag: "7-v1"GET /orders/7200, ETag: "7-v1"PATCH, If-Match: "7-v1"WHERE version = 1: 1 row200, ETag: "7-v2"PATCH, If-Match: "7-v1"WHERE version = 1: 0 rows412 Precondition FailedGET again, reapply, PATCH If-Match "7-v2"200, ETag: "7-v3"No If-Match at all: 428 Precondition Required (RFC 6585)

Real scenario: two support agents editing the same ticket; a mobile app syncing an offline edit made yesterday; an inventory admin and an import job changing the same product; a configuration tool (Kubernetes uses resourceVersion the same way: when the version "provided is stale), the API server returns a 409 Conflict").

Product or guideValidatorPreconditionFailure
RFC 9110ETagIf-Match, If-Unmodified-Since412
Google AIP-154etag field in the resource bodySent back in the update requestABORTED (HTTP 409)
Microsoft AzureETag header"DO support caching and optimistic concurrency by honoring the If-Match, If-None-Match"412
Kubernetesmetadata.resourceVersionBody field409 Conflict
Laravel 13$response->setEtag() (Symfony)Read If-Match yourself; compare-and-set with where('version', ...)->increment('version', 1, $changes)Throw PreconditionFailedHttpException
Go net/httpSet ETag header yourselfhttp.ServeContent handles If-Match for files; for APIs write precondition()412

Fix / how to use it: derive the ETag from a version column, not from hashing JSON on every request; require If-Match on PATCH/PUT/DELETE of shared resources (428 when absent); return the new ETag on every successful write; explain in the 412 body what to do.

Caching headers Important ​

In plain words: tell every cache on the path (browser, CDN, reverse proxy) whether it may keep a response, for how long, and how to check it is still fresh cheaply.

Common misunderstanding: "no-cache means do not cache." In RFC 9111 no-cache means "store it, but revalidate before every reuse"; the directive that forbids storing is no-store. Per-user API responses want private, no-cache plus an ETag; error responses and secrets want no-store.

Definition: Cache-Control directives (RFC 9111): max-age, s-maxage (shared caches only), public, private, no-cache, no-store, must-revalidate, stale-while-revalidate. Validators: ETag with If-None-Match, Last-Modified with If-Modified-Since. Vary names request headers that select the variant (Accept, Accept-Language; Authorization responses are not stored by shared caches unless explicitly allowed).

text
     Browser                         CDN (Cloudflare)               API
1    GET /products/42                miss                           200 Cache-Control: public, max-age=60, s-maxage=300; ETag "p42-v8"
2    GET /products/42 (30 s later)   browser cache hit, no request
3    GET /products/42 (2 min later)  CDN hit (s-maxage 300)
4    GET /products/42 (6 min later)  If-None-Match "p42-v8"   ->    304, 0 bytes of body

Real scenario: a public catalogue at 50,000 requests per second served almost entirely from a CDN; GET /me responses that must never be cached by a shared cache; a mobile app saving bandwidth with 304s; an outage page served stale-while-revalidate.

ProductKnob
Laravel 13cache.headers middleware: cache.headers:public;max_age=30;s_maxage=300;stale_while_revalidate=600;etag
Go net/httpSet Cache-Control/ETag headers; http.ServeContent answers conditional requests for byte content
NGINXproxy_cache, proxy_cache_valid, proxy_cache_use_stale
Cloudflare / Fastly / CloudFrontRespect origin Cache-Control/s-maxage, plus their own cache rules

Fix / how to use it: public read models get public, max-age, s-maxage; per-user reads get private, no-cache and an ETag; writes and errors get no-store; deeper cache design is in Caching and CDNs.

Rate-limit headers and Retry-After Important ​

In plain words: tell clients their quota and what is left before they hit it, and when they do hit it, answer 429 with how long to wait.

Common misunderstanding: "X-RateLimit-* is the standard." It is a widespread convention (GitHub, Laravel's throttle middleware) with no single meaning. The IETF HTTPAPI working group's draft defines RateLimit-Policy and RateLimit as structured fields; the syntax changed between drafts, so pin the draft version you implement.

Definition: RFC 6585 429 "MAY include a Retry-After header indicating how long to wait before making a new request". draft-ietf-httpapi-ratelimit-headers-12: RateLimit-Policy: burst;q=100;w=60,"daily";q=1000;w=86400 lists quota policies (q quota, w window seconds, qu unit, pk partition key); RateLimit: default;a=50;w=30 gives the available quota a and the effective window w. "If a response contains both the RateLimit and Retry-After fields, the Retry-After field MUST take precedence".

text
     Client app-1                                 API (limit 100/min)
1    GET /orders                                  200 RateLimit-Policy: default;q=100;w=60
2                                                     RateLimit: default;a=99;w=60
3    ... 99 more requests in 20 s ...
4    GET /orders                                  429 Retry-After: 40, RateLimit: default;a=0;w=40
5    client sleeps 40 s (plus jitter), resumes

Real scenario: a public API with free and paid tiers; a partner integration that paces bulk syncs by reading a instead of failing; Laravel answering 429 automatically when a limiter is exceeded; NGINX limit_req at the edge, whose default is limit_req_status 503; (set it to 429).

ProductHeaders emitted
Laravel 13 ThrottleRequestsX-RateLimit-Limit, X-RateLimit-Remaining; on 429 also Retry-After and X-RateLimit-Reset (framework source)
GitHub REST APIx-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset (convention, not this page's source)
IETF draft -12RateLimit-Policy, RateLimit (and RateLimit-Partition)
Zalando"MUST use code 429 with headers for rate limits"
This page's Go serverDraft -12 fields plus Retry-After

Fix / how to use it: limit per authenticated client, not per IP when you can; send the fields on every response; 429 for quotas, 503 for overload (Load Shedding); algorithms (token bucket, sliding window, distributed counters) are in Rate Limiting.

Bulk and batch endpoints Good to know ​

In plain words: when clients must create or change hundreds of things, one request with many items beats hundreds of requests, but you must decide what happens when item 37 fails.

Common misunderstanding: "Return 200 and a list of results, done." Then a client that ignores the body thinks everything worked. Either make the batch atomic (all or nothing, a normal status code) or make partial success explicit (207-style per-item results or a long-running operation with a report).

Definition: a bulk endpoint accepts a collection of items in one request: POST /orders:batchCreate (Google AIP-233 custom method: "Some APIs need to allow users to create multiple resources in a single transaction"; AIP-233 discusses atomic vs partial success and restricts synchronous batch methods to atomic), or POST /orders/bulk. Sizes are capped; each item can carry its own idempotency key.

text
     Client                                    API
1    POST /orders:batchCreate {requests:[500 items]}  Idempotency-Key: "b1"
2                                              validate all first; any invalid -> 422 listing pointers #/requests/37/total_cents
3                                              all valid -> one transaction -> 200 {orders:[...]}
4    too big for one transaction -> 202 + /operations/op_9, report lists per-item status

Real scenario: importing a CSV of products; a POS terminal uploading a day of offline sales; bulk-tagging 10,000 emails; marking notifications read.

ChoiceStatusWhen
Atomic synchronous batch200/201 or one 4xxSmall batches, one database
Partial success with per-item results200 with per-item status (or WebDAV 207)Independent items, client can retry the failed ones
Asynchronous batch202 + status resourceLarge or slow batches

Fix / how to use it: cap items (100–1,000), validate everything before writing anything, make the batch idempotent, and never hide failures behind a bare 200.

Long-running operations Important ​

In plain words: if the work takes longer than a request should (exports, video transcodes, provisioning), accept it, answer at once with 202 and a URI where the client can watch it, and when it finishes, point to the result.

Common misunderstanding: "202 means it worked." RFC 9110: the request "might or might not eventually be acted upon"; "The 202 response is intentionally noncommittal." The status resource is the only place the outcome appears.

Definition: POST /exports → 202 Accepted, Location: /operations/op_1, Retry-After: 1, body is the operation {id, status: running}. GET /operations/op_1 → 200 while running; once done, either 200 with status: succeeded and a result link, or 303 See Other with Location of the result. Google AIP-151 returns a google.longrunning.Operation with a done field; Microsoft Azure returns 202 with an operation-location header to a status monitor.

text
     Client                              API                         Worker
1    POST /exports?format=csv            -> 202 Location: /operations/op_1, Retry-After: 1
2                                        enqueue job op_1           picks op_1
3    GET /operations/op_1                -> 200 {status: running}, Retry-After: 1
4                                                                    writes file, marks succeeded
5    GET /operations/op_1                -> 303 See Other, Location: /exports/exp_1
6    GET /exports/exp_1                  -> 200 text/csv (or a presigned object-storage URL)

Real scenario: a monthly statement export; an ML batch prediction job; creating a database cluster in a cloud console; a bulk import with a per-row report.

Product or guideStartPollDone
Google AIP-151Method returns OperationGET /v1/{name=operations/*}done: true with response or error
Microsoft Azure202 + operation-locationStatus monitor resourcestatus: Succeeded/Failed
This page (Go and Laravel)202 + Location + Retry-AfterGET /operations/{id}303 to the result
Push alternativesWebhook or SSE/WebSocket—Callback

Fix / how to use it: make the start idempotent (Idempotency-Key), persist operations so a restart does not lose them, give results an expiry, and offer a webhook for clients that should not poll; job execution in Laravel is a queued job (Durable Workflows & Jobs).

Versioning summary Important ​

In plain words: design so that most changes are additive and need no version; when you must break, give the new contract a version and run both for a while.

Common misunderstanding: "Put /v1/ in every URL from day one and bump it for every change." A version bump is a migration for every client. Adding an optional field, a new endpoint or a new enum value (if clients were told to tolerate unknown values) is not breaking.

Definition: the main strategies are URI path (/v1/orders, Google APIs), query parameter (?api-version=2021-06-04, Microsoft Azure, which returns 400 "MissingApiVersionParameter" when it is absent), header (a custom version header such as Api-Version: 2026-11-01), and media type (Accept: application/vnd.example.order+json;version=2; Zalando "MUST use media type versioning" and "MUST not use URL versioning"). Breaking-change rules, deprecation headers, sunset policies and the expand/contract migration are in API Versioning & Evolution.

text
     Change                                    Breaking?   Action
1    add optional response field "eta"         No          ship; clients ignore unknown fields
2    add optional request field                No          ship with a default
3    rename "total" to "total_cents"           Yes         add new field, deprecate old, remove in v2
4    make "note" required                      Yes         new version or keep optional
5    change 200 to 202 for POST /orders        Yes         new version
StrategyExampleCache-friendlyUsed by
URI path/v1/ordersYesGoogle APIs (AIP examples use /v1/...), many public APIs
Query parameter?api-version=2021-06-04YesMicrosoft Azure
Custom headerApi-Version: 2026-11-01Needs VaryDate-pinned APIs
Media typeapplication/vnd.example+json;v=2Needs Vary: AcceptZalando

OpenAPI 3.1, contract-first and codegen Must-know ​

In plain words: write the API down as a machine-readable contract before (or while) you write the code, review it like code, and generate docs, client SDKs, server stubs, mocks and tests from it.

Common misunderstanding: "We generate the OpenAPI file from annotations, so we have a contract." Code-first output describes whatever the code happens to do, including accidental breaking changes. Contract-first means the contract is reviewed, versioned and diffed in CI, and the implementation is tested against it.

Definition: the OpenAPI Specification "defines a standard, programming language-agnostic interface description for HTTP APIs". In 3.1.0 (15 February 2021) "The Schema Object ... is a superset of JSON Schema Specification Draft 2020-12", so type: [string, 'null'] replaces 3.0's nullable: true, and webhooks are first-class. Contract-first (Zalando: "MUST follow API first principle") writes the document first; codegen turns it into clients and server interfaces (OpenAPI Generator, oapi-codegen for Go, Kiota); linting (Spectral) enforces the style guide; breaking-change diff (oasdiff) gates CI.

text
     Step                                        Tool (examples)
1    write orders.yaml, open a pull request      editor, Spectral lint with your style rules
2    review resources, codes, headers            humans
3    CI: diff against main                       oasdiff -> fail on breaking change
4    generate Go server interface + TS client    oapi-codegen, OpenAPI Generator
5    mock for frontend work                      Prism
6    contract tests: real server vs document     schemathesis or Pact-style tests

The contract for this page's service (both implementations follow it):

yaml
openapi: 3.1.0
info:
  title: Orders API
  version: 1.4.0
  description: Contract-first definition of the orders resource used on this page.
servers:
  - url: https://api.example.com
paths:
  /orders:
    get:
      operationId: listOrders
      parameters:
        - { name: status, in: query, schema: { $ref: '#/components/schemas/Status' } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - { name: cursor, in: query, description: 'Opaque; copy it from next_cursor or the Link header.', schema: { type: string } }
        - { name: fields, in: query, description: 'Sparse fieldset, e.g. id,status', schema: { type: string } }
      responses:
        '200':
          description: One page of orders.
          headers:
            Link: { description: 'rel="next" when another page exists', schema: { type: string } }
            RateLimit: { schema: { type: string } }
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data: { type: array, items: { $ref: '#/components/schemas/Order' } }
                  next_cursor: { type: string }
        '400': { $ref: '#/components/responses/Problem' }
        '429': { $ref: '#/components/responses/TooManyRequests' }
    post:
      operationId: createOrder
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/NewOrder' }
      responses:
        '201':
          description: Created.
          headers:
            Location: { required: true, schema: { type: string, format: uri-reference } }
            ETag: { required: true, schema: { type: string } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '400': { $ref: '#/components/responses/Problem' }
        '409': { $ref: '#/components/responses/Problem' }
        '415': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
  /orders/{id}:
    parameters:
      - { name: id, in: path, required: true, schema: { type: string, pattern: '^ord_[0-9a-z]+$' } }
    get:
      operationId: getOrder
      parameters:
        - { name: If-None-Match, in: header, schema: { type: string } }
      responses:
        '200':
          description: The order.
          headers:
            ETag: { required: true, schema: { type: string } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '304': { description: Not modified; reuse your cached copy. }
        '404': { $ref: '#/components/responses/Problem' }
        '410': { $ref: '#/components/responses/Problem' }
    patch:
      operationId: updateOrder
      parameters:
        - { name: If-Match, in: header, required: true, schema: { type: string } }
      requestBody:
        required: true
        content:
          application/merge-patch+json:
            schema: { $ref: '#/components/schemas/OrderPatch' }
          application/json-patch+json:
            schema:
              type: array
              items:
                type: object
                required: [op, path]
                properties:
                  op: { enum: [add, remove, replace, test] }
                  path: { type: string }
                  value: {}
      responses:
        '200':
          description: Updated; new ETag.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '409': { $ref: '#/components/responses/Problem' }
        '412': { $ref: '#/components/responses/Problem' }
        '415': { $ref: '#/components/responses/Problem' }
        '422': { $ref: '#/components/responses/Problem' }
        '428': { $ref: '#/components/responses/Problem' }
    delete:
      operationId: deleteOrder
      responses:
        '204': { description: Deleted. }
        '404': { $ref: '#/components/responses/Problem' }
        '410': { $ref: '#/components/responses/Problem' }
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Structured-field string, e.g. "8e03978e-40d5-43e8-bc93-6894a57f9324". Kept 24 h.
      schema: { type: string, maxLength: 257 }
  schemas:
    Status: { type: string, enum: [pending, paid, shipped, cancelled] }
    NewOrder:
      type: object
      additionalProperties: false
      required: [customer, total_cents]
      properties:
        customer: { type: string, minLength: 1 }
        total_cents: { type: integer, minimum: 1 }
        note: { type: [string, 'null'], maxLength: 500 }
    OrderPatch:
      type: object
      additionalProperties: false
      properties:
        customer: { type: string, minLength: 1 }
        status: { $ref: '#/components/schemas/Status' }
        note: { type: [string, 'null'], description: 'null removes the note (RFC 7396)' }
    Order:
      type: object
      required: [id, customer, status, total_cents, version, created_at]
      properties:
        id: { type: string, readOnly: true }
        customer: { type: string }
        status: { $ref: '#/components/schemas/Status' }
        total_cents: { type: integer }
        note: { type: [string, 'null'] }
        version: { type: integer, readOnly: true }
        created_at: { type: string, format: date-time, readOnly: true }
    Problem:
      type: object
      properties:
        type: { type: string, format: uri-reference }
        title: { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string, format: uri-reference }
        errors:
          type: array
          items:
            type: object
            properties:
              pointer: { type: string }
              detail: { type: string }
  responses:
    Problem:
      description: RFC 9457 Problem Details.
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
    TooManyRequests:
      description: Rate limited.
      headers:
        Retry-After: { schema: { type: integer } }
      content:
        application/problem+json:
          schema: { $ref: '#/components/schemas/Problem' }
ToolRole
OpenAPI 3.1The contract format
JSON Schema 2020-12Body schemas inside it
SpectralLinting against a style guide
oapi-codegen (Go), OpenAPI Generator, KiotaServer stubs and SDKs
PrismMock server
Laravel: Scribe, dedoc/scramble (third-party)Generate docs from Laravel code (code-first)

Security basics Important ​

In plain words: authenticate every request (stateless constraint), authorise every object (not just every route), never trust ids from the client, and leak nothing in errors.

Common misunderstanding: "The route has auth middleware, so the endpoint is secure." That checks who the caller is, not whether order 7 is theirs. Broken object-level authorization (changing the id in the URL to read someone else's data) is "API1:2023 Broken Object Level Authorization", the first item of the OWASP API Security Top 10.

Definition: 401 means no or invalid credentials and requires WWW-Authenticate; 403 means "I know you, and no"; 404 may be used instead of 403 to avoid revealing that a resource exists (Laravel Response::denyAsNotFound()). Tokens: OAuth 2.0 bearer tokens with scopes (OAuth 2.0 & OIDC, JWT), Laravel Sanctum personal tokens with abilities (tokenCan). Transport: TLS everywhere (Cryptography & TLS). Browser clients: CORS and CSRF (Sessions, Cookies & CORS).

text
     Request                                         Check                     Answer
1    GET /orders/ord_7  (no token)                   authentication            401 WWW-Authenticate: Bearer
2    GET /orders/ord_7  (token of user 42, owns it)  policy view: allow        200
3    GET /orders/ord_8  (token of user 42, not his)  policy view: deny         404 (not 403, hide existence)
4    PATCH /orders/ord_7 (token without orders:write) policy update: deny      404 or 403 by policy
ConcernGoLaravel 13
AuthenticationMiddleware verifying a JWT or sessionauth:sanctum middleware
Object authorizationCheck owner in the handler or a policy funcPolicies + Gate::authorize('view', $order); Form Request authorize() returns 403
Mass assignmentDecode into a request struct, DisallowUnknownFields$fillable, $request->validated()
Input sizehttp.MaxBytesReaderpost_max_size, validation max:
ErrorsProblem Details without internalsrender() callback, APP_DEBUG=false

Deeper material: OWASP Top 10, Authorization Models, Authentication.

Naming conventions and API style guides Good to know ​

In plain words: pick one published API style guide, adopt it with a short list of exceptions, and lint against it, so 40 teams produce one API instead of 40.

Common misunderstanding: "Style guides are bikeshedding." They decide pagination, errors, long-running work, versioning and idempotency, which are expensive to change later; casing is the smallest part.

Definition: an API style guide is a set of normative rules (MUST/SHOULD) for an organisation's APIs. The three most cited: Google AIP (API Improvement Proposals, google.aip.dev: resource-oriented design AIP-121, resource names AIP-122, standard methods AIP-131 to 135, custom methods AIP-136, LRO AIP-151, etags AIP-154, request ids AIP-155, pagination AIP-158, filtering AIP-160, batch AIP-231 to 235); Microsoft REST API Guidelines (github.com/microsoft/api-guidelines, with the Azure-specific guidelines); Zalando RESTful API Guidelines (opensource.zalando.com).

text
     Team writes orders.yaml -> Spectral ruleset "company-api-style" -> CI comment:
1    error  path segment "/orderItems" must be kebab-case            (Zalando rule)
2    error  operation createOrder has no 4xx Problem response         (house rule)
3    warn   list operation without cursor parameter                   (house rule)
TopicGoogle AIPMicrosoft AzureZalando
Paginationpage_token / next_page_tokennextLinkCursor preferred
Errorsgoogle.rpc.Statuserror envelope + x-ms-error-codeProblem JSON
PATCHUpdate with update_maskJSON Merge PatchJSON Merge Patch or JSON Patch
Idempotencyrequest_idRepeatability headersIdempotency-Key (MAY)
VersioningMajor version in pathapi-version query parameterMedia type
Long-runninggoogle.longrunning.Operation202 + operation-location202 + status resource
CasingcamelCase JSONcamelCasesnake_case JSON, kebab-case paths

Mechanics ​

HTTP grammar you must get exactly right ​

ThingExact formNote
Strong ETagETag: "ord_000001-v2"Quotes are part of the value
Weak ETagETag: W/"ord_000001-v2"Never matches If-Match (strong comparison)
If-Match listIf-Match: "a", "b" or ** means "any current representation"
Idempotency-KeyIdempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"Structured-field String: quoted
Link next pageLink: </orders?cursor=eyJh...&limit=2>; rel="next"RFC 8288; URI in angle brackets
Retry-AfterRetry-After: 40 or an HTTP-dateSeconds preferred (no clock skew)
RateLimit-PolicyRateLimit-Policy: default;q=100;w=60Draft -12 syntax
RateLimitRateLimit: default;a=99;w=60a = available, w = window seconds
Accept-PatchAccept-Patch: application/merge-patch+json, application/json-patch+jsonSend on 415 for PATCH and on OPTIONS
AllowAllow: DELETE, GET, HEAD, PATCHRequired with 405

Knobs in each stack ​

KnobValue used hereWhy
Go http.Server.ReadHeaderTimeout5 sSlow-header (Slowloris) protection; the zero value means no limit
Go http.MaxBytesReader1 MiBBody cap per request
Go json.Decoder.DisallowUnknownFieldson for createUnknown members become 400 instead of silently ignored
Page limitdefault 20, max 100Bounded responses
Idempotency key TTL24 hPublished in the contract, matches Stripe's v1 minimum
Laravel Limit::perMinute(120)->by('user:'.$id)120/min per user, 20/min per IPFair per-client quotas
Laravel cursorPaginate(25)25Requires an orderBy on the paginated table's columns
Laravel cache.headersprivate;etag for user dataWith etag it hashes the body (xxh128) when no ETag is set and calls isNotModified()

Error messages you will actually see ​

WhereMessageMeaning
Go ServeMux, wrong method405 Method Not Allowed body Method Not Allowed with AllowPattern exists for other methods
Go ServeMux, at registrationpanic: pattern "GET /orders/{name}" (registered at main.go:8) conflicts with pattern "GET /orders/{id}" (registered at main.go:7): GET /orders/{name} matches the same requests as GET /orders/{id}Two patterns match the same requests and neither is more specific (reproduced with Go 1.27)
Go json.Decoderjson: unknown field "admin"DisallowUnknownFields rejected a member
Go http.MaxBytesReaderhttp: request body too largeBody exceeded the cap
Laravel validationThe total cents field must be at least 1. (422)Form Request rule failed
Laravel, throttle429 Too Many Attempts.ThrottleRequestsException thrown by ThrottleRequests
Laravel, policy denied403 This action is unauthorized.AuthorizationException converted to 403
Laravel, missing model404 No query results for model [App\Models\Order] ...Route model binding found nothing (replace with Problem Details)
AzureMissingApiVersionParameter (400)No api-version query parameter

Go ​

The module academy/rest-api-design (go 1.24 directive, standard library only) has the bad first version, the service package and a runnable server.

Before ​

An RPC tunnel: one URI, actions in the body, 200 for errors, offset paging over a map, last write wins, and a retried createOrder creates a second order.

go
// Command before is the RPC-over-HTTP shape many first APIs take.
// It works, but every request is POST /api, every answer is 200,
// errors hide in the body, nothing is cacheable and a retried
// "createOrder" creates a second order.
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	"sync"
)

type order struct {
	ID       int    `json:"id"`
	Customer string `json:"customer"`
	Status   string `json:"status"`
}

var (
	mu     sync.Mutex
	nextID = 1
	orders = map[int]*order{}
)

type call struct {
	Action string          `json:"action"`
	Params json.RawMessage `json:"params"`
}

func api(w http.ResponseWriter, r *http.Request) {
	var c call
	_ = json.NewDecoder(r.Body).Decode(&c)
	w.Header().Set("Content-Type", "application/json")
	mu.Lock()
	defer mu.Unlock()
	switch c.Action {
	case "createOrder":
		var o order
		_ = json.Unmarshal(c.Params, &o)
		o.ID, o.Status = nextID, "pending"
		nextID++
		orders[o.ID] = &o
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
	case "getOrder":
		var p struct{ ID int }
		_ = json.Unmarshal(c.Params, &p)
		o, found := orders[p.ID]
		if !found {
			// 200 with an error flag: caches, proxies and clients see success.
			_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": "not found"})
			return
		}
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "order": o})
	case "listOrders":
		// Offset paging over a map: unstable order, skipped and repeated rows.
		var p struct{ Page, Size int }
		_ = json.Unmarshal(c.Params, &p)
		list := []*order{}
		for _, o := range orders {
			list = append(list, o)
		}
		start := p.Page * p.Size
		if start > len(list) {
			start = len(list)
		}
		end := min(start+p.Size, len(list))
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "orders": list[start:end], "total": strconv.Itoa(len(list))})
	case "updateOrder":
		// Last write wins: no version, no precondition, lost updates.
		var o order
		_ = json.Unmarshal(c.Params, &o)
		orders[o.ID] = &o
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": true})
	default:
		_ = json.NewEncoder(w).Encode(map[string]any{"ok": false, "error": fmt.Sprintf("unknown action %q", c.Action)})
	}
}

func main() {
	http.HandleFunc("/api", api)
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

After ​

Problem Details in one helper. kind becomes the last segment of type, so clients switch on a stable string.

go
// Package orders is a small REST service built on the Go 1.22+ net/http
// router: resources and collections, Problem Details (RFC 9457) errors,
// ETag/If-Match optimistic concurrency, cursor (keyset) pagination,
// sparse fieldsets, Idempotency-Key on POST, RateLimit headers and a
// long-running operation behind 202 Accepted.
package orders

import (
	"encoding/json"
	"net/http"
)

// ProblemTypeBase prefixes every problem "type" URI. A real API points it at
// documentation pages that explain each problem.
const ProblemTypeBase = "https://api.example.com/problems/"

// Problem is an RFC 9457 problem details object with one extension member.
type Problem struct {
	Type     string       `json:"type"`
	Title    string       `json:"title"`
	Status   int          `json:"status"`
	Detail   string       `json:"detail,omitempty"`
	Instance string       `json:"instance,omitempty"`
	Errors   []FieldError `json:"errors,omitempty"`
}

// FieldError is the "errors" extension used for 422 validation failures.
type FieldError struct {
	Pointer string `json:"pointer"`
	Detail  string `json:"detail"`
}

// writeProblem sends application/problem+json. kind becomes the last segment of
// the type URI so clients can switch on it without parsing the title.
func writeProblem(w http.ResponseWriter, r *http.Request, status int, kind, title, detail string, errs ...FieldError) {
	p := Problem{
		Type:     ProblemTypeBase + kind,
		Title:    title,
		Status:   status,
		Detail:   detail,
		Instance: r.URL.Path,
		Errors:   errs,
	}
	w.Header().Set("Content-Type", "application/problem+json")
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(p)
}

The store keeps a Version per order (the ETag source), does compare-and-set updates, keeps tombstones for 410 and answers keyset queries.

go
package orders

import (
	"errors"
	"fmt"
	"sort"
	"sync"
	"time"
)

// Order is the resource. Version is the optimistic-concurrency counter that
// the ETag is derived from; a SQL table carries it as a "version" column.
type Order struct {
	ID         string    `json:"id"`
	Customer   string    `json:"customer"`
	Status     string    `json:"status"`
	TotalCents int64     `json:"total_cents"`
	Note       *string   `json:"note"`
	Version    int64     `json:"version"`
	CreatedAt  time.Time `json:"created_at"`
}

// Errors the handlers map to status codes.
var (
	ErrNotFound        = errors.New("not found")
	ErrGone            = errors.New("gone")
	ErrVersionMismatch = errors.New("version mismatch")
	ErrBadTransition   = errors.New("invalid status transition")
)

// allowed lists legal status transitions; anything else is a 409 Conflict.
var allowed = map[string][]string{
	"pending":   {"paid", "cancelled"},
	"paid":      {"shipped", "cancelled"},
	"shipped":   {},
	"cancelled": {},
}

func canMove(from, to string) bool {
	if from == to {
		return true
	}
	for _, s := range allowed[from] {
		if s == to {
			return true
		}
	}
	return false
}

// Store is an in-memory stand-in for a table ordered by primary key.
type Store struct {
	mu      sync.Mutex
	seq     int
	rows    map[string]*Order
	deleted map[string]bool
	now     func() time.Time
}

// NewStore returns an empty store; now is injectable for tests.
func NewStore(now func() time.Time) *Store {
	return &Store{rows: map[string]*Order{}, deleted: map[string]bool{}, now: now}
}

// Create inserts a new order with version 1. IDs are zero-padded so their
// string order equals insertion order, which keyset pagination relies on.
func (s *Store) Create(customer string, total int64, note *string) Order {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.seq++
	o := &Order{
		ID:         fmt.Sprintf("ord_%06d", s.seq),
		Customer:   customer,
		Status:     "pending",
		TotalCents: total,
		Note:       note,
		Version:    1,
		CreatedAt:  s.now().UTC(),
	}
	s.rows[o.ID] = o
	return *o
}

// Get returns a copy of one order, ErrGone for a deleted one.
func (s *Store) Get(id string) (Order, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return Order{}, ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	return *o, nil
}

// Update applies fn only when the stored version equals want: the same
// compare-and-set as UPDATE ... WHERE id = $1 AND version = $2.
func (s *Store) Update(id string, want int64, fn func(*Order) error) (Order, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return Order{}, ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	if o.Version != want {
		return *o, ErrVersionMismatch
	}
	next := *o
	if err := fn(&next); err != nil {
		return *o, err
	}
	if !canMove(o.Status, next.Status) {
		return *o, ErrBadTransition
	}
	next.Version++
	*o = next
	return next, nil
}

// Delete removes an order and keeps a tombstone so later reads answer 410.
func (s *Store) Delete(id string, want int64) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.deleted[id] {
		return ErrGone
	}
	o, ok := s.rows[id]
	if !ok {
		return ErrNotFound
	}
	if want != 0 && o.Version != want {
		return ErrVersionMismatch
	}
	delete(s.rows, id)
	s.deleted[id] = true
	return nil
}

// ListAfter is keyset pagination: rows with id > after, ordered by id,
// optionally filtered by status. It returns limit+1 rows at most so the
// caller can tell whether another page exists.
func (s *Store) ListAfter(after, status string, limit int) []Order {
	s.mu.Lock()
	defer s.mu.Unlock()
	ids := make([]string, 0, len(s.rows))
	for id := range s.rows {
		ids = append(ids, id)
	}
	sort.Strings(ids)
	out := []Order{}
	for _, id := range ids {
		if id <= after {
			continue
		}
		o := s.rows[id]
		if status != "" && o.Status != status {
			continue
		}
		out = append(out, *o)
		if len(out) == limit+1 {
			break
		}
	}
	return out
}

The handlers use Go 1.22 patterns ("GET /orders/{id}", r.PathValue("id")). The mux answers 405 with Allow for a known path and wrong method, and a GET pattern also serves HEAD. Writes check Content-Type (415), PATCH needs If-Match (428, 412), merge patch and JSON Patch are both supported, the collection is cursor-paginated with a Link header and sparse fieldsets, deletes leave a 410 tombstone, cancellation is a sub-resource, and exports are a long-running operation (202, then 303).

go
package orders

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"mime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"time"
)

// Server wires the store, the idempotency layer and the rate limiter.
type Server struct {
	store   *Store
	idem    *IdempotencyStore
	limiter *Limiter

	mu  sync.Mutex
	ops map[string]*Operation
	op  int

	// Exporter does the slow work behind POST /exports. Tests replace it.
	Exporter func(format string) string
}

// Operation is the status resource of a long-running job (202 + poll).
type Operation struct {
	ID     string `json:"id"`
	Status string `json:"status"` // running | succeeded
	Result string `json:"result,omitempty"`
}

// New builds a server. limit is requests per window per client.
func New(store *Store, now func() time.Time, limit int, window time.Duration) *Server {
	return &Server{
		store:    store,
		idem:     NewIdempotencyStore(now, 24*time.Hour),
		limiter:  NewLimiter(now, limit, window),
		ops:      map[string]*Operation{},
		Exporter: func(string) string { time.Sleep(200 * time.Millisecond); return "exp_1" },
	}
}

// Handler registers Go 1.22 method-and-wildcard patterns. The mux answers
// 405 with an Allow header for a known path and a wrong method, and a
// "GET" pattern also serves HEAD.
func (s *Server) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders", s.list)
	mux.Handle("POST /orders", s.idem.Middleware(http.HandlerFunc(s.create)))
	mux.HandleFunc("GET /orders/{id}", s.get)
	mux.HandleFunc("PATCH /orders/{id}", s.patch)
	mux.HandleFunc("DELETE /orders/{id}", s.delete)
	mux.HandleFunc("POST /orders/{id}/cancellation", s.cancel)
	mux.Handle("POST /exports", s.idem.Middleware(http.HandlerFunc(s.startExport)))
	mux.HandleFunc("GET /operations/{id}", s.operation)
	return s.limiter.Middleware(mux)
}

func etag(o Order) string { return fmt.Sprintf(`"%s-v%d"`, o.ID, o.Version) }

// versionFromETag turns `"ord_000001-v3"` back into 3 for that id.
func versionFromETag(tag, id string) (int64, bool) {
	tag = strings.TrimSpace(tag)
	if strings.HasPrefix(tag, "W/") { // If-Match needs strong comparison
		return 0, false
	}
	tag = strings.Trim(tag, `"`)
	prefix := id + "-v"
	if !strings.HasPrefix(tag, prefix) {
		return 0, false
	}
	v, err := strconv.ParseInt(strings.TrimPrefix(tag, prefix), 10, 64)
	return v, err == nil
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

func hasMediaType(r *http.Request, want ...string) bool {
	mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
	if err != nil {
		return false
	}
	for _, w := range want {
		if mt == w {
			return true
		}
	}
	return false
}

func (s *Server) storeError(w http.ResponseWriter, r *http.Request, err error) {
	switch {
	case errors.Is(err, ErrNotFound):
		writeProblem(w, r, http.StatusNotFound, "not-found", "Order not found", "")
	case errors.Is(err, ErrGone):
		writeProblem(w, r, http.StatusGone, "gone", "Order was deleted", "")
	case errors.Is(err, ErrVersionMismatch):
		writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed",
			"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.")
	case errors.Is(err, ErrBadTransition):
		writeProblem(w, r, http.StatusConflict, "invalid-transition", "Status change not allowed", err.Error())
	default:
		writeProblem(w, r, http.StatusInternalServerError, "internal", "Internal error", "")
	}
}

// ---- collection ----

type cursor struct {
	After  string `json:"a"`
	Status string `json:"s,omitempty"`
}

func encodeCursor(c cursor) string {
	b, _ := json.Marshal(c)
	return base64.RawURLEncoding.EncodeToString(b)
}

func decodeCursor(s string) (cursor, error) {
	var c cursor
	b, err := base64.RawURLEncoding.DecodeString(s)
	if err != nil {
		return c, err
	}
	return c, json.Unmarshal(b, &c)
}

var listable = map[string]bool{"id": true, "customer": true, "status": true, "total_cents": true, "note": true, "version": true, "created_at": true}

// sparse keeps only the requested top-level fields (fields=id,status).
func sparse(o Order, fields []string) map[string]any {
	b, _ := json.Marshal(o)
	var all map[string]any
	_ = json.Unmarshal(b, &all)
	if len(fields) == 0 {
		return all
	}
	out := map[string]any{}
	for _, f := range fields {
		out[f] = all[f]
	}
	return out
}

func (s *Server) list(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	limit := 20
	if v := q.Get("limit"); v != "" {
		n, err := strconv.Atoi(v)
		if err != nil || n < 1 || n > 100 {
			writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Invalid limit", "limit must be an integer from 1 to 100",
				FieldError{Pointer: "#/query/limit", Detail: "out of range"})
			return
		}
		limit = n
	}
	c := cursor{Status: q.Get("status")}
	if v := q.Get("cursor"); v != "" {
		dc, err := decodeCursor(v)
		if err != nil || (q.Has("status") && dc.Status != c.Status) {
			writeProblem(w, r, http.StatusBadRequest, "invalid-cursor", "Invalid cursor",
				"Use the cursor exactly as returned, with the same filters.")
			return
		}
		c = dc
	}
	var fields []string
	if v := q.Get("fields"); v != "" {
		for _, f := range strings.Split(v, ",") {
			if !listable[f] {
				writeProblem(w, r, http.StatusBadRequest, "invalid-parameter", "Unknown field", f,
					FieldError{Pointer: "#/query/fields", Detail: "unknown field " + f})
				return
			}
			fields = append(fields, f)
		}
	}
	rows := s.store.ListAfter(c.After, c.Status, limit)
	page := map[string]any{}
	data := []map[string]any{}
	for i, o := range rows {
		if i == limit {
			break
		}
		data = append(data, sparse(o, fields))
	}
	page["data"] = data
	if len(rows) > limit {
		next := encodeCursor(cursor{After: rows[limit-1].ID, Status: c.Status})
		nq := url.Values{"cursor": {next}, "limit": {strconv.Itoa(limit)}}
		if len(fields) > 0 {
			nq.Set("fields", strings.Join(fields, ","))
		}
		page["next_cursor"] = next
		w.Header().Set("Link", fmt.Sprintf(`</orders?%s>; rel="next"`, nq.Encode()))
	}
	w.Header().Set("Cache-Control", "private, no-cache")
	writeJSON(w, http.StatusOK, page)
}

type createReq struct {
	Customer   string  `json:"customer"`
	TotalCents int64   `json:"total_cents"`
	Note       *string `json:"note"`
}

func (s *Server) create(w http.ResponseWriter, r *http.Request) {
	if !hasMediaType(r, "application/json") {
		writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Send application/json", "")
		return
	}
	dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
	dec.DisallowUnknownFields()
	var in createReq
	if err := dec.Decode(&in); err != nil {
		writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed request body", err.Error())
		return
	}
	var errs []FieldError
	if strings.TrimSpace(in.Customer) == "" {
		errs = append(errs, FieldError{Pointer: "#/customer", Detail: "is required"})
	}
	if in.TotalCents <= 0 {
		errs = append(errs, FieldError{Pointer: "#/total_cents", Detail: "must be greater than 0"})
	}
	if len(errs) > 0 {
		writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Validation failed", "", errs...)
		return
	}
	o := s.store.Create(in.Customer, in.TotalCents, in.Note)
	w.Header().Set("Location", "/orders/"+o.ID)
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusCreated, o)
}

// ---- item ----

func (s *Server) get(w http.ResponseWriter, r *http.Request) {
	o, err := s.store.Get(r.PathValue("id"))
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	tag := etag(o)
	w.Header().Set("ETag", tag)
	w.Header().Set("Cache-Control", "private, no-cache")
	for _, t := range strings.Split(r.Header.Get("If-None-Match"), ",") {
		t = strings.TrimPrefix(strings.TrimSpace(t), "W/") // weak comparison for GET
		if t == tag || t == "*" {
			w.WriteHeader(http.StatusNotModified)
			return
		}
	}
	writeJSON(w, http.StatusOK, o)
}

// precondition enforces If-Match on writes: 428 when absent, 412 when it
// cannot match. It returns the version the client claims to have read.
func (s *Server) precondition(w http.ResponseWriter, r *http.Request, id string) (int64, bool) {
	h := r.Header.Get("If-Match")
	if h == "" {
		writeProblem(w, r, http.StatusPreconditionRequired, "precondition-required", "If-Match required",
			"GET the order and send its ETag in If-Match.")
		return 0, false
	}
	v, ok := versionFromETag(h, id)
	if !ok {
		writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "ETag does not belong to this order")
		return 0, false
	}
	return v, true
}

// applyMerge implements RFC 7396 for the writable members: a member with
// null removes the value, an absent member leaves it unchanged.
func applyMerge(o *Order, patch map[string]json.RawMessage) []FieldError {
	var errs []FieldError
	for k, raw := range patch {
		switch k {
		case "customer", "status":
			var v string
			if err := json.Unmarshal(raw, &v); err != nil || v == "" {
				errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "must be a non-empty string"})
				continue
			}
			if k == "customer" {
				o.Customer = v
			} else {
				o.Status = v
			}
		case "note":
			if string(raw) == "null" {
				o.Note = nil
				continue
			}
			var v string
			if err := json.Unmarshal(raw, &v); err != nil {
				errs = append(errs, FieldError{Pointer: "#/note", Detail: "must be a string or null"})
				continue
			}
			o.Note = &v
		default:
			errs = append(errs, FieldError{Pointer: "#/" + k, Detail: "is read-only or unknown"})
		}
	}
	return errs
}

type jsonPatchOp struct {
	Op    string          `json:"op"`
	Path  string          `json:"path"`
	Value json.RawMessage `json:"value"`
}

// applyJSONPatch supports the RFC 6902 ops that make sense on a flat
// resource: test, replace, add and remove. Any failed test aborts the whole
// document, which is how RFC 6902 makes a patch atomic.
func applyJSONPatch(o *Order, ops []jsonPatchOp) []FieldError {
	for i, op := range ops {
		name := strings.TrimPrefix(op.Path, "/")
		ptr := fmt.Sprintf("#/%d", i)
		switch op.Op {
		case "test":
			cur := sparse(*o, []string{name})[name]
			var want any
			_ = json.Unmarshal(op.Value, &want)
			if fmt.Sprint(cur) != fmt.Sprint(want) {
				return []FieldError{{Pointer: ptr, Detail: "test failed for " + op.Path}}
			}
		case "replace", "add":
			if errs := applyMerge(o, map[string]json.RawMessage{name: op.Value}); errs != nil {
				return errs
			}
		case "remove":
			if name != "note" {
				return []FieldError{{Pointer: ptr, Detail: "only /note can be removed"}}
			}
			o.Note = nil
		default:
			return []FieldError{{Pointer: ptr, Detail: "unsupported op " + op.Op}}
		}
	}
	return nil
}

func (s *Server) patch(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	w.Header().Set("Accept-Patch", "application/merge-patch+json, application/json-patch+json")
	merge := hasMediaType(r, "application/merge-patch+json")
	if !merge && !hasMediaType(r, "application/json-patch+json") {
		writeProblem(w, r, http.StatusUnsupportedMediaType, "unsupported-media-type", "Unsupported patch format",
			"Use application/merge-patch+json or application/json-patch+json")
		return
	}
	want, ok := s.precondition(w, r, id)
	if !ok {
		return
	}
	body := http.MaxBytesReader(w, r.Body, 1<<20)
	var mergeDoc map[string]json.RawMessage
	var ops []jsonPatchOp
	var err error
	if merge {
		err = json.NewDecoder(body).Decode(&mergeDoc)
	} else {
		err = json.NewDecoder(body).Decode(&ops)
	}
	if err != nil {
		writeProblem(w, r, http.StatusBadRequest, "malformed-json", "Malformed patch document", err.Error())
		return
	}
	var verrs []FieldError
	o, err := s.store.Update(id, want, func(o *Order) error {
		if merge {
			verrs = applyMerge(o, mergeDoc)
		} else {
			verrs = applyJSONPatch(o, ops)
		}
		if verrs != nil {
			return errors.New("validation")
		}
		return nil
	})
	if verrs != nil {
		writeProblem(w, r, http.StatusUnprocessableEntity, "validation", "Patch cannot be applied", "", verrs...)
		return
	}
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusOK, o)
}

func (s *Server) delete(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	var want int64
	if h := r.Header.Get("If-Match"); h != "" {
		v, ok := versionFromETag(h, id)
		if !ok {
			writeProblem(w, r, http.StatusPreconditionFailed, "stale-etag", "Precondition failed", "")
			return
		}
		want = v
	}
	if err := s.store.Delete(id, want); err != nil {
		s.storeError(w, r, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// cancel is a state change modelled as creating a "cancellation"
// sub-resource instead of a verb in the URI (POST /cancelOrder).
// Cancelling an already cancelled order returns the same 200: the
// effect is idempotent even though POST is not by definition.
func (s *Server) cancel(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	cur, err := s.store.Get(id)
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	o, err := s.store.Update(id, cur.Version, func(o *Order) error { o.Status = "cancelled"; return nil })
	if err != nil {
		s.storeError(w, r, err)
		return
	}
	w.Header().Set("ETag", etag(o))
	writeJSON(w, http.StatusOK, o)
}

// ---- long-running operation ----

func (s *Server) startExport(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	s.op++
	op := &Operation{ID: fmt.Sprintf("op_%d", s.op), Status: "running"}
	s.ops[op.ID] = op
	snapshot := *op
	s.mu.Unlock()
	format := r.URL.Query().Get("format")
	go func() {
		res := s.Exporter(format)
		s.mu.Lock()
		op.Status, op.Result = "succeeded", "/exports/"+res
		s.mu.Unlock()
	}()
	w.Header().Set("Location", "/operations/"+op.ID)
	w.Header().Set("Retry-After", "1")
	writeJSON(w, http.StatusAccepted, snapshot)
}

// operation answers 200 while the job runs and 303 See Other, pointing at
// the result, once it has finished.
func (s *Server) operation(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	op, ok := s.ops[r.PathValue("id")]
	var snap Operation
	if ok {
		snap = *op
	}
	s.mu.Unlock()
	if !ok {
		writeProblem(w, r, http.StatusNotFound, "not-found", "Operation not found", "")
		return
	}
	if snap.Status == "succeeded" {
		w.Header().Set("Location", snap.Result)
		w.WriteHeader(http.StatusSeeOther)
		return
	}
	w.Header().Set("Retry-After", "1")
	writeJSON(w, http.StatusOK, snap)
}

Idempotency-Key middleware implementing the draft's 400/409/422/replay contract, scoped per client and fingerprinted on method, path and body:

go
package orders

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"net/http"
	"strings"
	"sync"
	"time"
)

// IdempotencyStore implements the API contract of the IETF Idempotency-Key
// draft for POST: 400 when the key is missing, 409 while the first request
// is still running, 422 when the key is reused with a different payload, and
// a replay of the stored response otherwise. Storage design (SQL table,
// Redis, TTL sweeps) is the subject of /system-design/api-idempotency; this
// one is in memory.
type IdempotencyStore struct {
	mu   sync.Mutex
	rows map[string]*idemRow
	now  func() time.Time
	ttl  time.Duration
}

type idemRow struct {
	fingerprint string
	done        bool
	status      int
	header      http.Header
	body        []byte
	expires     time.Time
}

// NewIdempotencyStore keeps keys for ttl (the draft asks servers to publish it).
func NewIdempotencyStore(now func() time.Time, ttl time.Duration) *IdempotencyStore {
	return &IdempotencyStore{rows: map[string]*idemRow{}, now: now, ttl: ttl}
}

// parseKey accepts the draft's sf-string form ("abc") and, leniently, a bare token.
func parseKey(h string) string {
	h = strings.TrimSpace(h)
	if len(h) >= 2 && h[0] == '"' && h[len(h)-1] == '"' {
		h = h[1 : len(h)-1]
	}
	if len(h) > 255 {
		return ""
	}
	return h
}

type recorder struct {
	http.ResponseWriter
	status int
	buf    bytes.Buffer
}

func (r *recorder) WriteHeader(code int) { r.status = code; r.ResponseWriter.WriteHeader(code) }
func (r *recorder) Write(b []byte) (int, error) {
	if r.status == 0 {
		r.status = http.StatusOK
	}
	r.buf.Write(b)
	return r.ResponseWriter.Write(b)
}

// Middleware wraps a POST handler.
func (s *IdempotencyStore) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := parseKey(r.Header.Get("Idempotency-Key"))
		if key == "" {
			writeProblem(w, r, http.StatusBadRequest, "idempotency-key-missing", "Idempotency-Key is missing",
				"This operation requires an Idempotency-Key header (1 to 255 characters).")
			return
		}
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil {
			writeProblem(w, r, http.StatusRequestEntityTooLarge, "too-large", "Body too large", "")
			return
		}
		r.Body = io.NopCloser(bytes.NewReader(body))
		sum := sha256.Sum256(append([]byte(r.Method+" "+r.URL.Path+"\n"), body...))
		fp := hex.EncodeToString(sum[:])
		// Scope keys by caller so two tenants cannot collide or probe each other.
		scoped := r.Header.Get("X-Client-Id") + "|" + key

		s.mu.Lock()
		row, seen := s.rows[scoped]
		if seen && s.now().After(row.expires) {
			delete(s.rows, scoped)
			seen = false
		}
		switch {
		case seen && row.fingerprint != fp:
			s.mu.Unlock()
			writeProblem(w, r, http.StatusUnprocessableEntity, "idempotency-key-reused", "Idempotency-Key is already used",
				"The key was used with a different request payload.")
			return
		case seen && !row.done:
			s.mu.Unlock()
			w.Header().Set("Retry-After", "1")
			writeProblem(w, r, http.StatusConflict, "idempotency-key-in-flight", "A request is outstanding for this Idempotency-Key", "")
			return
		case seen:
			s.mu.Unlock()
			for k, v := range row.header {
				w.Header()[k] = v
			}
			w.Header().Set("Idempotent-Replayed", "true")
			w.WriteHeader(row.status)
			_, _ = w.Write(row.body)
			return
		}
		row = &idemRow{fingerprint: fp, expires: s.now().Add(s.ttl)}
		s.rows[scoped] = row
		s.mu.Unlock()

		rec := &recorder{ResponseWriter: w}
		next.ServeHTTP(rec, r)

		s.mu.Lock()
		defer s.mu.Unlock()
		if rec.status >= 400 {
			// Do not pin a failure to the key: the client may fix the request
			// (4xx) or the server may recover (5xx) and the same key retried.
			delete(s.rows, scoped)
			return
		}
		// Replay only the headers that describe the result, not per-response
		// ones such as RateLimit.
		keep := http.Header{}
		for _, k := range []string{"Content-Type", "Location", "ETag"} {
			if v := w.Header().Values(k); len(v) > 0 {
				keep[k] = v
			}
		}
		row.done, row.status, row.header, row.body = true, rec.status, keep, rec.buf.Bytes()
	})
}

RateLimit headers (draft -12 syntax) on a fixed-window limiter:

go
package orders

import (
	"fmt"
	"net"
	"net/http"
	"strconv"
	"sync"
	"time"
)

// Limiter is a fixed-window counter per client that advertises its policy
// with the IETF RateLimit-Policy / RateLimit fields (draft-ietf-httpapi-
// ratelimit-headers-12 syntax) and answers 429 with Retry-After. The
// algorithms themselves live in /system-design/rate-limiting-algorithms.
type Limiter struct {
	mu     sync.Mutex
	now    func() time.Time
	limit  int
	window time.Duration
	counts map[string]*windowCount
}

type windowCount struct {
	start time.Time
	n     int
}

// NewLimiter allows limit requests per window per client key.
func NewLimiter(now func() time.Time, limit int, window time.Duration) *Limiter {
	return &Limiter{now: now, limit: limit, window: window, counts: map[string]*windowCount{}}
}

func clientKey(r *http.Request) string {
	if id := r.Header.Get("X-Client-Id"); id != "" {
		return id // an authenticated client id in a real API
	}
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return r.RemoteAddr
	}
	return host
}

// Middleware applies the limit to every request.
func (l *Limiter) Middleware(next http.Handler) http.Handler {
	w := int(l.window / time.Second)
	policy := fmt.Sprintf("default;q=%d;w=%d", l.limit, w)
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		now := l.now()
		l.mu.Lock()
		c, ok := l.counts[clientKey(r)]
		if !ok || now.Sub(c.start) >= l.window {
			c = &windowCount{start: now}
			l.counts[clientKey(r)] = c
		}
		c.n++
		remaining := max(l.limit-c.n, 0)
		reset := int((l.window - now.Sub(c.start) + time.Second - 1) / time.Second)
		over := c.n > l.limit
		l.mu.Unlock()

		rw.Header().Set("RateLimit-Policy", policy)
		rw.Header().Set("RateLimit", fmt.Sprintf("default;a=%d;w=%d", remaining, reset))
		if over {
			rw.Header().Set("Retry-After", strconv.Itoa(reset))
			writeProblem(rw, r, http.StatusTooManyRequests, "rate-limited", "Too many requests",
				fmt.Sprintf("Limit is %d requests per %d s. Retry after %d s.", l.limit, w, reset))
			return
		}
		next.ServeHTTP(rw, r)
	})
}

Tests with httptest. httptest.NewServer runs the real handler on a loopback port; an injected clock makes rate-limit windows deterministic. They cover 201 + Location + ETag, the four Idempotency-Key outcomes, 422/415/400 as Problem Details, 304, 428, 412, a failing JSON Patch test, 409 on a bad transition, cursor pages that visit every row exactly once with sparse fields, 204 then 410, 405 with Allow, HEAD, 429 with Retry-After, and 202 then 303.

go
package orders

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time { return c.t }

func newTest(t *testing.T, limit int) (*Server, *httptest.Server, *clock) {
	t.Helper()
	c := &clock{t: time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)}
	s := New(NewStore(c.now), c.now, limit, time.Minute)
	ts := httptest.NewServer(s.Handler())
	t.Cleanup(ts.Close)
	return s, ts, c
}

func do(t *testing.T, ts *httptest.Server, method, path, body string, hdr ...string) *http.Response {
	t.Helper()
	req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
	if err != nil {
		t.Fatal(err)
	}
	for i := 0; i+1 < len(hdr); i += 2 {
		req.Header.Set(hdr[i], hdr[i+1])
	}
	cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
	res, err := cl.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { res.Body.Close() })
	return res
}

func decode[T any](t *testing.T, res *http.Response) T {
	t.Helper()
	var v T
	if err := json.NewDecoder(res.Body).Decode(&v); err != nil {
		t.Fatal(err)
	}
	return v
}

func create(t *testing.T, ts *httptest.Server, key, body string) *http.Response {
	return do(t, ts, "POST", "/orders", body, "Content-Type", "application/json", "Idempotency-Key", `"`+key+`"`)
}

func TestCreateReturns201LocationAndETag(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	res := create(t, ts, "k1", `{"customer":"c-42","total_cents":4999}`)
	if res.StatusCode != 201 || res.Header.Get("Location") != "/orders/ord_000001" || res.Header.Get("ETag") != `"ord_000001-v1"` {
		t.Fatalf("got %d %q %q", res.StatusCode, res.Header.Get("Location"), res.Header.Get("ETag"))
	}
}

func TestIdempotencyKeyContract(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	body := `{"customer":"c-42","total_cents":4999}`
	if res := do(t, ts, "POST", "/orders", body, "Content-Type", "application/json"); res.StatusCode != 400 {
		t.Fatalf("missing key: want 400, got %d", res.StatusCode)
	}
	first := decode[Order](t, create(t, ts, "k1", body))
	replay := create(t, ts, "k1", body)
	again := decode[Order](t, replay)
	if replay.StatusCode != 201 || replay.Header.Get("Idempotent-Replayed") != "true" || again.ID != first.ID {
		t.Fatalf("replay: %d %q %s vs %s", replay.StatusCode, replay.Header.Get("Idempotent-Replayed"), again.ID, first.ID)
	}
	if res := create(t, ts, "k1", `{"customer":"c-42","total_cents":1}`); res.StatusCode != 422 {
		t.Fatalf("reuse with other payload: want 422, got %d", res.StatusCode)
	}
	if res := create(t, ts, "k2", body); decode[Order](t, res).ID == first.ID {
		t.Fatal("a new key must create a new order")
	}
}

func TestValidationIsProblemDetails(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	res := create(t, ts, "k1", `{"customer":"","total_cents":0}`)
	if res.StatusCode != 422 || res.Header.Get("Content-Type") != "application/problem+json" {
		t.Fatalf("got %d %s", res.StatusCode, res.Header.Get("Content-Type"))
	}
	p := decode[Problem](t, res)
	if p.Type != ProblemTypeBase+"validation" || len(p.Errors) != 2 || p.Status != 422 {
		t.Fatalf("problem: %+v", p)
	}
	if res := do(t, ts, "POST", "/orders", `x`, "Content-Type", "text/plain", "Idempotency-Key", "k9"); res.StatusCode != 415 {
		t.Fatalf("want 415, got %d", res.StatusCode)
	}
	if res := create(t, ts, "k8", `{"customer":"a","total_cents":1,"admin":true}`); res.StatusCode != 400 {
		t.Fatalf("unknown member: want 400, got %d", res.StatusCode)
	}
}

func TestConditionalGetAndOptimisticConcurrency(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	create(t, ts, "k1", `{"customer":"c-42","total_cents":4999,"note":"leave at door"}`)
	res := do(t, ts, "GET", "/orders/ord_000001", "")
	tag := res.Header.Get("ETag")
	if res := do(t, ts, "GET", "/orders/ord_000001", "", "If-None-Match", tag); res.StatusCode != 304 {
		t.Fatalf("want 304, got %d", res.StatusCode)
	}
	merge := []string{"Content-Type", "application/merge-patch+json"}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, merge...); res.StatusCode != 428 {
		t.Fatalf("no If-Match: want 428, got %d", res.StatusCode)
	}
	// Alice patches with the ETag she read: 200 and a new ETag.
	ok := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid","note":null}`, append(merge, "If-Match", tag)...)
	o := decode[Order](t, ok)
	if ok.StatusCode != 200 || o.Version != 2 || o.Note != nil || ok.Header.Get("ETag") != `"ord_000001-v2"` {
		t.Fatalf("patch: %d %+v", ok.StatusCode, o)
	}
	// Bob still holds the old ETag: 412, his write cannot silently win.
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"customer":"bob"}`, append(merge, "If-Match", tag)...); res.StatusCode != 412 {
		t.Fatalf("stale If-Match: want 412, got %d", res.StatusCode)
	}
	// JSON Patch with a failing test op changes nothing.
	jp := []string{"Content-Type", "application/json-patch+json", "If-Match", `"ord_000001-v2"`}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 422 {
		t.Fatalf("failed test op: want 422, got %d", res.StatusCode)
	}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `[{"op":"test","path":"/status","value":"paid"},{"op":"replace","path":"/status","value":"shipped"}]`, jp...); res.StatusCode != 200 {
		t.Fatalf("json patch: want 200, got %d", res.StatusCode)
	}
	// shipped -> pending is not a legal transition: 409.
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"pending"}`, append(merge, "If-Match", `"ord_000001-v3"`)...); res.StatusCode != 409 {
		t.Fatalf("bad transition: want 409, got %d", res.StatusCode)
	}
	if res := do(t, ts, "PATCH", "/orders/ord_000001", `{"status":"paid"}`, "Content-Type", "application/json", "If-Match", `"ord_000001-v3"`); res.StatusCode != 415 || res.Header.Get("Accept-Patch") == "" {
		t.Fatalf("wrong patch type: want 415 + Accept-Patch, got %d", res.StatusCode)
	}
}

func TestCursorPaginationWalksEveryRowOnce(t *testing.T) {
	_, ts, _ := newTest(t, 1000)
	for i := 0; i < 7; i++ {
		create(t, ts, "k"+string(rune('a'+i)), `{"customer":"c","total_cents":100}`)
	}
	type page struct {
		Data []map[string]any `json:"data"`
		Next string           `json:"next_cursor"`
	}
	seen := map[string]bool{}
	path := "/orders?limit=3&fields=id,status"
	for pages := 0; path != ""; pages++ {
		res := do(t, ts, "GET", path, "")
		p := decode[page](t, res)
		for _, row := range p.Data {
			if len(row) != 2 {
				t.Fatalf("sparse fieldset ignored: %v", row)
			}
			id := row["id"].(string)
			if seen[id] {
				t.Fatalf("duplicate %s", id)
			}
			seen[id] = true
		}
		path = ""
		if link := res.Header.Get("Link"); link != "" {
			path = strings.TrimSuffix(strings.TrimPrefix(link, "<"), `>; rel="next"`)
		}
		if pages > 5 {
			t.Fatal("too many pages")
		}
	}
	if len(seen) != 7 {
		t.Fatalf("saw %d rows, want 7", len(seen))
	}
	if res := do(t, ts, "GET", "/orders?cursor=not-a-cursor!", ""); res.StatusCode != 400 {
		t.Fatalf("bad cursor: want 400, got %d", res.StatusCode)
	}
}

func TestDeleteThen410AndMethodNotAllowed(t *testing.T) {
	_, ts, _ := newTest(t, 100)
	create(t, ts, "k1", `{"customer":"c","total_cents":100}`)
	if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 204 {
		t.Fatalf("want 204, got %d", res.StatusCode)
	}
	if res := do(t, ts, "DELETE", "/orders/ord_000001", ""); res.StatusCode != 410 {
		t.Fatalf("second delete: want 410, got %d", res.StatusCode)
	}
	if res := do(t, ts, "GET", "/orders/ord_999999", ""); res.StatusCode != 404 {
		t.Fatalf("want 404, got %d", res.StatusCode)
	}
	res := do(t, ts, "PUT", "/orders/ord_000001", "{}")
	if res.StatusCode != 405 || !strings.Contains(res.Header.Get("Allow"), "PATCH") {
		t.Fatalf("want 405 with Allow, got %d %q", res.StatusCode, res.Header.Get("Allow"))
	}
	if res := do(t, ts, "HEAD", "/orders", ""); res.StatusCode != 200 {
		t.Fatalf("HEAD: want 200, got %d", res.StatusCode)
	}
}

func TestRateLimitHeadersAnd429(t *testing.T) {
	_, ts, c := newTest(t, 2)
	res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	if res.Header.Get("RateLimit-Policy") != "default;q=2;w=60" || res.Header.Get("RateLimit") != "default;a=1;w=60" {
		t.Fatalf("headers: %q %q", res.Header.Get("RateLimit-Policy"), res.Header.Get("RateLimit"))
	}
	do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	c.t = c.t.Add(20 * time.Second)
	res = do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-1")
	if res.StatusCode != 429 || res.Header.Get("Retry-After") != "40" {
		t.Fatalf("want 429 Retry-After 40, got %d %q", res.StatusCode, res.Header.Get("Retry-After"))
	}
	if res := do(t, ts, "GET", "/orders", "", "X-Client-Id", "app-2"); res.StatusCode != 200 {
		t.Fatalf("other client: want 200, got %d", res.StatusCode)
	}
}

func TestLongRunningOperation(t *testing.T) {
	s, ts, _ := newTest(t, 1000)
	release := make(chan struct{})
	s.Exporter = func(string) string { <-release; return "exp_7" }
	res := do(t, ts, "POST", "/exports?format=csv", "", "Idempotency-Key", "e1")
	if res.StatusCode != 202 || res.Header.Get("Location") != "/operations/op_1" {
		t.Fatalf("want 202 + Location, got %d %q", res.StatusCode, res.Header.Get("Location"))
	}
	if res := do(t, ts, "GET", "/operations/op_1", ""); res.StatusCode != 200 {
		t.Fatalf("running: want 200, got %d", res.StatusCode)
	}
	close(release)
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		res := do(t, ts, "GET", "/operations/op_1", "")
		if res.StatusCode == 303 {
			if res.Header.Get("Location") != "/exports/exp_7" {
				t.Fatalf("Location %q", res.Header.Get("Location"))
			}
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
	t.Fatal("operation never finished")
}

The server used in the lab:

go
// Command server runs the orders API on 127.0.0.1:8080 for the lab.
package main

import (
	"log"
	"net/http"
	"time"

	"academy/rest-api-design/orders"
)

func main() {
	srv := orders.New(orders.NewStore(time.Now), time.Now, 100, time.Minute)
	h := &http.Server{
		Addr:              "127.0.0.1:8080",
		Handler:           srv.Handler(),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      10 * time.Second,
	}
	log.Println("listening on", h.Addr)
	log.Fatal(h.ListenAndServe())
}

The Go angle ​

Go featureUse hereNote
http.ServeMux patterns (Go 1.22+)"GET /orders/{id}", "POST /orders/{id}/cancellation""the most specific pattern wins"; 405 + Allow automatic
Request.PathValueRead {id}{path...} matches the rest; {$} matches only the exact path with trailing slash
mime.ParseMediaType415 checksIgnores parameters such as charset
json.Decoder.DisallowUnknownFieldsStrict create bodiesUse a separate decoder for PATCH
http.MaxBytesReaderBody limitsReturns an error after the limit
net/http/httptestNewServer, NewRecorder for testsNo real network needed beyond loopback
encoding/base64.RawURLEncodingOpaque, URL-safe cursorsSign or encrypt if cursors must not be forged
http.ServeContentByte ranges (206) and conditional GET for filesNot for JSON resources
Ecosystemoapi-codegen (OpenAPI to Go), chi, echo, gin routersThe stdlib mux is enough for most services since 1.22

Laravel ​

Before ​

Verbs in URIs, mass assignment from $request->all(), the model serialised as-is, 200 for "not found", no ownership check, offset pages with a client-controlled size.

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * The shape many first Laravel APIs take: verbs in the URI, 200 for
 * everything, the model serialized as-is, offset paging, no ownership
 * check, last write wins and a retried POST creates a second order.
 *
 * Route::post('/api/createOrder', [OrderControllerBefore::class, 'create']);
 * Route::get('/api/getOrders', [OrderControllerBefore::class, 'list']);
 * Route::post('/api/updateOrder/{id}', [OrderControllerBefore::class, 'update']);
 */
class OrderControllerBefore
{
    public function create(Request $request): JsonResponse
    {
        // Mass assignment straight from input, no validation.
        $order = Order::create($request->all());

        return response()->json(['success' => true, 'order' => $order]);
    }

    public function list(Request $request): JsonResponse
    {
        // Every column (internal ones too), offset paging, COUNT(*) per page.
        $orders = Order::paginate($request->integer('per_page', 1000));

        return response()->json(['success' => true, 'data' => $orders]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $order = Order::find($id);
        if ($order === null) {
            // A "not found" that every cache and client reads as success.
            return response()->json(['success' => false, 'error' => 'not found']);
        }
        $order->update($request->all());

        return response()->json(['success' => true]);
    }
}

After ​

Routes. Route::apiResource registers index, store, show, update and destroy without the HTML-only create/edit routes; middlewareFor('store', ...) attaches the idempotency middleware to one action; withTrashed(['show']) lets soft-deleted orders reach show() so it can answer 410.

php
<?php

use App\Http\Controllers\OperationController;
use App\Http\Controllers\OrderController;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Support\Facades\Route;

// bootstrap/app.php loads this file with the "api" prefix, so these are
// /api/orders, /api/orders/{order}, /api/exports and /api/operations/{operation}.
Route::middleware(['auth:sanctum'])->group(function () {
    // index, store, show, update, destroy; no HTML-only create/edit routes.
    // {order} is resolved by Order::getRouteKeyName() (public_id).
    // withTrashed(['show']) lets show() see soft-deleted rows and answer 410.
    Route::apiResource('orders', OrderController::class)
        ->middlewareFor('store', RequireIdempotencyKey::class)
        ->withTrashed(['show']);

    // A state change modelled as a sub-resource, not POST /cancelOrder.
    Route::post('orders/{order}/cancellation', [OrderController::class, 'cancel'])
        ->name('orders.cancel');

    // Long-running work: 202 Accepted + a status resource.
    Route::post('exports', [OperationController::class, 'store'])
        ->middleware([RequireIdempotencyKey::class, 'throttle:exports'])
        ->name('exports.store');
    Route::get('operations/{operation}', [OperationController::class, 'show'])
        ->whereUuid('operation')
        ->name('operations.show');
});

The model: getRouteKeyName() makes route model binding resolve {order} by an opaque public_id; the version column feeds the ETag.

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Order extends Model
{
    use HasFactory, SoftDeletes;

    public const STATUSES = ['pending', 'paid', 'shipped', 'cancelled'];

    private const TRANSITIONS = [
        'pending' => ['paid', 'cancelled'],
        'paid' => ['shipped', 'cancelled'],
        'shipped' => [],
        'cancelled' => [],
    ];

    protected $fillable = ['customer_id', 'total_cents', 'note', 'status'];

    protected $attributes = ['status' => 'pending', 'version' => 1];

    protected static function booted(): void
    {
        // Public, non-guessable identifier; the integer key never leaves the database.
        static::creating(fn (Order $order) => $order->public_id ??= 'ord_'.Str::lower((string) Str::ulid()));
    }

    /** Route model binding resolves {order} by this column. */
    public function getRouteKeyName(): string
    {
        return 'public_id';
    }

    public function etag(): string
    {
        return "{$this->public_id}-v{$this->version}";
    }

    public function canMoveTo(string $status): bool
    {
        return $status === $this->status || in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
    }

    protected function casts(): array
    {
        return ['total_cents' => 'integer', 'version' => 'integer'];
    }
}

Form Requests. authorize() returning false gives 403 before the controller runs; failed rules give 422. sometimes plus nullable gives JSON Merge Patch semantics, and prohibited rejects read-only members.

php
<?php

namespace App\Http\Requests;

use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;

class StoreOrderRequest extends FormRequest
{
    /** A false return becomes 403 before the controller runs. */
    public function authorize(): bool
    {
        return $this->user()->can('create', Order::class);
    }

    /** Failing rules become 422; bootstrap/app.php renders it as Problem Details. */
    public function rules(): array
    {
        return [
            'total_cents' => ['required', 'integer', 'min:1'],
            'note' => ['nullable', 'string', 'max:500'],
        ];
    }
}
php
<?php

namespace App\Http\Requests;

use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
 * JSON Merge Patch (RFC 7396) semantics with Laravel rules: "sometimes"
 * means an absent member is left unchanged, "nullable" lets null clear it.
 * Laravel parses application/merge-patch+json because isJson() accepts
 * any Content-Type containing "+json".
 */
class UpdateOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        // Route model binding already resolved {order}.
        return $this->user()->can('update', $this->route('order'));
    }

    public function rules(): array
    {
        return [
            'status' => ['sometimes', 'required', Rule::in(Order::STATUSES)],
            'note' => ['sometimes', 'nullable', 'string', 'max:500'],
            // Read-only members are rejected, not silently ignored.
            'id' => ['prohibited'],
            'version' => ['prohibited'],
            'total_cents' => ['prohibited'],
        ];
    }
}

API Resource: the representation is a contract, with sparse fieldsets and state-dependent links.

php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;

/**
 * The representation is a contract, not the table: the integer key, the
 * customer foreign key and deleted_at never leave the server.
 */
class OrderResource extends JsonResource
{
    public const FIELDS = ['id', 'status', 'total_cents', 'note', 'version', 'created_at', 'links'];

    public function toArray(Request $request): array
    {
        $data = [
            'id' => $this->public_id,
            'status' => $this->status,
            'total_cents' => $this->total_cents,
            'note' => $this->note,
            'version' => $this->version,
            'created_at' => $this->created_at?->toIso8601ZuluString(),
            // A little hypermedia: what the client may do next.
            'links' => array_filter([
                'self' => route('orders.show', $this->resource),
                'cancel' => $this->canMoveTo('cancelled') && $this->status !== 'cancelled'
                    ? route('orders.cancel', $this->resource) : null,
            ]),
        ];

        // Sparse fieldsets: ?fields=id,status (validated in the controller).
        $fields = $request->query('fields');

        return is_string($fields) ? Arr::only($data, explode(',', $fields)) : $data;
    }
}

Policy: someone else's order is a 404 via Response::denyAsNotFound(); writes need the orders:write Sanctum ability.

php
<?php

namespace App\Policies;

use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class OrderPolicy
{
    public function viewAny(User $user): bool
    {
        return true; // the query is scoped to the user's own orders
    }

    /** Someone else's order answers 404, not 403, so ids cannot be probed. */
    public function view(User $user, Order $order): Response
    {
        return $order->customer_id === $user->id
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function create(User $user): bool
    {
        return $user->tokenCan('orders:write');
    }

    public function update(User $user, Order $order): Response
    {
        return $this->view($user, $order)->allowed() && $user->tokenCan('orders:write')
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function delete(User $user, Order $order): Response
    {
        return $this->update($user, $order);
    }
}

Controller: cursorPaginate() with allow-listed filters and sorts, 201 + Location + ETag, conditional GET with isNotModified(), If-Match with a compare-and-set increment('version', 1, $changes), 204 on delete and 410 afterwards, cancellation as a sub-resource.

php
<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreOrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException;
use Symfony\Component\HttpKernel\Exception\PreconditionRequiredHttpException;

class OrderController extends Controller
{
    /** GET /api/orders?status=paid&sort=-created_at&fields=id,status&limit=25&cursor=... */
    public function index(Request $request): AnonymousResourceCollection
    {
        Gate::authorize('viewAny', Order::class);

        $q = $request->validate([
            'status' => ['sometimes', Rule::in(Order::STATUSES)],
            'sort' => ['sometimes', Rule::in(['created_at', '-created_at'])], // allow-list, never raw input
            'fields' => ['sometimes', 'string', function (string $attr, string $value, \Closure $fail) {
                if (array_diff(explode(',', $value), OrderResource::FIELDS) !== []) {
                    $fail('Unknown field in fields.');
                }
            }],
            'limit' => ['sometimes', 'integer', 'between:1,100'],
        ]);
        $dir = ($q['sort'] ?? '-created_at') === '-created_at' ? 'desc' : 'asc';

        // Keyset under the hood: WHERE (created_at, id) < (?, ?) ORDER BY created_at, id.
        // The id tie-breaker makes the order total, so no row is skipped or repeated.
        $orders = Order::query()
            ->where('customer_id', $request->user()->id)
            ->when($q['status'] ?? null, fn ($query, $status) => $query->where('status', $status))
            ->orderBy('created_at', $dir)
            ->orderBy('id', $dir)
            ->cursorPaginate($q['limit'] ?? 25)
            ->withQueryString();

        return OrderResource::collection($orders);
    }

    /** POST /api/orders (RequireIdempotencyKey runs first). */
    public function store(StoreOrderRequest $request): JsonResponse
    {
        $order = Order::create([...$request->validated(), 'customer_id' => $request->user()->id]);

        return $order->toResource(OrderResource::class)
            ->response()
            ->setStatusCode(201)
            ->header('Location', route('orders.show', $order))
            ->setEtag($order->etag());
    }

    /** GET /api/orders/{order}: ETag + If-None-Match gives 304. */
    public function show(Request $request, Order $order): JsonResponse
    {
        Gate::authorize('view', $order);

        if ($order->trashed()) {
            throw new GoneHttpException('This order was deleted.');
        }

        $response = $order->toResource(OrderResource::class)
            ->response()
            ->setEtag($order->etag())
            ->header('Cache-Control', 'private, no-cache');

        $response->isNotModified($request); // turns it into an empty 304 when the tag matches

        return $response;
    }

    /** PATCH /api/orders/{order} with application/merge-patch+json and If-Match. */
    public function update(UpdateOrderRequest $request, Order $order): JsonResponse
    {
        $expected = $this->versionFromIfMatch($request, $order);
        $changes = $request->validated();

        if (isset($changes['status']) && ! $order->canMoveTo($changes['status'])) {
            throw new ConflictHttpException("Cannot move from {$order->status} to {$changes['status']}.");
        }

        // Compare-and-set: UPDATE orders SET ..., version = version + 1
        // WHERE id = ? AND version = ?  -- 0 rows means someone else won.
        $affected = Order::query()
            ->whereKey($order->getKey())
            ->where('version', $expected)
            ->increment('version', 1, $changes);

        if ($affected === 0) {
            throw new PreconditionFailedHttpException('The order changed since you read it.');
        }

        $order->refresh();

        return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
    }

    /** DELETE /api/orders/{order}: 204, then 410 on later reads. */
    public function destroy(Request $request, Order $order): Response
    {
        Gate::authorize('delete', $order);

        if ($request->hasHeader('If-Match')) {
            $this->versionFromIfMatch($request, $order);
        }
        $order->delete();

        return response()->noContent();
    }

    /** POST /api/orders/{order}/cancellation: repeating it changes nothing. */
    public function cancel(Request $request, Order $order): JsonResponse
    {
        Gate::authorize('update', $order);

        if (! $order->canMoveTo('cancelled')) {
            throw new ConflictHttpException("A {$order->status} order cannot be cancelled.");
        }
        if ($order->status !== 'cancelled') {
            $order->forceFill(['status' => 'cancelled', 'version' => $order->version + 1])->save();
        }

        return $order->toResource(OrderResource::class)->response()->setEtag($order->etag());
    }

    /** 428 when If-Match is missing, 412 when it names another version. */
    private function versionFromIfMatch(Request $request, Order $order): int
    {
        $header = $request->header('If-Match');
        if ($header === null) {
            throw new PreconditionRequiredHttpException('Send the ETag you read in If-Match.');
        }
        $tag = trim($header);
        if ($tag !== '"'.$order->etag().'"') { // strong comparison: W/ tags never match
            throw new PreconditionFailedHttpException('The order changed since you read it.');
        }

        return $order->version;
    }
}

Idempotency-Key middleware with the table's primary key as the lock:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

/**
 * The Idempotency-Key API contract (IETF draft): 400 without a key, 409
 * while the first request with the key is still running, 422 when the key
 * is reused with another payload, otherwise replay the stored response.
 * The primary key (client_id, idempotency_key) is the lock. Storage design,
 * TTL sweeps and crash recovery: /system-design/api-idempotency.
 */
class RequireIdempotencyKey
{
    private const REPLAYED_HEADERS = ['Content-Type', 'Location', 'ETag'];

    public function handle(Request $request, Closure $next): Response
    {
        $key = trim((string) $request->header('Idempotency-Key'), " \t\"");
        if ($key === '' || strlen($key) > 255) {
            return $this->problem(400, 'idempotency-key-missing', 'Idempotency-Key is missing',
                'This operation requires an Idempotency-Key header (1 to 255 characters).');
        }

        $clientId = (string) ($request->user()?->getAuthIdentifier() ?? $request->ip());
        $fingerprint = hash('sha256', $request->method().' '.$request->path()."\n".$request->getContent());
        $where = ['client_id' => $clientId, 'idempotency_key' => $key];

        try {
            DB::table('idempotency_keys')->insert($where + [
                'fingerprint' => $fingerprint,
                'expires_at' => now()->addDay(),
                'created_at' => now(),
            ]);
        } catch (UniqueConstraintViolationException) {
            $row = DB::table('idempotency_keys')->where($where)->first();

            if ($row->fingerprint !== $fingerprint) {
                return $this->problem(422, 'idempotency-key-reused', 'Idempotency-Key is already used',
                    'The key was used with a different request payload.');
            }
            if ($row->status_code === null) {
                return $this->problem(409, 'idempotency-key-in-flight',
                    'A request is outstanding for this Idempotency-Key', null, ['Retry-After' => '1']);
            }

            return response($row->response_body, $row->status_code,
                json_decode($row->response_headers, true) + ['Idempotent-Replayed' => 'true']);
        }

        $response = $next($request);

        if ($response->getStatusCode() >= 400) {
            // Do not pin a failure to the key: the client may fix the request and retry.
            DB::table('idempotency_keys')->where($where)->delete();

            return $response;
        }

        $headers = [];
        foreach (self::REPLAYED_HEADERS as $name) {
            if ($response->headers->has($name)) {
                $headers[$name] = $response->headers->get($name);
            }
        }
        DB::table('idempotency_keys')->where($where)->update([
            'status_code' => $response->getStatusCode(),
            'response_headers' => json_encode($headers),
            'response_body' => $response->getContent(),
        ]);

        return $response;
    }

    private function problem(int $status, string $kind, string $title, ?string $detail, array $headers = []): Response
    {
        return response()->json(array_filter([
            'type' => "https://api.example.com/problems/{$kind}",
            'title' => $title,
            'status' => $status,
            'detail' => $detail,
        ]), $status, $headers + ['Content-Type' => 'application/problem+json']);
    }
}

Rate limiting: named limiters in AppServiceProvider, plus a small middleware that adds the IETF fields next to Laravel's X-RateLimit-*:

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Used by throttle:api ($middleware->throttleApi() in bootstrap/app.php).
        // Over the limit Laravel answers 429 with Retry-After; bootstrap/app.php
        // turns the ThrottleRequestsException into Problem Details.
        RateLimiter::for('api', function (Request $request) {
            return $request->user()
                ? Limit::perMinute(120)->by('user:'.$request->user()->id)
                : Limit::perMinute(20)->by('ip:'.$request->ip());
        });

        // Expensive endpoints get their own, smaller bucket.
        RateLimiter::for('exports', fn (Request $request) => Limit::perHour(10)->by('user:'.$request->user()?->id));
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Laravel's ThrottleRequests middleware emits X-RateLimit-Limit and
 * X-RateLimit-Remaining (plus Retry-After and X-RateLimit-Reset on 429).
 * This adds the IETF draft fields (draft-ietf-httpapi-ratelimit-headers-12)
 * next to them so standard clients can pace themselves. Register it
 * before throttling in the api group so it sees the throttle headers.
 */
class AddRateLimitFields
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $limit = $response->headers->get('X-RateLimit-Limit');
        $remaining = $response->headers->get('X-RateLimit-Remaining');

        if ($limit !== null && $remaining !== null) {
            $response->headers->set('RateLimit-Policy', "api;q={$limit};w=60");
            $retry = $response->headers->get('Retry-After');
            $response->headers->set('RateLimit', "api;a={$remaining}".($retry !== null ? ";w={$retry}" : ''));
        }

        return $response;
    }
}

Problem Details exception rendering for everything under api/*:

php
<?php

use App\Http\Middleware\AddRateLimitFields;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->throttleApi();                       // throttle:api on the api group
        $middleware->prependToGroup('api', AddRateLimitFields::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Every error under /api/* becomes RFC 9457 Problem Details. By the time
        // this runs Laravel has already mapped ModelNotFoundException to a 404
        // and AuthorizationException to a 403 HttpException.
        $exceptions->render(function (Throwable $e, Request $request) {
            if (! $request->is('api/*')) {
                return null; // keep the default HTML/JSON rendering elsewhere
            }

            [$status, $kind, $extra] = match (true) {
                $e instanceof ValidationException => [422, 'validation', ['errors' => collect($e->errors())
                    ->map(fn (array $messages, string $field) => [
                        'pointer' => '#/'.str_replace('.', '/', $field),
                        'detail' => $messages[0],
                    ])->values()->all()]],
                $e instanceof AuthenticationException => [401, 'unauthenticated', []],
                $e instanceof HttpExceptionInterface => [$e->getStatusCode(), 'http-'.$e->getStatusCode(), []],
                default => [500, 'internal', []],
            };

            $headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : [];
            if ($status === 401) {
                $headers['WWW-Authenticate'] = 'Bearer';
            }

            return response()->json([
                'type' => "https://api.example.com/problems/{$kind}",
                'title' => Response::$statusTexts[$status] ?? 'Error',
                'status' => $status,
                // Never leak exception messages from 5xx; 4xx messages are ours.
                'detail' => $status < 500 && $e->getMessage() !== '' ? $e->getMessage() : null,
                'instance' => '/'.$request->path(),
                ...$extra,
            ], $status, $headers + ['Content-Type' => 'application/problem+json', 'Cache-Control' => 'no-store']);
        });
    })->create();

Long-running export: 202 + Location, a queued job, 303 when done.

php
<?php

namespace App\Http\Controllers;

use App\Jobs\ExportOrders;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Long-running operation: POST answers 202 with a status resource;
 * the status resource answers 200 while running and 303 See Other to the
 * result when done.
 */
class OperationController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $request->validate(['format' => ['required', 'in:csv,jsonl']]);

        $id = (string) Str::uuid();
        DB::table('operations')->insert([
            'id' => $id,
            'user_id' => $request->user()->id,
            'status' => 'running',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        ExportOrders::dispatch($id, $request->user()->id, $request->input('format'));

        return response()
            ->json(['id' => $id, 'status' => 'running'], 202)
            ->header('Location', route('operations.show', $id))
            ->header('Retry-After', '2');
    }

    public function show(Request $request, string $operation): JsonResponse|RedirectResponse
    {
        $op = DB::table('operations')
            ->where('id', $operation)
            ->where('user_id', $request->user()->id)
            ->first();
        abort_if($op === null, 404);

        if ($op->status === 'succeeded') {
            return redirect()->to($op->result_url, 303);
        }

        return response()
            ->json(['id' => $op->id, 'status' => $op->status, 'error' => $op->error], 200)
            ->header('Retry-After', '2');
    }
}
php
<?php

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Throwable;

class ExportOrders implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $operationId,
        public int $userId,
        public string $format,
    ) {}

    public function handle(): void
    {
        $path = "exports/{$this->operationId}.{$this->format}";
        $lines = [];
        Order::query()->where('customer_id', $this->userId)->orderBy('id')
            ->lazyById(1000)
            ->each(function (Order $o) use (&$lines) {
                $lines[] = $this->format === 'csv'
                    ? "{$o->public_id},{$o->status},{$o->total_cents}"
                    : json_encode(['id' => $o->public_id, 'status' => $o->status, 'total_cents' => $o->total_cents]);
            });
        Storage::put($path, implode("\n", $lines));
        // temporaryUrl() needs a disk that supports it (S3, or local with 'serve' => true).

        DB::table('operations')->where('id', $this->operationId)->update([
            'status' => 'succeeded',
            'result_url' => Storage::temporaryUrl($path, now()->addHour()),
            'updated_at' => now(),
        ]);
    }

    public function failed(?Throwable $e): void
    {
        DB::table('operations')->where('id', $this->operationId)->update([
            'status' => 'failed',
            'error' => 'export_failed',
            'updated_at' => now(),
        ]);
    }
}

Schema for orders (version column, keyset indexes, soft deletes), idempotency keys and operations:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('public_id', 40)->unique();       // what URIs expose
            $table->foreignId('customer_id')->constrained('users');
            $table->string('status', 16)->default('pending');
            $table->unsignedBigInteger('total_cents');
            $table->string('note', 500)->nullable();
            $table->unsignedInteger('version')->default(1);  // ETag source, optimistic lock
            $table->timestamps();
            $table->softDeletes();                           // deleted rows answer 410
            // Keyset pagination: filter, then the sort key plus a unique tie-breaker.
            $table->index(['customer_id', 'status', 'created_at', 'id']);
            $table->index(['customer_id', 'created_at', 'id']);
        });

        Schema::create('idempotency_keys', function (Blueprint $table) {
            $table->string('client_id', 64);
            $table->string('idempotency_key', 255);
            $table->char('fingerprint', 64);
            $table->unsignedSmallInteger('status_code')->nullable(); // null = still running
            $table->json('response_headers')->nullable();
            $table->longText('response_body')->nullable();
            $table->timestamp('expires_at')->index();
            $table->timestamp('created_at');
            $table->primary(['client_id', 'idempotency_key']);        // the lock
        });

        Schema::create('operations', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('user_id')->constrained();
            $table->string('status', 16);                             // running | succeeded | failed
            $table->text('result_url')->nullable();
            $table->string('error', 64)->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('operations');
        Schema::dropIfExists('idempotency_keys');
        Schema::dropIfExists('orders');
    }
};

Feature tests for 201/replay/422, Problem Details, 428/412 and 404/410:

php
<?php

namespace Tests\Feature;

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class OrderApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_create_is_201_with_location_and_replays_on_retry(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['orders:write']);
        $headers = ['Idempotency-Key' => '"k-1"'];

        $first = $this->postJson('/api/orders', ['total_cents' => 4999], $headers)
            ->assertCreated()
            ->assertHeader('Location')
            ->assertHeader('ETag');

        $this->postJson('/api/orders', ['total_cents' => 4999], $headers)
            ->assertCreated()
            ->assertHeader('Idempotent-Replayed', 'true')
            ->assertJsonPath('data.id', $first->json('data.id'));

        $this->postJson('/api/orders', ['total_cents' => 1], $headers)->assertStatus(422);
        $this->assertSame(1, Order::count());
    }

    public function test_validation_errors_are_problem_details(): void
    {
        Sanctum::actingAs(User::factory()->create(), ['orders:write']);

        $this->postJson('/api/orders', ['total_cents' => 0], ['Idempotency-Key' => '"k-2"'])
            ->assertStatus(422)
            ->assertHeader('Content-Type', 'application/problem+json')
            ->assertJsonPath('errors.0.pointer', '#/total_cents');
    }

    public function test_patch_needs_if_match_and_rejects_a_stale_etag(): void
    {
        $user = User::factory()->create();
        Sanctum::actingAs($user, ['orders:write']);
        $order = Order::create(['customer_id' => $user->id, 'total_cents' => 100]);
        $uri = "/api/orders/{$order->public_id}";
        $merge = ['CONTENT_TYPE' => 'application/merge-patch+json'];
        $body = json_encode(['status' => 'paid']);

        $this->call('PATCH', $uri, [], [], [], $merge, $body)->assertStatus(428);

        $this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
            ->assertOk()
            ->assertJsonPath('data.version', 2);

        // Same old ETag again: someone (we) already moved it to version 2.
        $this->call('PATCH', $uri, [], [], [], $merge + ['HTTP_IF_MATCH' => '"'.$order->etag().'"'], $body)
            ->assertStatus(412);
    }

    public function test_someone_elses_order_is_404_and_deleted_is_410(): void
    {
        $owner = User::factory()->create();
        $order = Order::create(['customer_id' => $owner->id, 'total_cents' => 100]);

        Sanctum::actingAs(User::factory()->create(), ['orders:write']);
        $this->getJson("/api/orders/{$order->public_id}")->assertNotFound();

        Sanctum::actingAs($owner, ['orders:write']);
        $this->deleteJson("/api/orders/{$order->public_id}")->assertNoContent();
        $this->getJson("/api/orders/{$order->public_id}")->assertStatus(410);
    }
}

The Laravel angle ​

Laravel 13 featureUseNote
Route::apiResource() / apiResources()Five REST routes per resourceExcludes create and edit
->shallow(), ->scoped(), scopeBindings()Nested resourcesChild bindings scoped to the parent
->middlewareFor(), ->withTrashed()Per-action middleware, soft-deleted bindingResource route registration
Route model binding, getRouteKeyName(){order} by public_idMissing model becomes 404
Form Request (make:request)authorize() 403, rules() 422$request->validated() only
API Resource (JsonResource, toResource())Representation layerwhenLoaded() avoids N+1
JsonApiResourceJSON:API with sparse fieldsets and includesSets application/vnd.api+json
Policies, Gate::authorize(), Response::denyAsNotFound()Object-level authorizationAuthorizationException becomes 403
cursorPaginate(), simplePaginate(), paginate()Keyset vs offsetCursor needs orderBy
RateLimiter::for(), Limit::perMinute()->by(), throttle:Rate limiting429 automatic; $middleware->throttleApi()
cache.headers middlewareCache-Control and ETagetag directive adds 304 handling
$exceptions->render(), shouldRenderJsonWhen()Problem DetailsRuns after Laravel maps model-not-found to 404
response()->noContent()204—

Solving the classic problems ​

Double order after a timeout ​

SolutionHowAdvantageCost
Idempotency-KeyClient key per operation, server replaysExact original response, covers side effectsA store with TTL
Client-chosen id + PUTPUT /orders/{uuid}Idempotent by methodClients must generate ids
Natural unique constraintUNIQUE(customer_id, cart_id)No extra tableRetry gets an error, not the original result

Preferred: Idempotency-Key (Go, Laravel); storage mechanics in API Idempotency.

Lost update between two editors ​

SolutionHowAdvantageCost
ETag + If-Match412 on stale writes, 428 withoutStandard, works through proxiesClients must keep the ETag
Version in body (Kubernetes, AIP-154)version/etag fieldWorks in batch bodiesNot visible to HTTP tooling
Pessimistic lock endpointPOST /docs/7/lockSimple for humansLock expiry and abandonment
sql
-- What If-Match becomes in the database (the Laravel increment() call generates this shape)
UPDATE orders
SET status = 'paid', version = version + 1, updated_at = now()
WHERE id = 7 AND version = 1;     -- 0 rows affected -> 412 Precondition Failed

Pages that skip or repeat rows ​

SolutionHowAdvantageCost
Keyset cursor(sort key, id) in an opaque cursorStable, fast at any depthNo random page jumps
Snapshot tokenCursor pins a snapshot time (as_of)Consistent viewNeeds history or MVCC reads
Offset with a stable sortORDER BY created_at, idPage numbersStill shifts under writes, slow when deep

Errors nobody can handle ​

SolutionHowAdvantageCost
Problem Details everywhereOne helper per stack, gateway includedOne parser for clientsMigrating old shapes
Stable type URIsDocumented catalogueClients switch on itMust not change
Field pointerserrors[].pointerForms map errors to fieldsExtension to document

A slow endpoint that times out at the gateway ​

SolutionHowAdvantageCost
202 + status resourceQueue, poll, 303 to resultSurvives client and gateway timeoutsJob store, cleanup
Webhook on completionCallback with signatureNo pollingClient must expose an endpoint
Streaming responseChunked or SSEProgress visibleConnection held open

Clients hammering the API ​

SolutionHowAdvantageCost
RateLimit + 429 + Retry-AfterPer-client quota, visible headersClients self-paceShared counter store
Caching headersETag, max-ageRemoves load entirelyStaleness
Bulk endpointOne request for many itemsFewer round tripsPartial-failure design

Choosing ​

SituationRecommendationExtra techniqueReason
Public API, many unknown clientsREST level 2, OpenAPI 3.1, Problem DetailsStyle guide + lint, cursor pagesTooling, caches and SDKs work
Internal service-to-service, high volumegRPC or RESTSee gRPCBinary contracts, streaming
UI aggregating many entities per screenREST + BFF, or GraphQLSee GraphQLAvoid over/under-fetching
Payments, orders, anything with moneyPOST + Idempotency-Key, If-Match on updatesOutbox for events (Outbox)Retries are certain
Collaborative editsPATCH + If-Match, 412JSON Patch test for field-level checksLost updates are silent otherwise
Large or slow work202 + status resourceWebhook, presigned result URLNo request should run for minutes
Lists that growCursor (keyset) paginationFilters inside the cursorStable and O(page)
Admin table with page numbers, small dataOffset paginationTotal countSimpler UI
Public read-mostly dataCache headers + CDNs-maxage, stale-while-revalidateMost requests never reach you
Clients with long lifetimes and changing workflowsAdd hypermedia links (level 3 parts)State-dependent action linksServer can evolve without client releases

In architecture: from a single process to a distributed system ​

The same API contract has to survive more and more machines behind it. What changes is where state lives, who can answer a request, and which guarantees still hold.

Monolith: one process, one database ​

A Laravel or Go monolith exposes /api/orders straight from its database. ETags come from a version column, idempotency keys from a table in the same database (so "claim key, insert order, save response" can be one transaction), cursors from an index. The simplest correct setup: apiResource, Form Requests, Policies, cursorPaginate(), Problem Details rendering, throttle:api. Everything on this page fits in one process.

Modular monolith: boundaries inside one deployable ​

Orders, Billing and Catalog are modules with their own tables. The public API is still one, but each module owns its resources (/orders, /invoices, /products) and its OpenAPI fragment; a shared middleware stack provides Problem Details, rate limits and idempotency. Rule: one module never writes another module's table through the API layer; cross-module actions are internal calls or events, not HTTP to yourself.

Microservices: every arrow is an API ​

text
     Mobile app        API gateway (Envoy/Kong)       orders-svc                billing-svc
1    POST /orders  ->  auth, RateLimit, 429           -> POST /orders  Idempotency-Key k1
2                                                      claim k1, insert order, outbox OrderPlaced
3                                                      201 Location /orders/ord_7
4                                                      relay -> broker                 consumes, charges
5    GET /orders/ord_7 -> gateway -> orders-svc -> 200 {"status":"paid", "links":{...}}

What survives the boundary: status codes, Problem Details, the Idempotency-Key (forward it, or derive child keys such as k1:charge), ETags per service. What does not: a transaction spanning orders and billing, so cross-service consistency comes from sagas and the outbox, and the API shows it honestly (status: pending, 202, or a status link). Gateways and BFFs are covered in API Gateway, BFF & Service Mesh.

Distributed data: replicas, caches, regions ​

  • Read replicas: a client creates an order (201) then immediately GETs it from a lagging replica and gets 404. Fixes: read-your-writes by routing reads after a write to the primary for a few seconds, or return the full representation in the 201 so the client does not need to read. See Replication Topologies.
  • Caches and CDNs: private vs public, Vary, and ETags that come from the version column so every node computes the same tag. A weak spot: ETags generated from an in-process hash differ between nodes and break 304s.
  • Idempotency across regions: a retry may land in another region; the key store must be global or keys must be region-affine. Details in API Idempotency.
  • Rate limits across instances: a per-process counter multiplies the limit by the instance count; use Redis or the gateway (Rate Limiting).

Scaling path: 1x, 10x, 100x ​

LoadWhat changes in the APIWhat changes behind it
1x (hundreds of rps)Contract-first, Problem Details, cursor pages, Idempotency-KeyOne app, one database
10x (thousands of rps)Cache headers on reads, RateLimit headers, bulk endpoints for heavy clientsCDN, Redis for limits and keys, read replicas, more stateless app nodes
100x (tens of thousands of rps and more)202 for anything heavy, webhooks instead of polling, stricter limits per tier, versioned contracts per client segmentGateway in front, per-service APIs, sharded data (Sharding), regional deployments

Lab: the Go service with curl ​

The Go server is a single process with an in-memory store, so this lab was run on this machine with go run ./cmd/server (Go 1.27 toolchain, module directive go 1.24); the outputs below are from that run, with Date headers removed. The Laravel steps at the end are expected, not run.

Setup

bash
cd docs/snippets/system-design/rest-api-design/go
go test ./...                 # ok  academy/rest-api-design/orders
go run ./cmd/server           # listening on 127.0.0.1:8080

1. Create, then retry with the same key (replay), then reuse the key with another body (422).

text
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' \
    -H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' -d '{"customer":"c-42","total_cents":4999}'
HTTP/1.1 201 Created
Content-Type: application/json
Etag: "ord_000001-v1"
Location: /orders/ord_000001
Ratelimit: default;a=99;w=60
Ratelimit-Policy: default;q=100;w=60

{"id":"ord_000001","customer":"c-42","status":"pending","total_cents":4999,"note":null,"version":1,...}

$ (same command again)
HTTP/1.1 201 Created
Etag: "ord_000001-v1"
Idempotent-Replayed: true
Location: /orders/ord_000001

$ (same key, "total_cents":1)
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/idempotency-key-reused","title":"Idempotency-Key is already used","status":422,...}

Go's status text is still "Unprocessable Entity"; RFC 9110 renamed 422 to "Unprocessable Content". Clients must read the number, not the text.

2. Conditional GET and the lost-update protocol.

text
$ curl -si localhost:8080/orders/ord_000001 -H 'If-None-Match: "ord_000001-v1"'
HTTP/1.1 304 Not Modified
Cache-Control: private, no-cache
Etag: "ord_000001-v1"

$ curl -si -X PATCH localhost:8080/orders/ord_000001 -H 'Content-Type: application/merge-patch+json' -d '{"status":"paid"}'
HTTP/1.1 428 Precondition Required
Accept-Patch: application/merge-patch+json, application/json-patch+json
{"type":"https://api.example.com/problems/precondition-required","title":"If-Match required",...}

$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"status":"paid"}'
HTTP/1.1 200 OK
Etag: "ord_000001-v2"

$ curl -si -X PATCH ... -H 'If-Match: "ord_000001-v1"' -d '{"customer":"bob"}'
HTTP/1.1 412 Precondition Failed
{"type":"https://api.example.com/problems/stale-etag","title":"Precondition failed","status":412,
 "detail":"The order changed since you read it. GET it again, reapply your change, retry with the new ETag.",...}

3. Method not allowed is free with the Go 1.22 mux.

text
$ curl -si -X PUT localhost:8080/orders/ord_000001 -d '{}'
HTTP/1.1 405 Method Not Allowed
Allow: DELETE, GET, HEAD, PATCH
Content-Type: text/plain; charset=utf-8

4. Cursor pages with sparse fieldsets (after creating five orders).

text
$ curl -si 'localhost:8080/orders?limit=2&fields=id,status'
HTTP/1.1 200 OK
Link: </orders?cursor=eyJhIjoib3JkXzAwMDAwMiJ9&fields=id%2Cstatus&limit=2>; rel="next"
{"data":[{"id":"ord_000001","status":"pending"},{"id":"ord_000002","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwMiJ9"}

$ curl -si 'localhost:8080/orders?limit=2&fields=id,status&cursor=eyJhIjoib3JkXzAwMDAwMiJ9'
{"data":[{"id":"ord_000003","status":"pending"},{"id":"ord_000004","status":"pending"}],"next_cursor":"eyJhIjoib3JkXzAwMDAwNCJ9"}

Decode the cursor (echo eyJhIjoib3JkXzAwMDAwMiJ9 | base64 -d prints {"a":"ord_000002"}): it is the last id, which is why it is stable. Real APIs sign or encrypt it so clients treat it as opaque.

5. Long-running export: 202, then 200 while running, then 303.

text
$ curl -si -X POST 'localhost:8080/exports?format=csv' -H 'Idempotency-Key: "e1"'
HTTP/1.1 202 Accepted
Location: /operations/op_1
Retry-After: 1
{"id":"op_1","status":"running"}

$ curl -si localhost:8080/operations/op_1
HTTP/1.1 200 OK
Retry-After: 1
{"id":"op_1","status":"running"}

$ curl -si localhost:8080/operations/op_1     # 300 ms later
HTTP/1.1 303 See Other
Location: /exports/exp_1

6. Delete twice, and the error contract.

text
$ curl -si -X DELETE localhost:8080/orders/ord_000005     ->  HTTP/1.1 204 No Content
$ curl -si -X DELETE localhost:8080/orders/ord_000005     ->  HTTP/1.1 410 Gone (application/problem+json)
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 400 Bad Request
{"type":"https://api.example.com/problems/idempotency-key-missing","title":"Idempotency-Key is missing",...}
$ curl -si -X POST localhost:8080/orders -H 'Content-Type: application/json' -H 'Idempotency-Key: "v1"' \
    -d '{"customer":"","total_cents":0}'
HTTP/1.1 422 Unprocessable Entity
{"type":".../validation","title":"Validation failed","status":422,"instance":"/orders",
 "errors":[{"pointer":"#/customer","detail":"is required"},{"pointer":"#/total_cents","detail":"must be greater than 0"}]}

7. Laravel (expected, not run). In a Laravel 13 app with Sanctum, the snippets copied in and php artisan migrate:

text
$ php artisan route:list --path=api
  GET|HEAD   api/orders ................. orders.index   › OrderController@index
  POST       api/orders ................. orders.store   › OrderController@store
  GET|HEAD   api/orders/{order} ......... orders.show    › OrderController@show
  PUT|PATCH  api/orders/{order} ......... orders.update  › OrderController@update
  DELETE     api/orders/{order} ......... orders.destroy › OrderController@destroy
  POST       api/orders/{order}/cancellation  orders.cancel
  POST       api/exports ................ exports.store
  GET|HEAD   api/operations/{operation} . operations.show
$ php artisan test --filter=OrderApiTest
  PASS  Tests\Feature\OrderApiTest   (4 tests)

Note that apiResource registers both PUT and PATCH for update; this controller treats both as merge patch. If you want PUT to mean full replacement, register update for PATCH only and add a separate replace action.

Common misconceptions ​

BeliefReality
REST means JSON and nice URLsREST is six constraints; most JSON APIs are Richardson level 2
Stateless means no databaseIt forbids server-side session state between requests, not resource state
PUT is update, POST is createPUT stores at a client-known URI (and can create); POST lets the server decide
Idempotent means identical responsesSame intended effect; a second DELETE may get 404/410
PATCH with a partial JSON object is standardThe standard formats are application/merge-patch+json and application/json-patch+json
401 and 403 are interchangeable401 = who are you (with WWW-Authenticate); 403 = known, not allowed
409 is the code for a stale ETagStale If-Match is 412; 409 is a state conflict
no-cache forbids cachingIt means revalidate before reuse; no-store forbids storing
202 means successIt means accepted; the outcome lives in the status resource
A unique constraint makes POST idempotentIt blocks duplicates but does not replay the original response or cover side effects
Cursor pagination is just another page numberIt is a bookmark from the sort key; stable under writes and cheap at depth
Level 3 hypermedia is required to be usefulLevel 2 gives caching, retries and tooling; add links where clients branch on state
X-RateLimit-* is a standardConvention only; the IETF draft defines RateLimit-Policy and RateLimit

Cheat sheet ​

TopicRemember
ConstraintsClient-server, stateless, cacheable, uniform interface (4 parts), layered, code on demand (optional)
Safe methodsGET, HEAD, OPTIONS, TRACE
Idempotent methodsSafe ones + PUT + DELETE; POST and PATCH are not
CreatePOST to the collection, 201 + Location + ETag; PUT when the client chooses the id
Partial updatePATCH with application/merge-patch+json (null deletes) or JSON Patch (test for preconditions)
ConcurrencyETag on read, If-Match on write, 412 stale, 428 missing
Retry-safe POSTIdempotency-Key: "uuid"; 400 missing, 409 in flight, 422 reused, replay otherwise
Validation vs syntax422 vs 400; 415 wrong media type
Errorsapplication/problem+json with type, title, status, detail, instance
PaginationOpaque cursor from (sort key, id), Link: rel="next", cap the limit
Query designAllow-listed filters and sorts, fields= for sparse fieldsets, indexes per combination
Long work202 + Location to a status resource, Retry-After, 303 to the result
Rate limits429 + Retry-After; RateLimit-Policy and RateLimit (draft)
Cachingprivate, no-cache + ETag for user data; public, s-maxage for shared data; no-store for errors
ContractOpenAPI 3.1 first, lint (Spectral), diff in CI, generate clients
Style guideAdopt Google AIP, Microsoft or Zalando; write down your exceptions

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Name Fielding's six constraints and the one that is optional. Must-know ​

Answer

Answer: Client-server, stateless, cacheable, uniform interface, layered system, code on demand; code on demand is optional. See Constraints.

2 — A server keeps a user's search results in process memory and returns ?page=2 from them. Which constraint does that break, and what operational symptom will you see? Must-know ​

Answer

Answer: Stateless: request 2 depends on context stored on the server that handled request 1. Symptoms: sticky sessions required, wrong or missing pages after a deploy or failover, uneven load. Put the position in a cursor instead.

3 — Is DELETE /orders/7 still idempotent if the second call returns 410 instead of 204? Why? Must-know ​

Answer

Answer: Yes. Idempotency is about the intended effect on the server (the order is deleted), not about identical responses. See Methods.

4 — A client sends PATCH {"note": null}. What does that mean under JSON Merge Patch, and how would you express "change status only if it is still pending"? Important ​

Answer

Answer: Merge Patch: remove note. The conditional change needs JSON Patch: [{"op":"test","path":"/status","value":"pending"},{"op":"replace","path":"/status","value":"paid"}], plus If-Match for the whole resource. See PATCH formats.

5 — Pick the status code: (a) valid JSON but total_cents is negative; (b) the body is text/plain; (c) If-Match is stale; (d) no If-Match but the server requires it; (e) shipped order moved back to pending. Must-know ​

Answer

Answer: (a) 422, (b) 415, (c) 412, (d) 428, (e) 409. See Status codes.

6 — Why does offset pagination show duplicates under concurrent inserts, and what does a keyset cursor contain? Must-know ​

Answer

Answer: New rows shift every later offset, so the next page starts one row earlier and repeats one. A keyset cursor holds the last row's sort key and unique id (plus filters), and the next query is WHERE (created_at, id) < (...). See Pagination.

7 — Your POST /payments timed out. The client retries with the same Idempotency-Key while the first request is still running. What should it get, and what should it get after the first finishes? Must-know ​

Answer

Answer: 409 (request outstanding), ideally with Retry-After; after completion, a replay of the original response (for example the same 201 body). If the payload differs, 422. See Idempotency keys.

8 — Why do most public APIs stop at Richardson level 2, and what is a cheap step toward level 3? Good to know ​

Answer

Answer: Clients are generated from OpenAPI and hard-code URIs, JSON has no single link standard, and the payoff needs clients that follow links. Cheap step: Link: rel="next", Location, and state-dependent action links such as cancel. See Hypermedia.

9 — What is the difference between Cache-Control: no-cache and no-store, and which do you use for GET /me? Must-know ​

Answer

Answer: no-cache allows storing but requires revalidation; no-store forbids storing. For GET /me: private, no-cache with an ETag (or no-store if it contains secrets). See Caching.

10 — An export takes 4 minutes. Design the HTTP exchange. Must-know ​

Answer

Answer: POST /exports with an Idempotency-Key → 202 Accepted, Location: /operations/{id}, Retry-After; poll GET /operations/{id} → 200 running → 303 See Other to the result (or succeeded with a link); optionally a webhook. See Long-running operations.

11 — Name three things a contract-first OpenAPI workflow catches that code-first does not. Important ​

Answer

Answer: Accidental breaking changes (CI diff), style-guide violations before code exists (lint), and missing error responses or headers in review; it also lets frontend work start against a mock. See OpenAPI.

12 — User 42 requests /orders/ord_8, which belongs to user 7. 403 or 404, and how does Laravel express it? Must-know ​

Answer

Answer: Usually 404, so ids cannot be probed for existence; in Laravel a policy returns Response::denyAsNotFound(). See Security basics.

Glossary ​

TermMeaning
RESTRepresentational State Transfer, Fielding's architectural style: six constraints
Fielding constraintsClient-server, stateless, cacheable, uniform interface, layered system, code on demand
StatelessEach request carries all information needed; no server-side session context
CacheableResponses label themselves as reusable or not
Uniform interfaceSame methods, codes and media types for all resources: identification, representations, self-descriptive messages, HATEOAS
Layered systemComponents see only the adjacent layer; enables proxies, CDNs, gateways
Code on demandOptional constraint: server sends executable code
HATEOASHypermedia as the engine of application state: clients follow links
Richardson maturity modelLevels 0 (tunnel), 1 (resources), 2 (verbs and codes), 3 (hypermedia)
ResourceAnything that can be named and has a URI
CollectionResource that lists and creates members, e.g. /orders
Sub-resourceResource reachable only through its parent, e.g. /orders/7/items
URI designNaming rules: plural nouns, no verbs, opaque ids, shallow nesting
RepresentationResource state in a media type
Media typetype/subtype label such as application/json, application/problem+json
Content negotiationServer chooses the representation using Accept and friends; Vary records it
Safe methodRead-only semantics: GET, HEAD, OPTIONS, TRACE
Idempotent methodRepeating has the same intended effect: safe methods, PUT, DELETE
GET / HEAD / OPTIONSRead; read headers only; ask for capabilities
POST / PUT / PATCH / DELETEProcess or create; replace at URI; partial change; remove
JSON PatchRFC 6902 list of operations (test, add, remove, replace, move, copy)
JSON Merge PatchRFC 7396 partial document; null removes a member
Location headerURI of a created resource or a status monitor
Problem DetailsRFC 9457 error format: type, title, status, detail, instance
RFC 9457The 2023 Problem Details RFC that obsoletes RFC 7807
Offset paginationSkip N rows; simple, unstable under writes, slow when deep
Keyset paginationContinue after the last sort key and id; stable and fast
CursorOpaque token encoding the keyset position and filters
Filtering / sortingAllow-listed query parameters that narrow and order a collection
Sparse fieldsetsClient chooses returned fields (fields=id,status)
ETagOpaque validator of a representation; strong or weak
If-MatchWrite only if the current ETag matches; else 412
If-None-MatchGET: 304 if it matches; PUT with *: create only if absent
Optimistic concurrencyDetect conflicts at write time with a version, instead of locking at read time
Idempotency key / Idempotency-KeyClient-chosen unique key that lets the server replay the first result of a POST
Idempotency fingerprintHash of the request used to detect a key reused with another payload
Retry-AfterSeconds (or a date) to wait before retrying (429, 503, 202 polling)
RateLimit headersIETF draft RateLimit-Policy (quota) and RateLimit (available) fields
Bulk endpointOne request carrying many items; atomic or with per-item results
Long-running operationWork accepted with 202 and tracked through a status resource
OpenAPIMachine-readable HTTP API description; 3.1 aligns with JSON Schema 2020-12
Contract-firstWrite and review the API contract before the implementation
CodegenGenerating clients, stubs and mocks from the contract
API style guideOrganisation-wide normative rules for APIs, e.g. Google AIP
Google AIPGoogle's API Improvement Proposals (google.aip.dev)
apiResourceLaravel route registration for index, store, show, update, destroy
API ResourceLaravel JsonResource class that shapes a model into a representation
Form RequestLaravel request class with authorize() (403) and rules() (422)
Route model bindingLaravel resolving {order} into a model, 404 if missing
PolicyLaravel class holding per-model authorization rules

References ​

Built by Morteza Negahi