Backend

Beyond CRUD: 8 REST API Patterns for Production-Ready APIs

Eight patterns, from Problem Details errors to idempotency keys, that make a REST API predictable, safe to retry, and easy to evolve.

·
8 min read
·
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

Beyond CRUD: 8 REST API Patterns for Production-Ready APIs

A good API works when everything goes right. A great API keeps working when networks drop, clients retry, two users edit the same record, and traffic spikes.

The difference is rarely a clever framework. It comes down to a handful of patterns that make an API predictable, safe to retry, and easy to evolve. Here are eight, grouped by what they buy you.

flowchart TB
    G(["Great REST API"])
    G --> P["Predictable"]
    G --> S["Safe"]
    G --> D["Durable"]
    P --> P1["1. Resource design and HTTP semantics"]
    P --> P2["2. Structured errors"]
    P --> P3["3. Cursor pagination"]
    S --> S1["4. Idempotency keys"]
    S --> S2["5. Conditional requests"]
    S --> S3["6. Rate limit signals"]
    D --> D1["7. Versioning and deprecation"]
    D --> D2["8. Async operations"]
    classDef root fill:#6366f1,stroke:#4338ca,color:#ffffff
    classDef p fill:#dbeafe,stroke:#3b82f6,color:#1e3a8a
    classDef s fill:#dcfce7,stroke:#22c55e,color:#14532d
    classDef d fill:#fef3c7,stroke:#f59e0b,color:#78350f
    class G root
    class P,P1,P2,P3 p
    class S,S1,S2,S3 s
    class D,D1,D2 d

1. Model resources and use HTTP the way it was designed

A good API exposes POST /createOrder and returns 200 OK with {"success": false} when something breaks. A great API uses nouns for resources, methods for actions, and status codes for outcomes.

GET    /orders        # list
POST   /orders        # create  -> 201 Created + Location: /orders/42
GET    /orders/42     # read
PUT    /orders/42     # replace
PATCH  /orders/42     # partial update
DELETE /orders/42     # delete  -> 204 No Content

Method

Safe

Idempotent

Typical use

GET

Yes

Yes

Read

PUT

No

Yes

Replace a resource

DELETE

No

Yes

Remove a resource

PATCH

No

Not guaranteed

Partial update

POST

No

No

Create, or trigger an action

Rules worth enforcing:

  • Use plural, lowercase nouns and nest at most one or two levels (/orders/42/items).

  • Let status codes carry meaning: 201 plus a Location header on create, 204 when there is no body, 400 for malformed requests, 401 unauthenticated, 403 forbidden, 404 missing, 409 conflict, 422 well-formed but failing validation.

  • Model actions that don't fit CRUD as sub-resources, for example POST /orders/42/cancellation.

  • For PATCH, pick JSON Merge Patch (RFC 7396) or JSON Patch (RFC 6902) and document which one you accept.

  • Be consistent everywhere. Pick one property naming style (snake_case or camelCase) for the whole API, as the examples in this post do with snake_case, and send timestamps as RFC 3339 (ISO 8601) strings in UTC, such as 2026-11-23T09:30:00Z. Once a developer learns one endpoint, they should be able to guess the rest.

2. Return errors as Problem Details (RFC 9457)

{"error": "something went wrong"} forces every client to parse your prose. RFC 9457 defines a standard error shape with the media type application/problem+json.

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Validation failed",
  "status": 422,
  "detail": "One or more fields are invalid.",
  "instance": "/errors/9f1c2e7a",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "errors": [
    { "detail": "Must be at least 1", "pointer": "#/items/0/quantity" }
  ]
}
  • type is a stable identifier clients can branch on. Never make them match on detail text.

  • title, status, detail and instance are the other standard members. instance identifies this specific occurrence, and status is advisory, so it must match the real HTTP status. Anything else (errors, trace_id) is an extension member, and the errors shape here follows the example in RFC 9457.

  • Use one error format for every endpoint, including 404, 429 and 500.

  • Include a trace or request ID so support can find the log line. Never leak stack traces.

3. Paginate with cursors, not offsets

?page=3&per_page=50 is easy to build and breaks at scale. If rows are inserted or deleted between requests, clients see duplicates or miss items. Large offsets are also slow, because the database still scans and discards every skipped row.

Cursor (keyset) pagination returns an opaque token that points at the last item seen.

