APIs

REST API design best practices: an up-to-date guide

An up-to-date guide to REST API best practices: resources, HTTP methods and status codes, RFC 9457 errors, pagination, versioning, idempotency, security and OpenAPI.

A GET /v1/orders request and its 200 OK JSON response

An API is an interface that other people will use for years, from code you do not control. That is why design mistakes are expensive: once clients are in production, every decision becomes hard to change. This guide collects the practices that are now considered standard for designing REST APIs over HTTP, with concrete examples and the reasoning behind each one.

It brings older REST advice up to date. A lot has changed in recent years: the HTTP semantics RFCs were rewritten (RFC 9110), there is a standard error format (RFC 9457), OpenAPI 3.1 is the standard for describing contracts, and API security has its own risk ranking at OWASP. All of that is included here.

It is aimed at developers with intermediate experience who have already built at least one API. Examples are independent of language or framework.

What “REST” actually means

REST is an architectural style, not a standard. In practice, when people say “REST API” they expect the following:

  • Resources identified by URL (/orders/42), not remote functions.
  • HTTP methods with their standard semantics to act on them.
  • No server-side state between requests: each request carries what is needed (credentials, parameters) to be processed. That allows horizontal scaling.
  • Representations of the resource, normally JSON.
  • HTTP status codes and headers used for what they mean, not as decoration.

Very few APIs meet the full academic definition (which includes hypermedia, or HATEOAS). The pragmatic path is to follow the conventions above well and be consistent. A predictable API is worth more than a pure one.

Golden rule: design from the point of view of whoever consumes the API, not from how your database is organised.

1. Design the contract first

Before writing code, describe the API with OpenAPI 3.1 (YAML or JSON). The contract is the source of truth: documentation, mocks, contract tests and client SDKs all come from it. Reviewing it in a pull request is far cheaper than fixing an API that is already published.

openapi: 3.1.0
info:
  title: Orders API
  version: 1.0.0
servers:
  - url: https://api.example.com/v1
paths:
  /orders/{orderId}:
    get:
      summary: Get an order
      parameters:
        - name: orderId
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '404':
          $ref: '#/components/responses/NotFound'

Complement the contract with a linter (Spectral, for example) in CI to enforce your team’s style rules, and with contract tests that check the implementation does what is documented.

2. Resources and URLs

The URL identifies what the resource is. The HTTP method says what to do with it.

Avoid Prefer Why
POST /createOrder POST /orders The method already expresses the action
GET /getOrders GET /orders Same
GET /order/42 GET /orders/42 Collections in plural, always
GET /Orders/42/ GET /orders/42 Lowercase and no trailing slash
GET /customer_orders GET /customer-orders kebab-case in paths; avoid underscores
GET /companies/3/employees/45/orders/9/items/2 GET /order-items/2?orderId=9 Avoid nesting more than two levels

Practical rules:

  • Plural nouns for collections: /orders, /customers.
  • Nest only when it expresses clear ownership, and at most two levels: GET /customers/7/orders.
  • Opaque identifiers. Use UUIDs or other non-sequential IDs when revealing how many records you have, or letting people guess IDs, is a risk. Never assume the client interprets the ID.
  • No extensions or implementation details in the path (.php, .json, table names). The format is negotiated with the Accept header.

Actions that do not fit CRUD

Sometimes an operation is not create, read, update or delete. There are two reasonable approaches; pick one and stay consistent:

  • Model the action as a sub-resource or a state: POST /orders/42/cancellation, PUT /users/7/password.
  • Use an action endpoint when there is no good noun: POST /orders/42/actions/refund. It is a valid compromise as long as it stays the exception.

3. HTTP methods

RFC 9110 defines the semantics of each method. Two properties matter when designing:

  • Safe: does not modify server state.
  • Idempotent: repeating the same request several times leaves the server in the same state as making it once.
Method Use Safe Idempotent Request body
GET Read a resource or collection Yes Yes No
POST Create a resource or run an action No No Yes
PUT Replace a whole resource No Yes Yes
PATCH Partially modify a resource No Not necessarily Yes
DELETE Remove a resource No Yes Normally no
HEAD Same as GET but headers only Yes Yes No
OPTIONS Query allowed methods (and CORS) Yes Yes No

