Software Architecture

REST API Design: Resources, HTTP Semantics, Versioning and Error Formats

Intermediate10 min readUpdated

A REST API is a contract you will be living with for years, and most of its long-term cost is decided in the first week. This guide covers resource modelling, the HTTP semantics defined by RFC 9110, representation and error design including problem details, pagination and filtering, caching with ETags, and the versioning strategies that let an API change without breaking its consumers.

What you will learn

  • Model resources and URIs that reflect the domain rather than the database
  • Apply HTTP method, status code and conditional-request semantics correctly
  • Design pagination, filtering and sorting that stay correct as data changes
  • Return machine-readable errors using RFC 9457 problem details
  • Evolve an API compatibly and choose a versioning strategy you can live with

An HTTP API is the most durable interface most systems ever expose. The service behind it will be rewritten, moved to another platform and possibly replaced entirely, while the API keeps serving clients that were built by people who have long since left. That asymmetry is the reason to spend real design effort at the start: internal code can be refactored on a Tuesday afternoon, but a published field name is close to permanent.

Good REST design is mostly about using HTTP as it was specified rather than tunnelling a bespoke protocol through it. RFC 9110 defines what the methods mean, what the status codes mean and how conditional requests work, and an API that respects those definitions gets caching, retry safety, proxy behaviour and client library support for free. An API that ignores them has to reinvent all of it badly.

Resources and URIs

A resource is a thing in the domain worth addressing: an order, a customer, a payment, the collection of an account's transactions. It is not a database table, and modelling one URI per table is how APIs end up exposing schema decisions that then cannot change.

Conventions that hold up well:

  • Plural nouns for collections, with the identifier appended for an item: /orders, /orders/8f21c. Consistency matters more than the choice itself.
  • Nesting only where the child cannot exist alone. /orders/8f21c/lines is reasonable because a line has no meaning outside its order. /customers/42/orders is better expressed as /orders?customer=42 once orders are addressable in their own right, and nesting three levels deep is always a mistake.
  • No verbs in paths. The method is the verb. /orders/8f21c/cancel is a common pragmatic exception and worth resisting once; the alternative is a state field updated with PATCH, or a sub-resource /orders/8f21c/cancellation created with POST, which also gives you somewhere to record who cancelled and why.
  • Kebab-case, lowercase, no file extensions, and no trailing slash, chosen once and applied everywhere.
  • Opaque identifiers. Sequential integers leak volume and invite enumeration. UUIDs or short random identifiers cost nothing extra.

The deeper point is that URIs are part of the public contract. If a URI encodes your internal hierarchy, reorganising that hierarchy is a breaking change.

Method semantics

RFC 9110 assigns each method two properties that matter enormously in practice: whether it is safe (does not change state) and whether it is idempotent (repeating it has the same effect as doing it once). Infrastructure everywhere relies on these — proxies may retry idempotent requests, browsers may prefetch safe ones — so violating them causes bugs you will never reproduce locally.

MethodSafeIdempotentUse
GETYesYesRetrieve a representation; never change state, never take a body
HEADYesYesHeaders only — size or existence checks
POSTNoNoCreate a subordinate resource, or submit a process request
PUTNoYesCreate or replace a resource at a known URI
PATCHNoNoApply a partial modification
DELETENoYesRemove a resource; a second call returns 404 or 204
OPTIONSYesYesCommunicate supported methods; used by CORS preflight

POST being non-idempotent is the practical problem: a client that times out cannot know whether the order was created. Solve it with an idempotency key — a client-generated identifier sent in a header, stored server-side with the outcome, and replayed on repeat. The implementation is discussed in microservice design patterns.

For PATCH, choose a defined media type rather than inventing semantics. application/merge-patch+json sends an object with the fields to change, using null to remove; application/json-patch+json (RFC 6902) sends an ordered list of operations and can address array positions. Merge patch covers most needs; JSON Patch is worth it when clients edit lists.

Status codes

Use the small set precisely rather than the large set approximately.

CodeMeaning in practice
200 OKSuccess with a body
201 CreatedResource created; include a Location header pointing at it
202 AcceptedRequest accepted for asynchronous processing; return a status URI
204 No ContentSuccess with nothing to return, typically DELETE or PUT
304 Not ModifiedConditional GET whose validator still matches
400 Bad RequestMalformed syntax or an unparseable body
401 UnauthorizedNo or invalid credentials — authentication failed
403 ForbiddenAuthenticated, but not permitted
404 Not FoundNo such resource, or deliberately hidden from this caller
409 ConflictThe request conflicts with current state — duplicate, version mismatch
412 Precondition FailedA conditional request's If-Match did not hold
422 Unprocessable ContentSyntactically valid, semantically invalid — validation failures
429 Too Many RequestsRate limit hit; include Retry-After
500 / 502 / 503 / 504Server fault, bad upstream response, unavailable, upstream timeout

