REST API Best Practices: A Cheat Sheet for Designing HTTP APIs

API reviews keep coming back to the same REST questions: URLs, status codes, errors, versioning, and paging. In this article, we collect REST API best practices into one cheat sheet, with an example for each rule and a table you can copy.

If you've reviewed a few REST APIs and worked with them closely, you've observed the same questions. Should the URL have /v1? Is a 200 with an error in the body fine? PUT or PATCH? Offset or cursor? The HTTP spec (RFC 9110) already answers half of them. The other half are conventions a team picks once and writes down.

I wanted one page with the REST rules I can send before an API review. In this article, I collect them by topic: URLs, methods, status codes, errors, payloads, pagination, versioning, caching, concurrency, long-running tasks, and security. Each rule comes with a request example, and the article ends with a cheat-sheet table you can copy into your own guideline.

Richardson Maturity Model: how much REST do you need?

Leonard Richardson split HTTP APIs into four levels, and Martin Fowler's 2010 write-up made the model popular:

  • Level 0: one endpoint. Every call is a POST with the operation name in the body (SOAP, JSON-RPC).
  • Level 1, resources: each thing has its own URL (/orders/42), but every call is still a POST.
  • Level 2, HTTP methods: GET reads, DELETE deletes, and 404 means "not found".
  • Level 3, hypermedia controls: responses carry links to what the client can do next.

Use the model to see where your API stands, not as a score to max out. Fowler writes that it "is not a definition of levels of REST itself", and Roy Fielding treats Level 3 as a precondition of REST. By that strict reading, most APIs called REST aren't REST at all, and that's fine. Level 2 already gives you what this cheat sheet is about: cacheable reads, safe retries, and errors a client can act on.

I think people sometimes over-engineer REST and follow it where it isn't the best fit. A command like "recalculate all prices" doesn't become clearer when you invent a price-recalculation resource for it. Links in every response don't help a client that never reads them. Go to Level 3 only where clients follow links (more on that in the HAL section).

REST API design: contract first, then resources and URLs

REST API design: contract first, then resources and URLs
 The OpenAPI contract comes first, and tests check the code against it.

Write the OpenAPI contract before the code

I'd design the contract first and change it only by adding. 

So write the OpenAPI description before the implementation, review it like code, and keep it in the same repository as the service. Lint it in CI with a linter such as Spectral. Then test the running service against the spec, so the two can't drift apart. Consumer-driven contract tests (Pact) go one step further: each client publishes what it uses, and the provider's build fails when a change breaks one of them.

Start new specs on OpenAPI 3.1 or 3.2. Version 3.1 has been out since February 2021, and 3.2 since September 2025.

Note: check that your code generator, gateway, and docs tool support the OpenAPI version before you pick it. A spec your tools can't read is worse than an older one they can.

Write your team's conventions down once, too. The adidas API Guidelines are a good public example of what that looks like: short rules with MUST and SHOULD, and an example for each.

URLs identify resources, and the method says what to do

URLs identify resources, and the method says what to do
Each part of an HTTP message carries one kind of information.

Each part of an HTTP message carries one kind of information. The URL identifies the resource. The method says what to do with it. The status code reports the result. Headers carry metadata, and the body carries the content. When one part does another part's job, clients have to guess.

Bad example

❌ GET   /getOrders.json?version=2
❌ POST  /orders/42/update
❌ GET   /orders/search          (with a JSON body)

Improved example

✔️ GET   /orders?status=open
✔️ PATCH /orders/42
✔️ GET   /orders/42/items

Use plural nouns for collections (/orders), an ID for one item (/orders/42), kebab-case for multi-word segments (/shipping-addresses), and no trailing slash. Keep file extensions and version numbers out of the path.

Some actions aren't a field change. Canceling an order can refund a payment and notify a warehouse. Model it as a resource when that reads naturally (POST /orders/42/cancellations). When it doesn't, a plain action endpoint (POST /orders/42/cancel) is an honest exception. A bent domain model costs more than one verb in a URL.

Pick one naming convention for each part of the request