Points that are often confused:

  • GET must never change data. Browsers, crawlers and proxies call it freely.
  • PUT replaces; it does not “update some fields”. If the client omits a field, that field is taken to be gone. Use PATCH for partial changes.
  • PATCH can use JSON Merge Patch (RFC 7396, application/merge-patch+json), which is simple but does not distinguish null well, or JSON Patch (RFC 6902), which is more expressive. Define which one you accept.
  • DELETE is idempotent even if the second call returns 404: the end state is the same.
  • Creating with POST to the collection (POST /orders) is the usual way: the server assigns the ID. Reserve PUT /orders/{id} for when the client chooses the ID.

4. HTTP status codes

The status code is the first part of the response the client reads, and the one proxies, metrics and alerts use. Use it properly and do not return 200 with an error hidden in the body.

Success (2xx)

Code When
200 OK Successful read or update with a response body
201 Created A resource was created. Include the Location header with its URL and, ideally, the resource in the body
202 Accepted The request was accepted but is processed asynchronously (see the long-running operations section)
204 No Content Success without a body: typical for DELETE, and for PUT or PATCH that do not return the resource

Redirection and caching (3xx)

Code When
304 Not Modified Conditional request (If-None-Match): the client already has the current version
301 / 308 The resource moved permanently (308 preserves the method)

Client error (4xx)

Code When
400 Bad Request Malformed request: invalid JSON, a parameter of the wrong type
401 Unauthorized Not authenticated: credentials are missing or invalid. Include WWW-Authenticate
403 Forbidden Authenticated, but not allowed to perform that action
404 Not Found The resource does not exist, or you do not want to reveal it exists to someone without access
405 Method Not Allowed The method is not supported on that path. Include Allow
409 Conflict Conflict with current state: duplicate, invalid transition
410 Gone The resource existed and was permanently removed
412 Precondition Failed An If-Match condition failed (concurrency control)
415 Unsupported Media Type The Content-Type sent is not supported
422 Unprocessable Content Correct syntax but invalid data according to business or validation rules
429 Too Many Requests Usage limit exceeded. Include Retry-After

The difference between 400 and 422 is useful but optional: what matters is to pick a convention and apply it everywhere. Many teams use 400 for both and distinguish the reason in the error body.

And between 401 and 403: 401 means “I do not know who you are”, 403 means “I know who you are and you cannot”.

Server error (5xx)

Code When
500 Internal Server Error Unexpected failure on the server. Never return the stack trace to the client
502 Bad Gateway / 504 Gateway Timeout A service it depends on did not respond correctly or in time
503 Service Unavailable Maintenance or overload. Include Retry-After if you know it

5. Request and response format

  • JSON as the default format, with Content-Type: application/json. Validate the request’s Content-Type and Accept headers.
  • One naming style for all fields: camelCase or snake_case, but not both. Pick one and document it.
  • Dates and times in RFC 3339 / ISO 8601, in UTC: "2026-11-17T14:30:00Z". Avoid ambiguous timestamps or local formats.
  • Money: use integers in the smallest unit ("amount": 1999, "currency": "USD") or decimal strings. Floating-point numbers cause rounding errors.
  • Enumerations as readable strings ("status": "shipped"), not magic numbers.
  • Distinguish null from an absent field and document what each means, especially in PATCH.
  • Return the resource directly for single-object responses. Do not wrap it in { "data": ... } out of habit.
  • For collections, use an object rather than a bare array, because it lets you add metadata (pagination) without breaking clients:
{
  "items": [
    { "id": "ord_8f3a", "status": "shipped", "total": { "amount": 1999, "currency": "USD" } }
  ],
  "page": { "nextCursor": "eyJpZCI6Im9yZF84ZjNhIn0", "limit": 25 }
}

6. Errors: use Problem Details (RFC 9457)

Every API tends to invent its own error format. Today there is a standard: Problem Details for HTTP APIs, RFC 9457 (which replaces RFC 7807). It is served with Content-Type: application/problem+json:

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