Two distinctions cause most confusion. 401 means "I do not know who you are"; 403 means "I know and you may not". And 400 versus 422: reserve 400 for bodies the parser rejects, and use 422 when the JSON parsed fine but the content breaks a business rule. Never return 200 with an error object in the body — every client library, proxy and monitoring system treats 200 as success, and you have made failures invisible. The full catalogue is available in HTTP status codes.

Errors that clients can act on

RFC 9457 defines application/problem+json, a small standard shape that removes the need for every API to invent its own error envelope.

{
  "type": "https://api.example.com/problems/insufficient-funds",
  "title": "Insufficient funds",
  "status": 422,
  "detail": "Account FR76…0189 has a balance of 12.40 EUR; the transfer requires 250.00 EUR.",
  "instance": "/transfers/9c1a4b7e",
  "balance": "12.40",
  "currency": "EUR",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736"
}

The rules that make it useful: type is a stable URI identifying the kind of problem and is what clients branch on, so it must never change meaning; title is a short human-readable summary that stays constant for a given type; detail explains this occurrence and may vary; extension members carry structured data the client needs. Include a trace identifier so that a support ticket can be joined to a distributed trace.

For validation failures, return every problem at once rather than the first, so a form can highlight all bad fields in a single round trip.

{
  "type": "https://api.example.com/problems/validation",
  "title": "Request validation failed",
  "status": 422,
  "errors": [
    { "field": "email",     "code": "format",  "message": "must be a valid email address" },
    { "field": "quantity",  "code": "min",     "message": "must be at least 1" }
  ]
}

Never leak stack traces, SQL fragments or internal hostnames in a detail. Log those with the trace identifier and return the identifier instead.

Collections: pagination, filtering, sorting

Any collection endpoint will eventually hold more rows than a response should carry, so page from the first day and never return an unbounded list.

Offset pagination (?page=3&size=50 or ?offset=100&limit=50) is simple and lets clients jump to an arbitrary page. Its weaknesses are real: the database scans and discards everything before the offset, so page 500 is far slower than page 1, and concurrent inserts shift rows between requests so items get skipped or duplicated.

Cursor pagination returns an opaque token encoding the position in a stable sort order, and the client passes it back for the next page. Deep pages cost the same as shallow ones, and concurrent writes do not cause skips.

GET /orders?status=confirmed&sort=-created_at&limit=50 HTTP/1.1
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json

{
  "items": [ { "id": "8f21c", "status": "confirmed", "total": "89.90" } ],
  "next":  "/orders?status=confirmed&sort=-created_at&limit=50&cursor=eyJjIjoiMjAyNi0wOS0wN1QwOTo0MSJ9"
}

Whichever you choose, apply the same disciplines: always sort by something unique (append the primary key as a tie-breaker, or pagination becomes non-deterministic), cap limit at a documented maximum, and use a fixed query-parameter vocabulary for filters rather than accepting arbitrary expressions — an API that accepts a filter string is an API whose query planner is now part of your public contract.

Representations and content negotiation

Clients state what they can accept with Accept; servers describe what they sent with Content-Type. Support one primary media type well — almost always application/json — and add others only when a real consumer needs them.

Conventions worth fixing early, because changing them later breaks everyone: a single casing style for field names (camelCase or snake_case, chosen once); RFC 3339 timestamps in UTC with an explicit offset; monetary amounts as strings with an explicit currency field, never as floating-point numbers; enumerations as stable uppercase tokens rather than display text; and absent versus null given distinct meanings, documented.

Do not wrap every response in a generic envelope such as {"data": …, "meta": …}. HTTP already provides status, headers and body; the envelope adds a layer clients must unwrap and duplicates information the protocol carries. Metadata that genuinely belongs alongside a collection — pagination links, total counts — is the reasonable exception.

Caching and concurrency

GET responses can carry validators that let clients and proxies avoid re-transferring unchanged data, and the same validators solve the lost-update problem for writes.

GET /orders/8f21c HTTP/1.1
If-None-Match: "v14"

HTTP/1.1 304 Not Modified
ETag: "v14"
Cache-Control: private, max-age=60

An ETag is an opaque validator for a specific representation — a version number, a content hash. A client that has one sends If-None-Match and receives 304 with no body when nothing changed. For writes, the client sends If-Match: "v14" on its PUT or PATCH; if the resource has moved on, the server returns 412 Precondition Failed and the client can reload and retry instead of silently overwriting someone else's change. This is optimistic concurrency control implemented in the protocol, and it costs almost nothing to add.