PartConventionExample
Path segmentkebab-case, plural nouns/shipping-addresses
Path parametercamelCase (URI templates don't allow hyphens in names)/orders/{orderId}
Query parametercamelCase?createdAfter=2026-10-01
JSON fieldcamelCase"orderNumber"
HeaderHyphenated-Pascal-Case, no X- prefix (RFC 6648)Idempotency-Key

Another consistent set works too. A mix is what hurts: when one endpoint returns order_id and the next one orderId, every client has to remember which is which.

HTTP methods and status codes

HTTP methods and status codes
HTTP methods by safety and idempotency.

Use each HTTP method for what the spec says it means

MethodSafeIdempotentUse for
GETyesyesRead a resource or a collection
HEADyesyesRead only the headers
PUTnoyesReplace the whole resource
PATCHnonoChange part of a resource
DELETEnoyesDelete a resource
POSTnonoCreate a resource, or run an action

Safe means the call doesn't change state, so caches and crawlers can repeat it. Idempotent means that sending the same request twice has the same effect as sending it once. So a client can retry a PUT or a DELETE after a timeout without thinking. POST and PATCH don't get that for free (the Idempotency-Key section below fixes it for POST).

Don't send a body with GET, don't create anything with GET (GET /users/new), and don't use PUT for a partial update.

For PATCH, pick one format and name it in Content-Type:

PATCH /orders/42
Content-Type: application/merge-patch+json

{ "status": "shipped", "giftMessage": null }

JSON Merge Patch (RFC 7396) is enough for most APIs: you send the fields to change, and null removes a field. Use JSON Patch (RFC 6902, application/json-patch+json) when you need operations on array items, such as "remove the third item".

Return the status code that matches the result

Wrong approach

❌ HTTP/1.1 200 OK
   { "error": "NOT_FOUND_ERR_CODE" }

Improved:

✔️ HTTP/1.1 404 Not Found
   Content-Type: application/problem+json

A 200 with an error inside tells every cache, retry policy, and dashboard that the call worked. Clients check the status code first, so put the result there.

CodeUse when
200 OKA read or an update succeeded and returns a body
201 CreatedA resource was created. Send its URL in Location
202 AcceptedThe work started but isn't finished (long-running tasks)
204 No ContentSuccess with no body, for example after DELETE
304 Not ModifiedThe client's cached copy is still valid
400 Bad RequestThe request is malformed
401 UnauthorizedCredentials are missing or invalid
403 ForbiddenThe caller is known but not allowed to do this
404 Not FoundThe resource doesn't exist, or the caller mustn't know it does
409 ConflictThe request conflicts with the current state, for example, a duplicate
412 Precondition FailedAn If-Match check failed
415 Unsupported Media TypeThe server doesn't accept the request body's Content-Type
422 Unprocessable ContentThe JSON is valid, but the values fail validation
429 Too Many RequestsThe client hit a rate limit
500 / 503A server bug / the service is temporarily unavailable

406 Not Acceptable is the opposite of 415: nothing you can return matches the client's Accept header. For validation errors, pick either 400 or 422 for the whole API and stick to it.

Error responses with Problem Details (RFC 9457)

If I could change one thing in an existing API, I'd start with the errors: switch to application/problem+json and let clients branch on type.

Problem Details is a standard JSON shape for HTTP API errors. RFC 9457 defines it (2023), and it replaced RFC 7807. Every error from every endpoint has the same fields, so a client needs one error handler instead of one per endpoint:

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

{
  "type": "https://api.example.com/problems/insufficient-stock",
  "title": "Not enough stock",
  "status": 422,
  "detail": "Only 3 units of SKU 1042 are left, and you asked for 5.",
  "instance": "/orders/42",
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  "errors": [
    { "pointer": "#/items/0/quantity", "detail": "Must be 3 or less." }
  ]
}
Error responses with Problem Details (RFC 9457)
Clients branch on type; title and detail are for people.

Each member has one job:

  • type is a URI that identifies the kind of problem. It's the stable part: client code branches on it, and the URI should open a page that explains the error and how to fix it. Use about:blank when the status code already says everything.
  • title is a short summary of the type, for people. It stays the same for every occurrence of that type, except for translation.
  • status repeats the HTTP status code for clients that lose the headers. It must match the real status.
  • detail explains this occurrence, for people. Clients show it or log it, but never parse it.
  • instance identifies this occurrence, often the request path or an error ID.
  • Extension members carry anything else. traceId lets support find the request in the logs. errors lists validation failures, each with a JSON pointer to the bad field. Clients ignore extensions they don't know.

Use Problem Details only for 4xx and 5xx responses. Never put a stack trace, an SQL statement, or a server name in detail. Log them, and return the trace ID instead.

In ASP.NET Core, a few lines turn unhandled exceptions and empty error responses into Problem Details:

builder.Services.AddProblemDetails(options =>
    options.CustomizeProblemDetails = ctx =>
        ctx.ProblemDetails.Extensions["traceId"] = ctx.HttpContext.TraceIdentifier);

var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();

MVC model validation already returns ValidationProblemDetails. For your own domain errors, return Results.Problem(...) and set type yourself, because type is what clients branch on. Treat each type URI as part of the contract: renaming it breaks clients the same way renaming a field does.

JSON payload conventions

JSON payload conventions
A resource with a nested relation and links.

Keep the JSON predictable

Not predictable JSON

{ "order_id": 42, "IsGift": null, "items": null,
  "created": "11/09/2026 14:07", "customerId": 7 }

Predictable JSON

{ "id": 42, "isGift": false, "items": [],
  "createdAt": "2026-11-09T14:07:17Z",
  "customer": { "id": 7 } }

The rules behind the second version:

  • camelCase field names, and plural names for arrays.
  • A boolean is true or false, never null.
  • An empty list is [] and an empty object is {}, not null.
  • Leave out fields that have no value.
  • Dates are ISO 8601 in UTC. Countries, currencies, and languages use ISO codes (DE, EUR, en).
  • A relation is a nested object ("customer": { "id": 7 }) or a link, not a loose customerId. The nested object can grow later (a name, a link) without a breaking rename.

Note: "leave out" and null mean different things in a Merge Patch request. There, a missing field means "don't change it", and null means "remove it".

What is HAL, and do you need it?

HAL (Hypertext Application Language, media type application/hal+json) is a convention for links in JSON. It reserves two fields: _links holds links to related resources and actions, and _embedded holds related resources included in the same response.

{
  "id": 42,
  "status": "open",
  "_links": {
    "self":     { "href": "/orders/42" },
    "customer": { "href": "/customers/7" },
    "cancel":   { "href": "/orders/42/cancellations" }
  },
  "_embedded": {
    "items": [ { "sku": "1042", "quantity": 2 } ]
  }
}

This is Level 3 of the maturity model. The client finds the cancel action by the link name cancel instead of building the URL. When the order can't be canceled anymore, the server leaves the link out, and the client hides the button. Keep each href relative to the API root, so the same response works behind any host or gateway.

I wouldn't make HAL mandatory unless your clients really follow the links. For most internal APIs, plain JSON with a self link is enough.

REST API pagination, filtering, and field selection

Page every collection, and return the page links

Page every collection, and return the page links
Pagination links let clients walk a collection without building URLs.

GET /orders?offset=100&limit=10

 

{
  "items": [ ... ],
  "totalCount": 910,
  "_links": {
    "self":  { "href": "/orders?offset=100&limit=10" },
    "first": { "href": "/orders?limit=10" },
    "prev":  { "href": "/orders?offset=90&limit=10" },
    "next":  { "href": "/orders?offset=110&limit=10" },
    "last":  { "href": "/orders?offset=900&limit=10" }
  }
}

Page every collection from the first release, with a default limit and a maximum. Adding paging later changes the response for every client. Return first, prev, next, and last links, in the body or in a Link header (RFC 8288). Clients that follow next instead of building URLs keep working when you switch from offset to cursor later.

I compared offset, keyset, and cursor pagination in Pagination Strategies. For a large collection that changes often, I'd pick a cursor over an offset.

Note: totalCount runs a count query on every request, which gets slow on a large table. Return it only when the UI needs it. Offset pages also drift: when a row is inserted on page 1, the last item of page 1 shows up again on page 2.

Filter with query parameters, and let clients choose fields

GET /orders?status=open&createdAfter=2026-10-01&sort=-createdAt&fields=id,status,total

Put filters, sorting, and field selection in query parameters on GET, so the request stays safe and cacheable. Document parameters that exclude each other ("customerId or email, not both"). The fields parameter returns only the listed fields, which cuts the payload for mobile clients and list views.

Note: a long filter can exceed URL length limits. The usual fallback is POST /orders/searches with the filter in the body, and it loses HTTP caching.

REST API versioning and backward compatibility

REST API versioning and backward compatibility
 Safe and breaking changes to an API contract.

Change the API only by adding

  1. Don't remove or rename anything: fields, parameters, endpoints, or headers.
  2. Don't change what an existing field or parameter means.
  3. Don't make an optional field or parameter required.
  4. Make everything you add optional.

Clients do their half: they ignore fields they don't know (the tolerant reader pattern). A client that fails on an unknown field turns every addition into a breaking change.

Avoid API versioning unless you must support legacy clients

I prefer to avoid versioning and use it only when it's strictly necessary. Versioning is tricky: every client has to support the switch, and you have to keep the old versions running. In practice, the API usually forces clients to update to the new version anyway, so /v1 in every URL is overhead. It makes sense in industries where you must support legacy clients for years.

When a breaking change is unavoidable, make it as small as possible. Add a new resource next to the old one (/order-drafts instead of a changed /orders), move clients over, and deprecate the old resource.

If you do need versions, there are two common places for them:

  • In the URL path (/v2/orders): easy to see and to route at the gateway. Every version is a new set of URLs, so links and caches split by version.
  • In the media type (Accept: application/vnd.example.order+json; version=2): the URLs stay stable. The version is easier to miss in logs and harder to try in a browser.

Either way, keep info.version in the OpenAPI file in semantic versioning (2.1.3), so the spec shows what changed even when the URLs don't.

Deprecate an endpoint with the Deprecation and Sunset headers

Deprecate an endpoint with the Deprecation and Sunset headers
Deprecate first, then sunset.
HTTP/1.1 200 OK
Deprecation: @1782863999
Sunset: Thu, 31 Dec 2026 23:59:59 GMT

Deprecation (RFC 9745, 2025) says that the endpoint is deprecated and since when. Sunset (RFC 8594) says when it stops working. The formats differ: Deprecation takes @ plus Unix seconds (here, 30 June 2026), and Sunset takes an HTTP date.

Mark the endpoint as deprecated in the spec and in the responses. Tell its consumers about the alternative and the migration path, and send a final notice before the sunset date. Log calls to deprecated endpoints by client ID, so you know who still uses them. Don't remove an endpoint while a known client still calls it.

Caching, concurrency, and retries in REST APIs

Send Cache-Control and an ETag, and answer If-None-Match with 304

Send Cache-Control and an ETag, and answer If-None-Match with 304
A conditional GET returns 304 when nothing changed.
GET /products/1042
→ 200 OK
  Cache-Control: max-age=300, must-revalidate
  ETag: "a7f3c2"

GET /products/1042
If-None-Match: "a7f3c2"
→ 304 Not Modified

Every response should say whether it can be cached and for how long. For personal data, that's Cache-Control: private or no-store. The ETag is a version tag for the representation, such as a hash or a row version. When the client sends it back in If-None-Match and it still matches, the server returns 304 with no body, and the client reuses its copy. Read more about cache layers in Mastering Caching: Strategies, Patterns & Pitfalls.

Stop lost updates with If-Match and 412

Stop lost updates with If-Match and 412
If-Match turns a lost update into a 412.

Two clients read order 42 with ETag: "v7", and both change it. Without a check, the second PUT silently overwrites the first one. With If-Match, the second write fails:

PUT /orders/42
If-Match: "v7"
→ 412 Precondition Failed      (the order is at "v8" now)

The client reads the order again, merges its change, and retries with the new ETag. For resources that several people edit, require If-Match on PUT and PATCH, and return 428 Precondition Required when it's missing. With EF Core on SQL Server, a row version column ([Timestamp]) gives you the ETag value and the database-side concurrency check from the same column.

Make POST safe to retry with an Idempotency-Key

Make POST safe to retry with an Idempotency-Key
An idempotency key makes a retried POST return the first result.

POST isn't idempotent. A client that times out and retries can create two payments. To prevent it, the client sends a unique key with the request:

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

The server stores the key with the first response. A retry with the same key gets the stored response, and the server doesn't create a second payment. Store a fingerprint of the request with the key and reject the same key with a different body. Keep keys for a limited time, such as 24 hours. The same idea protects message consumers, as described in Transactional Inbox and Outbox Patterns.

Long-running tasks and batch operations

Return 202 and a task resource for long-running work

Return 202 and a task resource for long-running work
A long-running task returns 202, then the client polls until a 303.

 

POST /reports
→ 202 Accepted
  Location: /reports/tasks/7
  Retry-After: 30

GET /reports/tasks/7
→ 200 OK   { "status": "running", "progress": 40 }

GET /reports/tasks/7
→ 303 See Other
  Location: /reports/7

When work takes tens of seconds or more, don't hold the connection open. Accept the request, return a task resource the client can poll, and use Retry-After to say how often to ask. When the task finishes, redirect to the result with 303. When it fails, return the task with "status": "failed" and a Problem Details object in a field. The poll itself succeeded, so it stays a 200.

Note: polling costs requests. When clients can receive calls, a callback (webhook) is the alternative: the client registers a URL, and the server POSTs the result to it. Then you own the retries of those calls.

Make bulk operations atomic

POST /orders
Content-Type: application/json

[ { "sku": "1042", "quantity": 2 }, { "sku": "2077", "quantity": 1 } ]

Accept a batch on the collection itself, and apply all of it or none of it. A client can't recover cleanly from "some of these worked". If the batch can't be atomic, return a success code only when every item succeeded. Otherwise, return an error with one problem per failed item, so the client knows exactly what to resend. Avoid a generic POST /batch endpoint that wraps arbitrary calls: it tunnels RPC through one URL and hides every status code.

REST API security and rate limiting

REST API security and rate limiting
Security checks and rate limits at the API gateway.

Use HTTPS only, and keep secrets out of URLs

Require TLS 1.2 or later on every endpoint, and reject plain HTTP instead of redirecting API calls. Send credentials, tokens, and API keys in headers (Authorization), never in the URL, because URLs end up in logs, browser history, and proxies. Check authorization on every resource, not only at the gateway: GET /orders/43 must fail for a user who owns only order 42. Enable CORS only for the browser origins that call you, and remove headers that reveal the server version.

I left authentication flows (OAuth 2.0, OpenID Connect) out. They deserve their own post.

Return 429 with Retry-After when a client hits the rate limit

HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json

Enforce limits per client at the API gateway, and tell the client when to come back. Also send the remaining quota on normal responses, so clients slow down before they hit the limit. The header names are still moving. The current IETF draft defines RateLimit and RateLimit-Policy. Older drafts used RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset, and gateways such as Kong still send those. Pick one set and document it.

The Idempotency-Key and RateLimit headers are still IETF drafts, so I'd expect the details to change.

REST API cheat sheet

TopicRuleExample
MaturityAim for Level 2; add hypermedia only where clients follow linksGET /orders/42 → 200, 404
ContractOpenAPI 3.1+ first, in the repo, linted and testedopenapi: 3.1.0
URLsPlural nouns, kebab-case, no verbs, no version, no extension/shipping-addresses/{addressId}
NamingcamelCase fields and parameters, Hyphenated-Pascal-Case headersorderNumber, Idempotency-Key
MethodsGET reads, PUT replaces, PATCH changes part, POST createsPATCH /orders/42
PATCH formatJSON Merge Patch by defaultapplication/merge-patch+json
Status codesThe status carries the result, never the body201 + Location, 404, 422
Media types415 for a bad Content-Type, 406 for an unmatched Accept415 Unsupported Media Type
ErrorsProblem Details; clients branch on typeapplication/problem+json
Error safetyNo stack traces; return a trace ID"traceId": "00-4bf9…"
JSONNo null booleans, [] not null, omit empty fields"items": []
Dates and codesISO 8601 UTC, ISO country/currency/language codes2026-11-09T14:07:17Z, EUR
RelationsNest or link, no loose foreign keys"customer": { "id": 7 }
PaginationAlways page; return next/prev links?limit=10 + _links.next
FilteringQuery parameters on GET; fields for sparse responses?status=open&fields=id,status
EvolutionOnly add; additions are optional; clients ignore unknown fieldsnew optional giftMessage
VersioningAvoid it; a new resource beats a new version/order-drafts
DeprecationDeprecation + Sunset headers, then removeSunset: Thu, 31 Dec 2026 …
CachingCache-Control + ETag; answer If-None-Match with 304ETag: "a7f3c2"
ConcurrencyIf-Match on writes; 412 on mismatch, 428 when missingIf-Match: "v7"
RetriesIdempotency-Key on POSTIdempotency-Key: "8e03…"
Long-running202 + task resource; poll; 303 to the resultLocation: /reports/tasks/7
BatchAtomic on the collection; no POST /batchPOST /orders with an array
SecurityTLS 1.2+, no secrets in URLs, authorize every resourceAuthorization: Bearer …
Rate limits429 + Retry-After; document the quota headersRetry-After: 30
LocalizationAccept-Language in, Content-Language outAccept-Language: en,de;q=0.8

Bonus

REST API iceberg

Comments (0)