{
  "type": "https://api.example.com/errors/validation",
  "title": "Invalid data",
  "status": 422,
  "detail": "One or more fields do not meet the validation rules.",
  "instance": "/v1/orders",
  "traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
  "errors": [
    { "field": "items[0].quantity", "message": "Must be greater than 0" },
    { "field": "email", "message": "Invalid email format" }
  ]
}
  • type: URI identifying the problem type (can point to documentation).
  • title: short summary, the same for every error of that type.
  • status: the same HTTP code as the response.
  • detail: explanation of this specific occurrence.
  • instance: identifies this occurrence.
  • Your own extensions (errors, traceId) are allowed.

Good practices with errors:

  • Return all validation errors at once, not one per attempt.
  • Helpful messages for developers and stable codes the client can process (type), not just text.
  • Do not leak internal information: no stack traces, SQL queries or server names.
  • Include a correlation identifier (traceId) you can search for in your logs.

7. Filtering, sorting, search and pagination

All of these are queries over a collection: implement them with query parameters on the GET, not with new endpoints.

GET /v1/orders?status=shipped&customerId=7&sort=-createdAt&limit=25
GET /v1/products?q=keyboard
GET /v1/orders?createdAfter=2026-01-01T00:00:00Z
  • Filters as parameters named after the field: status=shipped.
  • Sorting: sort=createdAt (ascending) and sort=-createdAt (descending). Allow several comma-separated fields. Validate against an allow list of fields.
  • Text search: q=....
  • Ranges: clear suffixes or prefixes (createdAfter, createdBefore).
  • Page size limit, with a reasonable default (20 to 50) and a maximum (for example, 100).

Pagination: offset or cursor

Offset (?page=3&limit=25) Cursor (?cursor=...&limit=25)
Simplicity High Medium
Jump to a specific page Yes No
Performance on large tables Degrades with high OFFSET Constant
Consistency when data changes Can duplicate or skip rows Stable
Recommended for Small lists and admin panels Feeds, large lists and data that changes

For large or changing collections, use cursor pagination: the server returns an opaque cursor (nextCursor) and the client sends it in the next request. Do not compute the total record count on every call if it is expensive: offer it as optional.

You can also expose links with the standard Link header (RFC 8288):

Link: <https://api.example.com/v1/orders?cursor=eyJpZCI6...>; rel="next"

If filters are so complex they do not fit in a URL, offer a search endpoint: POST /orders/search with the criteria in the body. It is a well-known exception, not the rule.

8. Versioning and evolving without breaking clients

The best versioning is not to break anything. Most changes can be made compatibly:

Compatible change (no new version needed) Incompatible change (needs a new version)
Adding a field to a response Removing or renaming a field
Adding an endpoint Changing a field’s type or meaning
Adding an optional parameter Adding a required parameter
Adding a value to an enumeration (if the contract warns it can happen) Changing status codes or error format

For this to work, clients must ignore unknown fields, and you must document that in the contract.

When you have to break compatibility:

  • Version in the URL (/v1/orders). It is the most used and the easiest to understand, debug and cache. Use the major version only.
  • Alternatives: a custom header (API-Version: 2) or a media type (Accept: application/vnd.example.v2+json). They are “purer” but harder to try from a browser or curl.
  • Keep few versions alive at once and define a support policy.
  • Announce retirement in advance. Standard headers exist: Deprecation (RFC 9745) marks a resource as deprecated and Sunset (RFC 8594) gives the retirement date.
Deprecation: @1767225600
Sunset: Wed, 01 Jul 2027 00:00:00 GMT
Link: <https://api.example.com/docs/migrating-to-v2>; rel="deprecation"

9. Idempotency and concurrency

Safe retries with Idempotency-Key

Networks fail. If a client sends POST /payments, gets no response because of a dropped connection, and retries, you could charge twice. The usual solution is an Idempotency-Key header with a unique value generated by the client (a UUID):

POST /v1/payments
Idempotency-Key: 6f1c2f9e-8b4a-4d7e-9c3a-1e2b5d7a9f10
Content-Type: application/json

The server stores the result tied to that key for some time (24 hours is common); if it receives the same key again with the same body, it returns the original response without repeating the operation. If the key is reused with a different body, it answers with an error (422 or 409). It is an established pattern in payment APIs, and an IETF draft exists to standardise it.