GET /orders?status=paid&limit=50&cursor=eyJpZCI6MTIwfQ
{
  "data": [{ "id": "ord_119", "status": "paid" }],
  "page": { "next_cursor": "eyJpZCI6MTE5fQ", "has_more": true }
}
SELECT * FROM orders
WHERE id < $1            -- the cursor
ORDER BY id DESC
LIMIT 51;                -- fetch limit + 1 to know whether another page exists
  • Always sort deterministically. If you sort on a non-unique column, add id as a tiebreaker.

  • Cap limit (for example 100) and set a sensible default.

  • Treat the cursor as opaque so you can change its internals later.

  • Keep filters and sort options in query parameters (?status=paid) and let the path identify the resource. GET must never change state, so avoid fakes like ?action=delete.

  • Allowlist filter and sort fields. Never pass client input straight into ORDER BY.

  • The trade-off: no jumping to page 47, and exact totals are expensive, so offer them only if clients truly need them.

4. Make unsafe retries safe with idempotency keys

Networks fail after the server has done the work. The client sees a timeout, retries, and the customer is charged twice. GET, PUT and DELETE are idempotent by definition; POST is not.

The fix is an Idempotency-Key header. The client generates a unique key per logical operation, and the server stores the key with the response and replays it on retries.

POST /payments HTTP/1.1
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"
Content-Type: application/json

{ "order_id": "ord_42", "amount": 4999, "currency": "USD" }
sequenceDiagram
    participant C as Client
    participant A as API
    participant S as Key store
    C->>A: POST /payments (Idempotency-Key K1)
    A->>S: Look up K1
    S-->>A: Not found
    A->>A: Charge the card
    A->>S: Save K1 and response
    A--xC: 201 Created (response lost)
    Note over C: Timeout, so the client retries
    rect rgb(220, 252, 231)
    C->>A: POST /payments (Idempotency-Key K1)
    A->>S: Look up K1
    S-->>A: Found, stored response
    A-->>C: 201 Created (same response, no second charge)
    end

Server rules:

  • Same key and same payload: replay the stored response, status and body included.

  • Same key with a different payload: reject with 422.

  • Same key while the first request is still processing: respond 409.

  • Key missing on an endpoint that requires it: 400.

  • Save the key and the business effect in one transaction, with a unique constraint on the key, so two concurrent duplicates cannot both run.

  • Expire keys after a bounded window (24 hours is a common choice).

The Idempotency-Key header is still an IETF Internet-Draft rather than an RFC, but payment APIs such as Stripe's have used it for years, so it is a safe convention to adopt. One detail differs: the draft specifies a quoted string, as in the example above, while Stripe sends the bare value.

5. Use conditional requests for caching and concurrency

Two clients read the same order. Both edit it. The second write silently overwrites the first. This is the lost update problem, and ETag solves it along with caching.

Caching. Return an ETag on GET. The client sends it back in If-None-Match, and if nothing changed you answer 304 Not Modified with no body.

Concurrency. Require If-Match on writes. If the resource changed since the client read it, respond 412 Precondition Failed. If the header is missing on a resource where you require it, respond 428 Precondition Required.

sequenceDiagram
    participant A as Client A
    participant B as Client B
    participant API
    A->>API: GET /orders/42
    API-->>A: 200 (ETag v1)
    B->>API: GET /orders/42
    API-->>B: 200 (ETag v1)
    B->>API: PATCH /orders/42 (If-Match v1)
    API-->>B: 200 (ETag v2)
    rect rgb(254, 226, 226)
    A->>API: PATCH /orders/42 (If-Match v1)
    API-->>A: 412 Precondition Failed
    end
    Note over A: Re-fetch, merge, retry
  • Build the ETag from a version column or a hash of the representation.

  • Use strong ETags for If-Match, because it uses strong comparison and weak (W/) tags never match.

  • Set Cache-Control explicitly. User-specific responses should be private.

6. Tell clients how to behave when they are rate limited

Rate limiting protects you, but silent throttling frustrates everyone. Tell clients what happened and when to come back.

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 30
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=0;t=30
  • 429 Too Many Requests means this client exceeded its quota. 503 Service Unavailable means the server itself is overloaded. Don't mix them up.

  • Retry-After is the standardized part, and clients should honor it. If both are present, it takes precedence over the RateLimit fields.

  • RateLimit and RateLimit-Policy come from an IETF draft that aims to standardize the older X-RateLimit-* convention. They are still a draft and the syntax has changed between revisions (the example above follows draft revision 11, from May 2026), so check the current draft before committing to it.

  • Limit per API key or user, not just per IP. Give expensive endpoints tighter limits than cheap ones.

  • Document your limits. On the client side, retry with exponential backoff and jitter so throttled clients don't all return at the same second.