Set Cache-Control deliberately on every response: private for anything user-specific, no-store for anything sensitive, and a modest max-age for reference data that many clients read.

Versioning and compatibility

The cheapest version is the one you never have to ship, so exhaust compatible evolution first. Adding an optional field, adding an endpoint, adding an enum value that clients are documented to tolerate, relaxing a validation rule — all are compatible if clients ignore unknown fields, which your documentation must require. Removing a field, renaming one, changing a type, tightening validation or changing a status code are all breaking.

When a break is unavoidable:

StrategyExampleTrade-off
URI path/v2/ordersObvious, easy to route and cache, but the version is baked into every client URI
Media typeAccept: application/vnd.example.order.v2+jsonPrecise and per-resource; clients and tooling often handle it poorly
Custom headerX-API-Version: 2Keeps URIs stable; invisible in logs and browser testing unless you look
Query parameter/orders?version=2Simple; interacts awkwardly with caching

Path versioning wins on operational simplicity for most teams, and its main cost — coarse granularity — is manageable if you version rarely. Whichever you choose, version the whole API rather than individual endpoints, keep the previous version running while consumers migrate, publish a Sunset header and a deprecation date on the old one, and measure per-version traffic so retirement is a decision based on evidence rather than hope.

Hypermedia, in proportion

The hypermedia constraint says a client should discover what it can do next from links in the response rather than from hard-coded URIs. Fully applied, it decouples clients from your URI structure permanently.

Honestly assessed, very few clients are written to navigate dynamically, and generic hypermedia formats add ceremony that most teams abandon. What does pay for itself is targeted: pagination links (clients genuinely follow next), links to related resources that save a lookup, and links representing available state transitions, which lets the server tell a UI that an order can be cancelled but not refunded without the client re-implementing that rule.

{
  "id": "8f21c",
  "status": "CONFIRMED",
  "total": { "amount": "89.90", "currency": "EUR" },
  "_links": {
    "self":    { "href": "/orders/8f21c" },
    "lines":   { "href": "/orders/8f21c/lines" },
    "cancel":  { "href": "/orders/8f21c/cancellation", "method": "POST" }
  }
}

Describing the API

An OpenAPI document is the machine-readable contract: paths, operations, schemas, security schemes, examples. It generates client libraries, drives mock servers, powers contract tests and feeds the developer portal of an API management platform.

Two approaches exist. Design first means writing the OpenAPI document before the code, reviewing it with consumers and generating server stubs — better for public or partner APIs where the contract is negotiated. Code first generates the document from annotated implementation, as springdoc does, which stays accurate with less effort and suits internal APIs. Either way, keep the document in version control, diff it in code review so breaking changes are visible, and include realistic examples — the example is the part developers actually read.

Key takeaways

  • Design URIs around domain resources, not tables, and treat every published path and field name as effectively permanent.
  • Respect the safe and idempotent properties defined in RFC 9110; where POST cannot be idempotent, add an idempotency key.
  • Use a precise, small set of status codes, and never signal failure with 200.
  • Return errors as RFC 9457 problem details with a stable type URI, structured extensions and a trace identifier.
  • Page every collection, sort by a unique key, and prefer cursors when data changes under the reader or pages get deep.
  • Evolve compatibly by adding rather than changing; when a break is unavoidable, version the whole API, announce a sunset date and measure usage before retiring anything.

Sources and further reading

Frequently asked questions

Should I use PUT or PATCH for updates?
PUT replaces the entire resource with the representation you send, so omitting a field means clearing it. PATCH applies a partial modification described by the request body. Most real clients want partial updates, so PATCH is the common choice; define its media type explicitly, either application/merge-patch+json for simple field updates or application/json-patch+json when you need operations on arrays.
Is offset pagination really that bad?
It is fine for small, stable data sets and for interfaces that need to jump to page 40. It has two genuine problems at scale: the database must scan and discard everything before the offset, so deep pages get slower, and rows inserted or deleted between requests cause items to be skipped or repeated. Cursor pagination based on a stable sort key avoids both.
Do I have to implement HATEOAS to call it REST?
By the original definition, yes — the hypermedia constraint is what allows clients to discover transitions rather than hard-code URIs. In practice very few clients navigate links dynamically, and full hypermedia rarely repays its cost. The pragmatic middle ground is to include links for genuine state transitions and for pagination, where clients really do follow them, and to document everything else in OpenAPI.
How long should an old API version be supported?
Long enough for the slowest consumer you care about, which for public APIs usually means at least twelve months and for mobile clients at least as long as your oldest supported app version. Announce a sunset date when the new version ships, publish the Sunset header on deprecated endpoints, and instrument usage per version so you can prove who is still calling before you switch anything off.