Offer it on every POST operation where a duplicate retry has consequences.

Optimistic concurrency control with ETag

If two clients edit the same resource, the last one can overwrite the first one’s changes. Use ETag and If-Match:

GET /v1/orders/42
→ 200 OK
  ETag: "v7"

PUT /v1/orders/42
If-Match: "v7"
→ 200 OK                      (if nobody changed it)
→ 412 Precondition Failed     (if the resource already changed: the client must re-read)

The same ETag also serves caching: with If-None-Match the server answers 304 Not Modified without sending the body.

10. Long-running operations

If an operation takes more than a few seconds (generating a report, processing a file), do not hold the connection open. Respond 202 Accepted with the URL of a status resource:

POST /v1/reports
→ 202 Accepted
  Location: /v1/reports/jobs/91

GET /v1/reports/jobs/91
→ 200 OK
  { "status": "running", "progress": 40 }

GET /v1/reports/jobs/91
→ 303 See Other  (when done: points to the result)
  Location: /v1/reports/55

To avoid constant polling, also offer webhooks signed with HMAC that notify the client when it finishes.

11. Security

Security is not a later phase: it is designed from the first endpoint. The reference is the OWASP API Security Top 10 (2023). The essential measures:

Transport and authentication

  • HTTPS only, no exceptions. Enable HSTS and reject or redirect HTTP traffic.
  • OAuth 2.0 and OpenID Connect to delegate access: Authorization Code with PKCE for user applications and Client Credentials for service-to-service communication. Do not invent your own authentication scheme.
  • API keys identify applications, they do not authenticate people. They are useful for measuring usage and limiting it; they do not replace strong authentication on sensitive operations. Store them hashed and allow rotation.
  • If you use JWT: short lifetime (minutes), validate the signature, iss, aud and exp, pin the allowed algorithm (never accept none) and keep sensitive data out of the payload, which is readable. With refresh tokens, rotate them and allow revocation.
  • Never send secrets in the URL (?token=...): they end up in logs, histories and proxies. Use the Authorization: Bearer ... header.

Authorization

  • Check authorization on every request and at object level. OWASP’s number one risk (Broken Object Level Authorization) is a user changing the ID in /orders/42 and reaching someone else’s order. Always verify that the resource belongs to the authenticated user.
  • Property-level authorization: being able to read or modify a resource does not mean being able to touch all its fields (isAdmin, price). Avoid mass assignment: never copy the received body straight into the model; use allow lists of fields.
  • Least privilege with OAuth scopes and explicit roles.

Input, abuse and exposure

  • Validate all input against a schema (type, length, format, range) and reject what is unknown. The OpenAPI contract can be used for this.
  • Limit body size and query complexity (depth, number of items).
  • Rate limiting per client or key, answering 429 Too Many Requests with Retry-After. Protect sensitive endpoints (login, password reset) with stricter limits.
  • CORS with an allow list of origins. Avoid Access-Control-Allow-Origin: * on APIs that use credentials.
  • Do not return more data than needed. Exclude passwords, hashes, tokens and internal fields.
  • Log accesses and authentication failures without storing sensitive data in the logs.
  • Keep an inventory of your APIs: forgotten old versions and exposed debug endpoints are a classic.

For the server hosting the API, also see our Ubuntu server security guide.

12. Performance and caching

  • Compression (gzip or br) for JSON responses above a certain size.
  • HTTP caching: use Cache-Control (max-age, private for user data, no-store for sensitive data) and ETag. A well-cached GET response is the fastest one.
  • Mandatory pagination on collections: never return a whole table.
  • Optional field selection (?fields=id,status) when responses are heavy and clients need little.
  • Avoid the N+1 problem on the server: load relations in batches.
  • Clear timeouts on calls to other services and to the database, and use circuit breakers so failures do not propagate.
  • HTTP/2 or HTTP/3 at the edge (proxy, load balancer): they multiplex requests and improve latency without changing your API.

13. Observability

  • Correlation: accept and propagate the W3C Trace Context traceparent header. Return the request identifier in the response and in errors.
  • Structured logs (JSON) with method, path, status, duration and the correlation identifier.
  • RED metrics per endpoint: request rate (Rate), errors (Errors) and duration (Duration, with p95 and p99 percentiles).
  • Health endpoints for the orchestrator: one for liveness (the process is alive) and one for readiness (it can take traffic, with its dependencies ready). Do not expose them publicly with internal detail.