7. Evolve without breaking clients: versioning and deprecation

Prefer additive changes: new optional fields, new endpoints, new optional parameters. Document that clients must ignore unknown fields and tolerate new enum values.

These changes are breaking and need a new version:

  • removing or renaming a field

  • changing a field's type or meaning

  • tightening validation

  • changing defaults

When you must break, version explicitly and pick one scheme. /v2/orders in the URL is the simplest to route, cache and debug. A media type such as application/vnd.example.v2+json is cleaner but harder for clients to discover.

Then retire the old version in-band, where clients can see it:

HTTP/1.1 200 OK
Deprecation: @1798761600
Sunset: Wed, 30 Jun 2027 23:59:59 GMT
Link: <https://api.example.com/docs/migrate-v2>; rel="deprecation"; type="text/html"

Deprecation (RFC 9745) says when the resource became or becomes deprecated, and uses a Unix timestamp prefixed with @. Sunset (RFC 8594) says when it will stop responding, and uses an HTTP date. The sunset date must not be earlier than the deprecation date.

flowchart LR
    A["v2 released"] --> B["v1 deprecated<br/>Deprecation header + migration guide"]
    B --> C["Sunset date announced<br/>Sunset header + direct emails"]
    C --> D["Watch v1 traffic<br/>contact remaining clients"]
    D --> E["v1 retired<br/>410 Gone"]
    classDef ok fill:#dcfce7,stroke:#22c55e,color:#14532d
    classDef warn fill:#fef3c7,stroke:#f59e0b,color:#78350f
    classDef bad fill:#fee2e2,stroke:#ef4444,color:#7f1d1d
    class A ok
    class B,C,D warn
    class E bad

Track usage per version so you know who is still on v1 before you turn it off.

8. Handle long-running work asynchronously

Report generation, video processing and bulk imports don't belong in a request that holds a connection open for minutes. Accept the work, return immediately, and let the client check on it.

POST /reports HTTP/1.1

HTTP/1.1 202 Accepted
Location: /operations/op_abc123
Retry-After: 5
sequenceDiagram
    participant C as Client
    participant API
    participant W as Worker
    C->>API: POST /reports
    API->>W: Enqueue job
    API-->>C: 202 Accepted (Location /operations/op_abc123)
    loop Until done
        C->>API: GET /operations/op_abc123
        API-->>C: 200 status running (Retry-After 5)
    end
    W->>API: Job finished
    C->>API: GET /operations/op_abc123
    API-->>C: 200 status succeeded (result at /reports/77)
    C->>API: GET /reports/77
    API-->>C: 200 report
  • The operation is a resource with a status such as queued, running, succeeded or failed. A failed operation carries a Problem Details body.

  • Retry-After on a 202 or a polling response is a common convention, not something RFC 9110 defines (it covers 503 and redirects, and RFC 6585 adds 429). Treat it as an advisory polling hint.

  • When it succeeds, link to the result. Some APIs return 303 See Other to the result instead.

  • Let clients cancel with DELETE /operations/{id}, and expire finished operations after a documented window.

  • Offer webhooks as an alternative to polling. Sign the payload (HMAC), include an event ID so receivers can deduplicate, and retry with backoff. Keep polling available, because webhooks can be missed.

  • Make the POST idempotent too (pattern 4), or a retry will start the job twice.


Good vs. great at a glance

#

Good API

Great API

1

Verbs in URLs, 200 for everything

Resources, correct methods and status codes

2

{"error": "failed"}

Problem Details with a stable type

3

?page=3 offsets

Cursor pagination with a capped limit

4

Retries create duplicates

Idempotency keys

5

Last write wins

ETag with If-Match

6

Silent throttling

429 with Retry-After and RateLimit headers

7

Breaking changes in place

Additive evolution, versions, Deprecation and Sunset

8

Requests that hang until timeout

202 Accepted and an operation resource

You don't need all eight on day one. If you can only do three this quarter, start with consistent errors (2), cursor pagination (3) and idempotency keys (4). They prevent the most painful production incidents and are the hardest to retrofit once clients depend on your current behavior.

Further reading

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Pradeep Kumar

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Pradeep Kumar's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.