BE·45
HTTP API Design
Designing HTTP APIs that last. Covers REST constraints and resource modelling, method semantics (safe and idempotent), status codes and headers, content negotiation, pagination (offset, cursor, keyset), filtering and sorting, versioning, idempotency keys and safe retries, conditional requests with ETags, HATEOAS, JSON Patch and Merge Patch, RFC 9457 Problem Details, rate-limit headers, and backward and forward compatibility. Shown with Spring, Go, Rust, ASP.NET and FastAPI examples, and compared with gRPC, GraphQL and JSON-RPC.
Start here: designing an API people can rely on
An API is a promise
Chapter 44 built a working service. This chapter is about its interface: the URLs, methods, status codes, headers and JSON shapes that other teams, mobile apps and partners will code against. Once a mobile app version that calls your API is installed on a million phones, you can't change the API without breaking them, so the design deserves more care than the implementation behind it. Most public APIs follow REST conventions: model the domain as resources (dishes, orders) at stable URLs, and use HTTP's own methods, status codes and headers for what they already mean, instead of inventing your own.
| Action | Method and URL | Success | Notes |
|---|---|---|---|
| List or search | GET /v1/dishes?category=drinks&limit=20 |
200 | Paginated, filtered with query parameters |
| Read one | GET /v1/dishes/42 |
200 (or 304) | Returns an ETag version tag |
| Create | POST /v1/dishes |
201 + Location |
Retry-safe with Idempotency-Key |
| Replace / partly update | PUT / PATCH /v1/dishes/42 |
200 | Guarded by If-Match |
| Delete | DELETE /v1/dishes/42 |
204 | Idempotent |
Nouns in URLs, plural collections, ids in paths, filters in query strings, and the version (/v1) somewhere stable. The program below implements all of it with the JDK's HttpServer so you can see each mechanism; frameworks provide the same through annotations.
Collections: filter and paginate
$ curl 'localhost:8092/v1/dishes?limit=3'
{"items":[{"id":1,"name":"Masala dosa","category":"breakfast","price":9000},{"id":2,"name":"Idli",…},{"id":3,"name":"Vada",…}],
"next":"/v1/dishes?limit=3&after=3"}
$ curl 'localhost:8092/v1/dishes?limit=3&after=3'
{"items":[{"id":4,"name":"Thali",…},{"id":5,"name":"Biryani",…},{"id":6,"name":"Filter coffee",…}],"next":"/v1/dishes?limit=3&after=6"}
$ curl 'localhost:8092/v1/dishes?category=drinks'
{"items":[{"id":6,"name":"Filter coffee","category":"drinks","price":3000},{"id":7,"name":"Lassi","category":"drinks","price":6000}]}
Never return an unbounded list: the server caps limit (here at 100). The response wraps items in an object, which leaves room for metadata like the next link; a bare JSON array can't grow. And the next page is requested with a cursor ("after id 3") rather than a page number: the lab shows that cursor pagination stays fast on page 50,000 (where OFFSET took 100 ms) and doesn't repeat items when new rows arrive between requests.
Reading with versions: ETags
$ curl -i localhost:8092/v1/dishes/1
HTTP/1.1 200 OK
Etag: "v1"
{"id":1,"name":"Masala dosa","category":"breakfast","price":9000}
$ curl -i localhost:8092/v1/dishes/1 -H 'If-None-Match: "v1"'
HTTP/1.1 304 Not Modified
Etag: "v1"
An ETag is a version tag for a representation. A client that already has version v1 asks "send it only if it changed" (If-None-Match), and the server answers 304 Not Modified with no body: same correctness, almost no bytes. Browsers and CDNs do this automatically (Volume 2 chapter 19).
Writing safely: lost updates and retries
Two staff members open the same dish, both edit the price, both save: whoever saves second silently overwrites the first. ETags prevent this lost update when the client sends back the version it read with If-Match:
$ curl -X PATCH localhost:8092/v1/dishes/1 -d '{"price":9500}'
HTTP/1.1 428 {"title":"Precondition Required","detail":"send If-Match with the ETag you last read"}
$ curl -X PATCH localhost:8092/v1/dishes/1 -H 'If-Match: "v1"' -d '{"price":9500}'
HTTP/1.1 200 OK
Etag: "v2" {"id":1,…,"price":9500}
$ curl -X PATCH localhost:8092/v1/dishes/1 -H 'If-Match: "v1"' -d '{"price":8000}' ← the second editor, holding a stale version
HTTP/1.1 412 Precondition Failed {"title":"Precondition Failed","detail":"dish changed since you read it; current version v2"}
The second editor gets 412 and must reload, instead of destroying the first edit. This is optimistic concurrency, the same idea as a version column in the database (chapter 49).
Networks fail mid-request: a client sends POST /orders, the connection drops, and it can't know whether the order was created. Retrying might create a duplicate order and charge twice. GET, PUT and DELETE are idempotent (doing them twice has the same effect as once), so they're safe to retry; POST isn't. The fix is an idempotency key: the client generates a unique key per logical operation and sends it on every retry, and the server remembers the result:
$ curl -X POST localhost:8092/v1/dishes -H 'Idempotency-Key: 7c1e' -d '{"name":"Upma","category":"breakfast","price":4500}'
HTTP/1.1 201 Created
Location: /v1/dishes/8 {"id":8,"name":"Upma",…}
$ curl -X POST localhost:8092/v1/dishes -H 'Idempotency-Key: 7c1e' -d '{…same…}' ← a retry
HTTP/1.1 201 Created
Idempotent-replayed: true {"id":8,"name":"Upma",…} ← the same dish, not a second one
Stripe, Adyen, Razorpay and most payment APIs work this way, and an IETF draft standardises the Idempotency-Key header.
Errors and the rest
$ curl -X DELETE localhost:8092/v1/dishes/8 → HTTP/1.1 204 No Content
$ curl -X PUT localhost:8092/v1/dishes/1 → HTTP/1.1 405 Method Not Allowed
Allow: GET, PATCH, DELETE
Use the status code that already means what happened (chapter 44's Problem Details format for the body): 400 malformed, 401 not authenticated, 403 not allowed, 404 missing, 405 wrong method (with Allow), 409 conflict with current state, 412/428 precondition, 422 invalid fields, 429 rate limited (with Retry-After), 500 your bug, 503 overloaded or down. And plan for change from day one: add fields freely (clients must ignore unknown ones), never rename or remove a field or change its meaning within a version, and publish a machine-readable description (OpenAPI) from which clients and documentation are generated.
How deep to go in API design
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Map operations to resources, methods and status codes |
| L2 | Design pagination, filtering, errors, ETags and idempotent creates; write an OpenAPI description |
| L3 | Explain HTTP semantics (safety, idempotency, caching, conditional requests), versioning strategies, and when GraphQL, gRPC, webhooks or event APIs fit better |
| L4 | Diagnose chatty APIs, deep-page slowness, duplicate creates, lost updates and breaking changes |
| L5 | Set API guidelines, review processes and deprecation policies for a team |
| L6 | Run API governance across an organisation (style guides, linting, compatibility checks, developer portals) |
REST and resources
What REST actually is
REST (Representational State Transfer, Roy Fielding's 2000 dissertation) is an architectural style defined by constraints:
- Client–server: separate UI concerns from data storage.
- Stateless: each request carries everything needed to process it. No server-side session state between requests (authentication tokens travel with every request). This enables horizontal scaling.
- Cacheable: responses declare whether and how long they can be cached.
- Uniform interface: resources are identified by URIs; you manipulate them through representations (JSON, HTML); messages are self-descriptive (methods, media types, headers); and hypermedia drives application state (HATEOAS).
- Layered system: clients can't tell whether they talk to the origin or an intermediary (CDN, gateway, proxy).
- Code on demand (optional): servers can send executable code (JavaScript).
Most "REST APIs" in industry are HTTP+JSON APIs following resource-oriented conventions, without hypermedia. The Richardson Maturity Model names the levels: level 0 (one endpoint, RPC over POST), level 1 (resources), level 2 (resources + correct HTTP methods and status codes), and level 3 (+ hypermedia). Level 2 is where most good APIs live. Being pragmatic about the label is fine. Being sloppy about HTTP semantics isn't, because caches, proxies, clients, retries and tooling all rely on them.
Resource modelling
Model your API around resources (nouns), not procedures (verbs):
GET /customers/42 a customer
GET /customers/42/orders a sub-collection
POST /customers/42/orders create an order for the customer
GET /orders/o-981 an order (also addressable on its own)
PATCH /orders/o-981 partial update
DELETE /orders/o-981/lines/3 remove a line
GET /orders?status=PAID&sort=-createdAt&limit=50
Guidelines:
- Plural nouns for collections (
/orders), with IDs for items (/orders/{id}). Lowercase, hyphenated path segments (/shipping-addresses). - Don't mirror database tables. Resources are the client's view: aggregates (an order with its lines), projections (an
order-summary), and process resources. - Shallow nesting:
/customers/42/ordersis fine, but/customers/42/orders/7/lines/3/discounts/1isn't. Give deep entities their own top-level URIs. - Opaque, stable identifiers. Don't expose auto-increment IDs if enumeration is a risk (use UUIDs, ULIDs or prefixed IDs like
ord_2Kc…), and never change an ID's meaning. - Actions that aren't CRUD: model them as sub-resources or state changes rather than verbs in URLs. To cancel an order, use
POST /orders/{id}/cancellation(creating a cancellation resource), orPATCH /orders/{id}with{"status":"CANCELLED"}if the transition is a plain state change. A pragmaticPOST /orders/{id}:cancel(Google's custom-method style) is also widely used. Be consistent. - Long-running operations:
POST /reports→202 AcceptedwithLocation: /operations/op-77, and the client polls (or gets a webhook) untilstatus: done, with a link to the result. - Field naming: pick one casing (camelCase is the JSON norm; snake_case is also common) and apply it everywhere.
HTTP semantics
HTTP methods
| Method | Meaning | Safe (no side effects) | Idempotent (repeat = same effect) | Request body | Cacheable |
|---|---|---|---|---|---|
GET |
Retrieve a representation | ✓ | ✓ | No (semantics undefined) | ✓ |
HEAD |
GET without a body (headers only) | ✓ | ✓ | No | ✓ |
OPTIONS |
Capabilities (CORS preflight) | ✓ | ✓ | Optional | No |
POST |
Process the enclosed representation: create a subordinate, trigger processing | ✗ | ✗ | Yes | Rarely |
PUT |
Replace the target's state with the representation (create if absent) | ✗ | ✓ | Yes | No |
PATCH |
Partial modification | ✗ | Not guaranteed (depends on the patch format) | Yes | No |
DELETE |
Remove the target | ✗ | ✓ (the second DELETE has no further effect, though it may return 404) | Optional | No |
QUERY (IETF draft) |
A safe, idempotent query with a body (for complex searches) | ✓ | ✓ | Yes | ✓ |
Safe methods must not change server state in a way the client is responsible for (logging is fine). Crawlers, prefetchers and link previewers call GETs freely, so never change state on GET (GET /orders/42/delete is how pages get deleted by crawlers).
Idempotency is the property that makes retries safe: after a timeout, a client (or proxy) can resend a PUT or DELETE without fear. Not knowing whether a request succeeded is the normal situation in distributed systems. POST isn't idempotent, so retrying a timed-out POST /payments can charge twice unless you add idempotency keys (below).
Status codes
Use them precisely. Clients, proxies, monitoring and retry logic key off them:
| Code | When |
|---|---|
| 200 OK | Success with a body |
| 201 Created | Created. Include a Location header with the new resource's URI, and usually the representation |
| 202 Accepted | Accepted for asynchronous processing. Point to a status resource |
| 204 No Content | Success, no body (DELETE, PUT without a body to return) |
| 206 Partial Content | Range requests (downloads, media) |
| 301 / 308 | Permanent redirect (308 preserves the method and body) |
| 302 / 303 / 307 | Temporary redirect. 303 See Other after a POST points to the result; 307 preserves the method |
| 304 Not Modified | The conditional GET matched: use the cached copy |
| 400 Bad Request | Malformed syntax, invalid parameters |
| 401 Unauthorized | Not authenticated (missing or invalid credentials). Include WWW-Authenticate |
| 403 Forbidden | Authenticated but not permitted |
| 404 Not Found | No such resource (also used to hide existence from unauthorised users) |
| 405 Method Not Allowed | Include an Allow header |
| 406 Not Acceptable | Can't produce any media type in Accept |
| 409 Conflict | State conflict: duplicate, invalid transition, edit conflict |
| 410 Gone | Permanently removed |
| 412 Precondition Failed | An If-Match / If-Unmodified-Since precondition failed (lost-update prevention) |
| 413 Content Too Large / 414 URI Too Long | Size limits |
| 415 Unsupported Media Type | The request's Content-Type isn't accepted |
| 422 Unprocessable Content | Well-formed but semantically invalid (validation failures) |
| 428 Precondition Required | The server requires conditional requests (If-Match) for updates |
| 429 Too Many Requests | Rate limited. Include Retry-After |
| 500 Internal Server Error | Unexpected server bug |
| 502 Bad Gateway | An upstream returned an invalid response |
| 503 Service Unavailable | Overloaded or in maintenance. Retry-After |
| 504 Gateway Timeout | An upstream didn't answer in time |
Anti-patterns: 200 with {"error": …} (breaks every HTTP-aware tool and retry policy), 500 for client mistakes (pages on-call engineers for nothing and triggers pointless retries), 404 for "empty list" (an empty collection is 200 []), and 401 versus 403 confusion.
Retryability by status: retry on 408, 429, 502, 503 and 504, and on connection failures, with backoff (chapter 52), only for idempotent requests or ones protected by idempotency keys. Don't retry other 4xx codes.
Headers that matter
| Header | Purpose |
|---|---|
Content-Type / Accept |
Media type of the body / acceptable response types (content negotiation) |
Location |
URI of a created resource or redirect target |
Cache-Control, ETag, Last-Modified, Vary |
Caching and validation (chapter 27 of Vol. 2) |
If-None-Match, If-Match, If-Modified-Since, If-Unmodified-Since |
Conditional requests |
Authorization / WWW-Authenticate |
Credentials (bearer tokens) / challenge |
Retry-After |
When to retry after 429/503 (seconds or an HTTP date) |
Idempotency-Key |
Deduplicate retried non-idempotent requests (IETF draft, widely adopted) |
RateLimit-Policy / RateLimit (IETF draft), older X-RateLimit-Limit/Remaining/Reset |
Advertise quotas |
Link |
Pagination and related resources (rel="next") |
traceparent / X-Request-ID |
Distributed tracing and correlation (Vol. 2 ch. 32) |
Deprecation / Sunset |
Announce deprecation and removal dates (RFC 9745 and RFC 8594) |
Prefer |
Client preferences (return=minimal, respond-async) |
Content negotiation
The client states what it can accept, and the server picks a representation:
GET /orders/o-981 HTTP/1.1
Accept: application/json;q=1.0, application/xml;q=0.5
Accept-Language: de-CH, en;q=0.8
Accept-Encoding: br, gzip
HTTP/1.1 200 OK
Content-Type: application/json
Content-Language: en
Content-Encoding: br
Vary: Accept, Accept-Language, Accept-Encoding ← caches must key on these
- Media types:
application/jsonis the norm. Specific types likeapplication/problem+json(errors),application/merge-patch+json,application/json-patch+jsonand vendor types (application/vnd.shop.order.v2+json, used for media-type versioning) carry more meaning. Varyis essential whenever the response depends on request headers, or caches serve the wrong variant.- Frameworks implement negotiation through message converters: Spring
HttpMessageConverters withproduces/consumes, ASP.NET output formatters, Axum extractor types, and Phoenixacceptsplugs. - Return 406 if nothing acceptable can be produced, and 415 if the request body's
Content-Typeisn't supported.
Working with collections
Pagination
Never return unbounded collections. Three strategies:
| Strategy | Request | Pros | Cons |
|---|---|---|---|
| Offset/limit (page/size) | ?offset=100&limit=50 or ?page=3&size=50 |
Simple; jump to any page; total counts are easy | Slow at depth (OFFSET 100000 still scans and discards 100,000 rows); unstable: inserts and deletes shift pages, so items are skipped or duplicated while paging |
| Keyset (seek) | ?after_created=2026-10-01T10:00Z&after_id=o-981&limit=50 |
Fast at any depth (an index seek: WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 50); stable under concurrent writes |
No random page jumps; requires a unique, indexed sort key |
| Cursor (an opaque token) | ?cursor=eyJjIjoiMjAyNi0xMC0wMVQxMDowMFoiLCJpIjoibzk4MSJ9&limit=50 |
Keyset under the hood, but opaque: the server can change the encoding; clients just follow next |
Same as keyset; tokens should be signed or validated |
{
"data": [ { "id": "o-981", "createdAt": "2026-10-01T10:00:00Z", "total": "49.90" } ],
"page": { "nextCursor": "eyJj…", "hasMore": true },
"links": { "next": "/orders?cursor=eyJj…&limit=50" }
}
-- Keyset query: needs a composite index on (created_at DESC, id DESC)
SELECT id, created_at, total
FROM orders
WHERE customer_id = $1
AND (created_at, id) < ($2, $3) -- the last row of the previous page
ORDER BY created_at DESC, id DESC
LIMIT 51; -- fetch one extra to compute hasMore
Total counts (COUNT(*)) are expensive on large tables. Make them optional (?include=total), approximate, or omit them. Spring Data offers Page<T> (runs a count query), Slice<T> (no count; knows only whether a next slice exists), and Window<T> with ScrollPosition for keyset scrolling (chapter 49). GraphQL standardised cursors in the Relay connection spec. Stripe, Slack and GitHub's newer APIs use cursors.
Filtering and sorting
GET /orders?status=PAID&status=SHIPPED&createdFrom=2026-10-01&minTotal=100&q=chair
GET /orders?sort=-createdAt,total ← '-' prefix for descending
GET /orders?fields=id,status,total ← sparse fieldsets (smaller payloads)
GET /orders?include=customer,lines ← embed related resources (JSON:API style)
Guidelines:
- Allow-list filterable and sortable fields, and map them to indexed columns. Never pass a client-supplied
sortstring into SQL (ORDER BY ${sort}is an injection vector and a performance risk). Validate against an enum. - Use the same parameter style everywhere. Consider a standard (JSON:API's
filter[status]=PAID, OData's$filter=, or RSQL/FIQL?filter=status==PAID;total>100) if your filters are rich, but beware giving clients a query language you must support forever. - Complex search with long criteria:
POST /orders/searchwith a body (pragmatic, but not cacheable), or the emergingQUERYmethod. - Always sort deterministically: add a unique tie-breaker (
id) so pagination is stable.
Change and evolution
Versioning
APIs evolve. Breaking changes need a strategy:
| Strategy | Example | Notes |
|---|---|---|
| URI path | /v1/orders, /v2/orders |
The most common: visible, easy to route at gateways and to document. Purists object that the resource is the same |
| Header / media type | Accept: application/vnd.shop.v2+json (GitHub's older approach) |
Keeps URIs stable, but harder to test in browsers and easy to forget |
| Custom header | Api-Version: 2 |
Similar |
| Query parameter | ?api-version=2026-10-01 (Azure) |
Easy, but mixes with filters |
| Date-based versions | Stripe-Version: 2026-09-30 |
Each account is pinned to the version it first used; the server transforms responses between versions with "version change" modules. Very client-friendly, more server work |
Better than any versioning scheme is not breaking clients:
- Additive changes are compatible: new optional fields, new endpoints, new optional query parameters, and new enum values (only if clients were told to tolerate unknown values).
- Breaking changes: removing or renaming fields, changing types or formats, making optional inputs required, changing semantics, tightening validation, changing status codes or error formats, and changing pagination behaviour.
- When you must break: run versions side by side, announce with
DeprecationandSunsetheaders, measure usage per version and client, and give a migration window.
Spring Framework 7 added first-class API versioning (configured through ApiVersionConfigurer, with @GetMapping(version = "1.1") on handlers and version resolution from a header, path, query parameter or media type). ASP.NET has Asp.Versioning. Most Go and Rust services route /v1 and /v2 explicitly.
Backward and forward compatibility
- Backward compatible (a new server with old clients): old clients keep working when the server changes.
- Forward compatible (an old client with new server responses, or an old server with new client requests): readers tolerate data they don't understand.
The robustness principle (Postel's law), applied carefully: be tolerant in what you accept from evolving schemas (ignore unknown fields, treat unknown enum values as "other"), and strict in what you send (always produce valid, documented output). Use it with care for security-relevant input: tolerance there becomes ambiguity that attackers exploit.
// A tolerant reader in Jackson: ignore unknown fields; map unknown enum values to a fallback
@JsonIgnoreProperties(ignoreUnknown = true)
record PaymentEvent(String id, PaymentStatus status) {}
enum PaymentStatus { AUTHORIZED, CAPTURED, REFUNDED, @JsonEnumDefaultValue UNKNOWN }
// mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
#[derive(Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
enum PaymentStatus { Authorized, Captured, Refunded, #[serde(other)] Unknown } // unknown variants → Unknown
// serde ignores unknown struct fields by default (#[serde(deny_unknown_fields)] opts into strictness)
Contract tests (chapter 54: consumer-driven contracts with Pact or Spring Cloud Contract) and schema diffing in CI (openapi-diff, oasdiff, buf breaking for Protobuf) catch accidental breaks before release. Schema-first design (OpenAPI or Protobuf as the source of truth, generating server stubs and clients) makes the contract explicit, while code-first generation (springdoc, FastAPI) keeps it close to the implementation. Both work if the contract is reviewed and diffed.
Idempotency and retries
Networks fail after the server processed a request but before the client got the response. The client can't distinguish "never arrived" from "done, response lost". Safe retries need idempotency:
- Naturally idempotent operations:
PUT(replace),DELETE, and setting state ("set status to CANCELLED"). Design operations to be idempotent where you can:PUT /orders/{client-generated-id}makes creation idempotent, because the client chooses the ID. - Idempotency keys for non-idempotent
POSTs: the client generates a unique key (a UUID) per logical operation and sends it asIdempotency-Key. The server stores the key with the outcome. A retry with the same key returns the stored result instead of executing again.
Implementation details that matter:
- Atomically claim the key (a unique constraint insert, or Redis
SET NX) before executing, so concurrent duplicates don't both run. A duplicate that arrives while the first is in progress gets 409 (or waits). - Store the response (status + body) and replay it exactly.
- Bind the key to the request: hash the body and reject the same key with a different payload (422).
- Scope keys per client or account, and expire them (24 hours is common).
- Same transaction: record the key's completion in the same database transaction as the business effect where possible. Otherwise a crash between the two leaves ambiguity.
- Downstream calls need idempotency too: pass the key (or a derived one) to the payment provider, which most payment APIs support.
@PostMapping("/payments")
ResponseEntity<PaymentDto> pay(@RequestHeader("Idempotency-Key") UUID key, @Valid @RequestBody PayCommand cmd) {
return idempotency.execute(key, cmd.fingerprint(), () -> { // claim → run → store, or replay
var p = payments.charge(cmd, key.toString()); // forward the key to the PSP
return ResponseEntity.status(201).body(p);
});
}
Retries themselves (backoff, jitter, budgets, and amplification across layers) are covered in chapter 52.
Conditional requests and ETags
An ETag is an opaque version identifier for a representation: a hash of the content, or a version number. It enables two things:
1. Efficient caching (conditional GET):
GET /products/p-1 → 200 OK, ETag: "v7", Cache-Control: max-age=0, must-revalidate
GET /products/p-1 If-None-Match: "v7" → 304 Not Modified (no body: saves bandwidth and serialisation)
2. Preventing lost updates (optimistic concurrency over HTTP):
GET /orders/o-981 → 200, ETag: "12"
PUT /orders/o-981 If-Match: "12" {…changes…} → 200, ETag: "13"
PUT /orders/o-981 If-Match: "12" {…stale…} → 412 Precondition Failed (someone else changed it)
Two users editing the same order can't silently overwrite each other. Require If-Match for updates with 428 Precondition Required if you want to enforce it. Map the ETag to the entity's version column (JPA @Version, chapter 49) so the HTTP check and the database check are the same mechanism.
- Strong ETags (
"12") mean byte-identical. Weak ones (W/"12") mean semantically equivalent (for example, the same data with different JSON formatting). Use strong ETags forIf-Match. - Spring's
ShallowEtagHeaderFiltercomputes ETags by hashing the response body. That saves bandwidth but not server work, since the response is still generated. For real savings, compute ETags from version columns and checkIf-None-Matchbefore loading the full data:WebRequest.checkNotModified(etag)in Spring MVC, orResponseEntity.ok().eTag(...).
@GetMapping("/orders/{id}")
ResponseEntity<OrderDto> get(@PathVariable String id, WebRequest req) {
long version = orders.currentVersion(id); // cheap query
String etag = "\"" + version + "\"";
if (req.checkNotModified(etag)) return null; // Spring writes 304
return ResponseEntity.ok().eTag(etag).body(orders.find(id));
}
@PutMapping("/orders/{id}")
ResponseEntity<OrderDto> update(@PathVariable String id, @RequestHeader(value = "If-Match", required = false) String ifMatch,
@Valid @RequestBody UpdateOrder cmd) {
if (ifMatch == null) return ResponseEntity.status(428).build();
var updated = orders.update(id, parseVersion(ifMatch), cmd); // throws on version mismatch → 412
return ResponseEntity.ok().eTag("\"" + updated.version() + "\"").body(updated);
}
PATCH formats: JSON Merge Patch and JSON Patch
PATCH needs a patch document format, identified by Content-Type:
JSON Merge Patch (RFC 7396, application/merge-patch+json): send a partial document. Present fields replace, null deletes, and absent fields are untouched:
PATCH /customers/42
Content-Type: application/merge-patch+json
{ "email": "ada@example.com", "phone": null, "address": { "city": "Pune" } }
It's simple and readable, but it can't set a field to a literal null (null means delete), can't modify array elements individually (arrays are replaced whole), and isn't idempotent-safe for conditional semantics.
JSON Patch (RFC 6902, application/json-patch+json): an array of operations on JSON Pointer paths:
[
{ "op": "test", "path": "/status", "value": "PENDING" },
{ "op": "replace", "path": "/shipping/method", "value": "EXPRESS" },
{ "op": "add", "path": "/lines/-", "value": { "sku": "SKU-9", "qty": 1 } },
{ "op": "remove", "path": "/coupon" }
]
It's precise: array operations, test for preconditions, move/copy. The whole patch applies atomically or not at all. It's harder for clients to construct and for servers to apply safely: validate paths against an allow-list, and run domain validation on the result, so a patch can't modify /id or /ownerId.
Many APIs avoid generic patch formats and expose explicit command endpoints for meaningful changes (POST /orders/{id}/shipping-method), which carry business intent better. Implementing merge patch in Java requires distinguishing absent from null: use JsonNode/Map, JsonNullable<T> (openapitools), or Jackson's readerForUpdating. Go uses map[string]json.RawMessage or pointer-to-pointer tricks. Rust uses Option<Option<T>> with #[serde(default, with = "::serde_with::rust::double_option")].
Problem Details (RFC 9457)
A standard JSON error format, application/problem+json (RFC 9457 obsoleted RFC 7807 in 2023):
{
"type": "https://api.shop.example/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"detail": "Only 2 units of SKU-9 are available; 5 were requested.",
"instance": "/orders/o-981",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"errors": [ { "pointer": "/lines/0/qty", "detail": "must be at most 2" } ]
}
type: a URI identifying the problem type (documentation lives there). It's the stable machine-readable code clients should switch on.title: a short human summary of the type (it doesn't change per occurrence).status,detail(specific to this occurrence),instance(where it happened).- Extension members are allowed (
errors,traceId,balance…).
Framework support: Spring 6+ ProblemDetail and ErrorResponse (enable with spring.mvc.problemdetails.enabled=true for built-in exceptions; chapter 48), ASP.NET Core AddProblemDetails()/TypedResults.Problem, Go's problem libraries (or a small struct), Rust's http-api-problem or a custom IntoResponse, and FastAPI exception handlers.
Rate limits
Rate limiting protects services from abuse and overload, and enforces fair use per client (algorithms in chapter 52). Tell clients what's happening:
HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=0;t=30
Content-Type: application/problem+json
{"type":"https://api.shop.example/problems/rate-limited","title":"Too many requests","status":429,"detail":"100 requests per minute exceeded"}
The IETF RateLimit and RateLimit-Policy header fields (draft) standardise what X-RateLimit-Limit/Remaining/Reset did informally (the exact syntax has changed between drafts, so check the current one). Limit by API key or account, not just IP (IPs are shared behind NAT and easily rotated). Distinguish rate limiting (429, per client) from overload protection (503, global). Well-behaved clients honour Retry-After with jitter.
HATEOAS awareness
Hypermedia As The Engine Of Application State: responses include links describing what the client can do next, so clients follow links instead of hard-coding URI templates and state rules:
{
"id": "o-981",
"status": "PENDING",
"total": "49.90",
"_links": {
"self": { "href": "/orders/o-981" },
"pay": { "href": "/orders/o-981/payment", "method": "POST" },
"cancel": { "href": "/orders/o-981/cancellation", "method": "POST" }
}
}
Once the order is paid, the server omits pay and cancel and adds refund. The client's UI shows buttons based on which links are present, so state rules live in one place. Formats: HAL (_links, _embedded; Spring HATEOAS's default), JSON:API (links), Siren, and Collection+JSON. Spring HATEOAS provides EntityModel, WebMvcLinkBuilder and RepresentationModelAssembler.
In practice, full HATEOAS is rare in public JSON APIs: clients are typically written against documentation and generated SDKs. Pagination links, self links and available-action links for state-dependent workflows are the parts that pay off. HTML is the most successful hypermedia format of all: a server-rendered web page with links and forms is HATEOAS, which is why htmx-style architectures revisit the idea (Vol. 2).
Beyond REST
gRPC, GraphQL and JSON-RPC
REST isn't the only option. Choose by the problem:
| REST/HTTP+JSON | gRPC | GraphQL | JSON-RPC / tRPC | |
|---|---|---|---|---|
| Model | Resources + HTTP semantics | Remote procedure calls defined in Protobuf IDL | A typed graph schema; the client sends a query selecting exactly the fields it needs | Procedure calls with JSON payloads (tRPC: TypeScript-inferred) |
| Transport | HTTP/1.1, 2, 3 | HTTP/2 (binary framing, multiplexing); streaming in both directions | Usually HTTP POST; subscriptions over WebSockets or SSE | HTTP |
| Payload | JSON (text) | Protobuf (binary, compact, schema-required) | JSON | JSON |
| Contracts | OpenAPI (optional) | .proto files (mandatory), codegen for every language |
SDL schema (mandatory), introspection | Code-first |
| Caching | HTTP caching works | Not HTTP-cacheable | Hard (POST, varied queries); persisted queries and client-side normalised caches | Weak |
| Browser support | Native | Needs gRPC-Web or Connect | Native | Native |
| Strengths | Universality, caching, tooling, public APIs | Internal service-to-service calls: performance, streaming, strong cross-language contracts, deadlines | Client-driven data fetching for varied UIs (BFFs, mobile), avoiding over- and under-fetching | Simple internal APIs, full-stack TypeScript |
| Pitfalls | Over- and under-fetching, chatty clients | Debuggability (binary), load-balancer support for HTTP/2, browser access | N+1 resolvers (needs DataLoader batching), query cost limits, authorisation per field | Coupling, no standard semantics |
// orders.proto: gRPC contract → generated servers and clients in Java, Go, Rust (tonic), C#, Python, …
syntax = "proto3";
package shop.orders.v1;
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order);
rpc CreateOrder(CreateOrderRequest) returns (Order);
rpc WatchOrder(WatchOrderRequest) returns (stream OrderEvent); // server streaming
}
message Order {
string id = 1; // field NUMBERS are the wire contract: never reuse or renumber
string customer_id = 2;
repeated Line lines = 3;
OrderStatus status = 4;
reserved 5; // removed field: reserve its number (and name) forever
google.protobuf.Timestamp created_at = 6;
}
enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; PENDING = 1; PAID = 2; CANCELLED = 3; }
Protobuf's compatibility rules give the same lesson as JSON's: add fields with new numbers; never reuse numbers; unknown fields are preserved and ignored by old readers; and enums need a zero "unspecified" value. Use buf breaking in CI. Spring has first-class gRPC support (Spring gRPC), and so do Go (grpc-go, Connect), Rust (tonic), .NET (Grpc.AspNetCore) and Python (grpcio).
A common architecture: REST or GraphQL at the edge for browsers, mobile and partners, and gRPC or asynchronous messaging inside between services (chapter 51), with an API gateway translating at the boundary.
Lab: API shapes under real network conditions
PostgreSQL 16 for pagination (2 million orders, queried from Python with psycopg); a JDK HttpServer with a filter that adds a 40 ms delay per request to stand in for a mobile network round trip; JDK 21.
Experiment 1: OFFSET versus keyset pagination
The same 20-row page fetched with LIMIT 20 OFFSET n and with a cursor (WHERE (created_at, id) < (last_created_at, last_id)), both using an index on (created_at DESC, id DESC); best of five:
page 1 (row 1): OFFSET 0.32 ms | keyset 0.17 ms | same rows True
page 100 (row 1,981): OFFSET 0.47 ms | keyset 0.26 ms | same rows True
page 10,000 (row 199,981): OFFSET 22.66 ms | keyset 0.47 ms | same rows True
page 50,000 (row 999,981): OFFSET 107.39 ms | keyset 0.24 ms | same rows True
EXPLAIN ANALYZE … LIMIT 20 OFFSET 999980
Limit (actual time=177.723..177.728 rows=20 loops=1)
-> Index Only Scan using orders_created_at_id_idx on orders (actual time=0.016..142.017 rows=1000000 loops=1)
OFFSET can't jump: the database walks the index and throws away a million rows to return 20, so cost grows linearly with page depth (and every crawler, export job or "jump to last page" button pays it). The keyset query seeks straight to the cursor position in the index and costs the same on every page. The cursor must be a unique, ordered key (here the timestamp plus id as a tiebreaker), and the API exposes it as an opaque token (often base64 of those values) in a next link, so clients can't do arithmetic on it and you can change the encoding later. The trade-off: no "jump to page 37", which few real users need.
Experiment 2: pages that shift under the reader
Fetch page 1, then a new order arrives, then fetch page 2:
a new order arrives between page 1 and page 2: OFFSET page 2 repeats 1 row(s) from page 1 | keyset page 2 repeats 0
The new row pushed everything down one position, so OFFSET 20 started one row too early and repeated the last item of page 1 (a deletion would instead skip an item). For an infinite-scroll feed that's a duplicated card; for a sync job copying records to another system, it's duplicated or missing data. Keyset pagination is anchored to a value, not a position, so it's stable under inserts and deletes.
Experiment 3: chatty versus batch APIs
A client needs 50 dishes. Three ways, over a 40 ms round trip:
50 sequential GETs /dishes/{id}: 2277 ms
50 parallel GETs /dishes/{id}: 109 ms
one GET /dishes?ids=1,2,…,50: 50 ms
Sequential per-item calls pay the round trip 50 times: the API equivalent of the N+1 query problem (chapter 49), and the reason mobile screens built on fine-grained APIs feel slow. Parallel calls hide latency but multiply load and connection use, and browsers limit parallel HTTP/1.1 connections per host to six (HTTP/2 multiplexes, Volume 2). A batch endpoint or a response that embeds related data does one round trip. That's the problem GraphQL and backend-for-frontend services (Volume 2 chapter 31) were created to solve; for REST, offer ?ids= lookups and ?include= expansions where clients need them.
Experiment 4: compression
1,000 dishes as JSON: 146,420 bytes | gzip 9,218 bytes (94% smaller)
JSON is repetitive (the same keys in every object), so it compresses extremely well. Enable gzip or Brotli on responses above about 1 KB (Accept-Encoding/Content-Encoding), usually at the reverse proxy or framework level (server.compression.enabled=true in Spring Boot). Don't compress tiny responses (overhead), already-compressed content (images), or responses that mix secrets with attacker-controlled text over TLS (the BREACH attack; Volume 10).
Experiment 5: the 40-millisecond mystery
The first run of experiment 3, before any tuning, gave strange numbers:
no simulated delay, 50 sequential GETs: 2395 ms (48 ms per request on localhost!)
with -Dsun.net.httpserver.nodelay=true: 166 ms (3 ms per request)
Every request on localhost took about 48 ms. The JDK's simple HttpServer writes the response headers and the body in separate small writes; with Nagle's algorithm on, the kernel holds the second small segment until the first is acknowledged, and the client's TCP stack delays its ACK for up to 40 ms hoping to piggyback it on data. Each waits for the other (Volume 1's networking chapter). Setting TCP_NODELAY on the server's sockets (the property above for this server; production servers such as Tomcat, Netty and Jetty set it by default) removed 45 ms from every request. Whenever latency clusters suspiciously around 40 ms (Linux's delayed-ACK timer) or 200 ms (older systems), suspect this interaction before anything else.
Try it yourself
- Encode experiment 1's cursor as a base64 JSON token and reject tampered tokens with an HMAC signature. Why might you want to?
- Add
If-None-Matchsupport to the list endpoint with an ETag computed from the page's ids and versions. When does a list ETag change? - Implement experiment 3's batch endpoint as GraphQL with one query fetching the 50 dishes and their categories, and compare payload sizes.
- Write an OpenAPI 3.1 description for the dish API from Start here and generate a TypeScript client from it (
openapi-typescript).
Revision sheet: HTTP API design
Key ideas
- Resources: nouns, plural collections, stable ids, sub-resources for ownership, actions modelled as resources (
/orders/42/cancellation) when they don't fit CRUD. - Semantics: safe (GET, HEAD) vs idempotent (PUT, DELETE) vs neither (POST, PATCH by default); status codes with their real meanings;
Location,Allow,Retry-After; Problem Details for errors. - Collections: pagination (cursor/keyset preferred, offset for small admin lists), capped limits, filtering and sorting parameters, sparse fieldsets,
includeexpansions, batch lookups. - Concurrency and retries: ETags with
If-None-Match(caching) andIf-Match(optimistic concurrency, 412/428); idempotency keys for creates; retry with backoff on 429/503. - Evolution: additive changes, tolerant readers, versioning in the path, header or media type; deprecation (
DeprecationandSunsetheaders) and migration windows; OpenAPI as the contract, with breaking-change checks in CI. - Beyond REST: GraphQL (client-shaped queries, N+1 resolvers, caching harder), gRPC (Protobuf, HTTP/2, streaming, deadlines; internal services), webhooks (signed, retried, idempotent receivers), async APIs (events, AsyncAPI), JSON:API and HAL conventions.
Numbers to remember
- Lab: page 50,000 cost 107 ms with OFFSET vs 0.24 ms with keyset; 50 sequential calls over 40 ms RTT took 2.3 s vs 50 ms batched; JSON gzipped 94% smaller; Nagle plus delayed ACK added about 45 ms per request.
Pitfalls
- Verbs in URLs, RPC disguised as REST, 200 with an error body.
- Unbounded lists; OFFSET pagination for feeds, syncs and exports.
- No idempotency for payments and order creation; retrying non-idempotent calls blindly.
- Last-write-wins updates without versions.
- Breaking changes without a new version or deprecation period; leaking database schema into the API.
- Chatty APIs designed per table rather than per client use case.
Glossary
- Idempotent: repeating the request has the same effect as doing it once.
- ETag: an opaque version identifier for a representation.
- Keyset pagination: paging by the last seen sort key instead of a row offset.
- Idempotency key: a client-generated id that lets the server deduplicate retries.
- Tolerant reader: a client that ignores fields it doesn't understand.
- OpenAPI: a standard description format for HTTP APIs.