14. Documentation and developer experience

An API without good documentation does not get adopted, or gets adopted badly.

  • Generate documentation from the OpenAPI contract (Swagger UI, Redoc, Scalar) so it never drifts from the code.
  • Include real examples of request and response for each endpoint, errors included.
  • Quick-start guide: how to get credentials and make the first call in under five minutes.
  • A sandbox environment with fictional data.
  • A public changelog and deprecation notices.
  • SDKs and collections generated from the contract (OpenAPI Generator, Postman collections).

Checklist

  • The API is described with OpenAPI 3.1 and reviewed before implementation.
  • URLs use plural nouns, lowercase, and at most two levels of nesting.
  • Each HTTP method is used with its semantics; GET does not modify data.
  • Correct status codes; never 200 with an error in the body.
  • Errors in Problem Details format (RFC 9457) with a correlation identifier.
  • Dates in RFC 3339 UTC; money as integers or decimal strings.
  • Collections paginated (cursor for large data) with a maximum limit.
  • Compatible changes by default; URL version only for breaking changes; retirement policy with Deprecation and Sunset.
  • Idempotency-Key on critical POSTs; ETag and If-Match on updates.
  • HTTPS only; OAuth 2.0 or OIDC; full token validation.
  • Object-level and property-level authorization on every request.
  • Input validation, size limits and rate limiting with 429.
  • CORS with an origin allow list; no secrets in URLs or logs.
  • Structured logs, metrics and traces with traceparent propagation.
  • Documentation generated from the contract, with examples and a quick-start.

Common mistakes

  • Verbs in URLs (/getUser, /deleteOrder): the HTTP method already expresses the action.
  • 200 OK for everything, with { "success": false } in the body. It breaks caches, metrics, alerts and generic clients.
  • Using GET for operations that change data. A crawler or a browser prefetch can run them.
  • Returning bare arrays at the root. It prevents adding pagination or metadata without breaking compatibility.
  • OFFSET pagination on huge tables. It gets slow and produces duplicates when data changes.
  • Exposing sequential IDs without checking ownership. It is the origin of OWASP’s number one API risk.
  • Error messages with stack traces or SQL. You hand information to the attacker.
  • Changing the response “just a little” without versioning. A renamed field breaks applications you do not control.
  • Inventing your own authentication instead of using OAuth 2.0 or OIDC.
  • Hand-written documentation that goes stale. Generate it from the contract.

Frequently asked questions

What is the difference between PUT and PATCH?

PUT replaces the whole resource with the representation sent. PATCH applies partial changes. If a client only wants to change a user’s phone number, PATCH is the right tool; with PUT it would have to send every other field too.

Should I use /v1 in the URL or a header?

Version in the URL is the most practical option for most teams: it is visible and easy to test and route. Headers and media types are valid but more awkward. The most important thing is not to break compatibility with unexpected changes.

Do I need to implement HATEOAS?

It is not mandatory in practice. Pagination links (Link) and Location URLs are the uses with the best return. A fully hypermedia API requires clients that take advantage of it, and few do.

REST, GraphQL or gRPC?

REST fits public and resource-oriented APIs very well, benefits from HTTP caching and is understood by everyone. GraphQL is useful when many different clients need very different data shapes. gRPC stands out for low-latency internal communication between services. They can coexist in one system.

How long should an access token last?

Briefly: 5 to 15 minutes is common, combined with a rotating refresh token. The shorter the lifetime, the less useful a stolen token is.

How do I avoid charging twice because of a retry?

With idempotency keys (Idempotency-Key) on the POST, storing the original response tied to the key for some time.

Further reading

About the author

Rootnite Engineering

Engineering team at Rootnite

The engineers behind Rootnite's custom software, automation and products. We write down the practices we use to build and run production systems so other teams can reuse them.

  • REST
  • API
  • HTTP
  • OpenAPI
  • Security
  • API design

Need a team that works this way?

We design, build and run production software with the practices described in these guides. Tell us about your project.

Contact Rootnite