Skip to content

API Design Best Practices

Intermediate 40 min read Part 4 of 18

Designing clean, evolvable APIs: resources and naming, verbs and status codes, pagination, filtering, versioning, compatibility, errors and rate-limit headers.

Summary#

A good API is predictable (consistent nouns, verbs and status codes), efficient (paginated, filterable, no huge responses), safe to retry (idempotency keys on creates), clear when it fails (one structured error format) and evolvable (additive changes, explicit versions for breaking ones). Start from the core entities, give each a resource, map user actions to methods, and paginate every list with cursors. In an interview, derive a short endpoint list from the functional requirements in about five minutes.

Why It Exists#

An API is a contract that is hard to change once clients depend on it. Mobile apps stay installed for years; partner integrations are rarely updated. A poor first design (unbounded lists, inconsistent errors, breaking changes) creates outages, support tickets and slow clients for a long time.

Most rules on this page apply to any style, but the examples use REST, the most common style for public APIs. See API Styles for when to choose gRPC or GraphQL instead.

How It Works#

The principles a reviewer checks#

Before the mechanics, the standard. When someone calls an API "clean", they are measuring it against a short list of principles that hold for any style. You will rarely be asked to recite them, but every design decision on this page is one of them applied:

  1. Model resources, not actions. Expose the things in your system and let methods say what happens to them. An endpoint named /getUserBookings or /processPayment is a sign to ask which resource is really involved: GET /users/42/bookings, POST /payments.
  2. Be consistent everywhere. Use the same names, parameters, response shapes and error format on every endpoint. If one list filters by status and another by state, developers must memorise the API instead of predicting it. Someone who has seen one endpoint should be able to guess the next.
  3. Do not surprise anyone. Use HTTP the way everyone else does: GET never changes data, DELETE deletes, and a 200 means success, not an error hidden in a body with "success": false. Every deviation costs every client a little, forever.
  4. Stay stateless. Each request carries everything needed to process it (token, parameters, payload), so any server can handle it and scaling out is a load-balancer problem rather than an application problem.
  5. Make retries safe. Networks fail mid-request, and the client cannot know whether the work happened. Its only option is to retry, so retries must be harmless: idempotent methods, plus idempotency keys on creates that matter.
  6. Paginate anything that can grow, from day one, with a maximum page size so nobody can request 100,000 rows at once.
  7. Secure by default. Every endpoint requires authentication unless deliberately marked public, authorisation checks the caller may act on this specific object, and rate limits back both up.
  8. Evolve without breaking clients. Once others depend on the API, you no longer control when they upgrade. Old mobile app versions run for years. Additive changes are safe; anything else needs a versioning plan.
  9. Make errors actionable. Use the right status code class plus a machine-readable code and a human-readable message, so the client knows what went wrong and what to do.

The way to show these in an interview is to use them as reasons, not to list them: "this booking endpoint takes an idempotency key, so a retry after a timeout cannot double-book the seat" demonstrates principle 5 better than any definition.

Resource modelling and naming#

Start from the core entities in the domain (users, posts, orders) and make each a resource:

  • Use plural nouns for collections: /orders, /orders/{orderId}.
  • Nest only for clear ownership, one level deep: /users/{id}/orders. Avoid /users/1/orders/2/items/3/reviews.
  • Use lowercase, hyphenated paths and consistent field naming (created_at or createdAt, never both).
  • Represent actions that do not fit CRUD as sub-resources or verbs on a resource: POST /orders/{id}/cancel, POST /payments/{id}/refunds.
  • Use opaque, stable IDs (ord_8f3k2) rather than exposing auto-increment database IDs.

Resource modelling in depth#

Start from the core entities. If you have listed the core entities of the problem (for a ticketing product: Event, Venue, Ticket, Booking, User), you have most of your resources already. Each entity becomes a collection (/events) and individual items within it (/events/123).

Required versus optional relationships. The choice between nesting and query parameters follows one question: is the parent required for the request to make sense?

  • Required, so put it in the path: /events/123/tickets always concerns one event.
  • Optional, so make it a filter: /tickets?event_id=123&section=VIP could be called with any subset of filters.

A child that also makes sense on its own gets a top-level URL as well: a booking is created under its event (POST /events/123/bookings) but read directly (GET /bookings/555), because the client holding a booking ID should not need to know its event.

Singletons and the current user. /users/me (or /me) names "whoever is authenticated", so clients never need to put their own ID in URLs, and the server takes identity from the token. Some resources exist exactly once per parent, such as /users/me/settings or /orders/981/shipping-address, and are read and replaced with GET and PUT, with no ID.

Identifiers.

OptionExampleStrengthsWeaknesses
Auto-increment integer981Small, ordered, simpleReveals volume (competitors can count your orders), easy to enumerate, hard to generate across shards
Random UUID (v4)3f6c9b1e-...Unique anywhere, unguessable36 characters, random order hurts B-tree index locality on insert
Time-ordered (UUIDv7, ULID, Snowflake-style)01JD3Q...Unique, roughly sorted by creation time, index-friendlyReveals approximate creation time
Prefixed opaque stringord_8f3k2LqThe type is visible in logs and support tickets, and mixing up IDs of different types becomes obviousSlightly longer, needs a convention

Return IDs as strings in JSON even when they are numbers internally. JavaScript represents all numbers as 64-bit floating point, which is exact only up to 2^53 (about 9 × 10^15), so a 64-bit Snowflake-style ID can be silently corrupted in a browser. Twitter's API added string versions of its IDs (id_str) for exactly this reason.

Naming conventions. Choose once and apply everywhere: plural nouns for collections, lowercase hyphenated path segments (/payment-methods), one field-naming case (snake_case or camelCase, never both), the same name for the same concept (created_at on every resource, not created here and creation_date there), and booleans named as questions (is_active, has_more).

Actions that do not fit. For cancel, refund, resend or archive, prefer, in this order: a state change (PATCH with a new status), a new resource that represents the action (POST /payments/77/refunds, which also gives you a refund ID, history and its own status), or an explicit action sub-resource (POST /orders/981/cancel). The second option is often the best design, because real actions tend to need an identity, an audit trail and a status of their own.

HTTP verbs and status codes#

ActionRequestSuccessCommon errors
ListGET /orders?status=open200400 invalid filter
ReadGET /orders/{id}200 (304 if ETag matches)404
CreatePOST /orders + Idempotency-Key201 + Location400, 409, 422
ReplacePUT /orders/{id}200404, 412 version mismatch
UpdatePATCH /orders/{id}200404, 409, 422
DeleteDELETE /orders/{id}204404
Async actionPOST /exports202 + status URL429

Use 401 for "not authenticated", 403 for "authenticated but not allowed", 409 for conflicts, 422 for valid JSON that breaks business rules, 429 for rate limits, and 503 when temporarily unavailable. See HTTP and HTTPS.

Status codes in depth#

The status code is the first thing clients, proxies, monitoring and retry logic look at, so choosing it well matters more than the message.

Success codes, chosen precisely:

  • 200 OK: success with a body, the default for GET, PUT and PATCH.
  • 201 Created: a new resource exists; include Location: /orders/981 and usually the resource itself.
  • 202 Accepted: the request is valid and queued, but not done yet. Return a link to an operation or job resource to poll.
  • 204 No Content: success with nothing to return, typical for DELETE.
  • 304 Not Modified: the response to a conditional GET whose ETag still matches; no body, so it saves bandwidth.

Client errors, and the distinctions people confuse:

  • 400 Bad Request means the request is malformed (invalid JSON, wrong types, a missing required field). 422 Unprocessable Content means it is well formed but breaks a rule ("quantity exceeds stock"). Many APIs use 400 for both, which is acceptable if the error body explains.
  • 401 Unauthorized means "who are you?": missing, invalid or expired credentials. 403 Forbidden means "I know who you are, and you may not do this".
  • 404 Not Found is also the right answer when a user asks for an object that exists but belongs to someone else. Returning 403 there would confirm that the ID exists, which leaks information.
  • 409 Conflict covers clashes with current state: a duplicate unique value, or a booking for a seat that was just taken. 412 Precondition Failed is specifically for a failed If-Match check, meaning someone else changed the resource since you read it.
  • 429 Too Many Requests means rate limited; include Retry-After.

Server errors: 500 for unexpected failures, 502 and 504 for bad or slow upstreams (usually produced by gateways and proxies), and 503 Service Unavailable for deliberate refusal during overload or maintenance, ideally with Retry-After.

Why the class matters more than the exact code. Clients and libraries decide what to do from the first digit. A 4xx means "do not retry the same request; change it first" (except 429 and sometimes 409). A 5xx means "the failure was ours; retrying later may work". Retrying a 400 forever wastes everyone's capacity; failing to retry a 503 turns a blip into an outage. An API that returns 500 for validation errors breaks this contract and also sets off on-call alerts for problems that are really client bugs.

Conditional requests use the same machinery that powers browser caches:

  • Reads: the server sends ETag: "v7"; the client later sends If-None-Match: "v7", and an unchanged resource returns 304 with no body. Mobile clients polling for changes save most of their bandwidth this way.
  • Writes: the client sends If-Match: "v7" with its update. If the resource is now at "v8", the server returns 412 instead of overwriting someone else's change. This is optimistic concurrency control over HTTP, and it prevents the "lost update" problem without locks.

Request and response shape#

  • JSON with consistent naming and types; money as integer minor units (total_cents: 4999) plus currency, never floats.
  • Timestamps in ISO 8601 UTC (2026-12-01T10:15:00Z).
  • Return the created or updated resource in the response, so the client does not need another GET.
  • Keep a consistent envelope for lists: data plus pagination info.
  • Allow field selection (?fields=id,status) or expansions (?expand=customer) for heavy resources.

Request and response shape in depth#

Where each kind of input goes. Path parameters say which resource (structural and required). Query parameters modify how a resource is fetched (optional filters, sorting, pagination, switches). The body carries the data being created or changed. Headers carry metadata: credentials, content type, idempotency keys, conditional checks, tracing IDs. A booking request shows all four:

POST /v1/events/123/bookings?notify=email
Authorization: Bearer eyJhbGciOi...
Idempotency-Key: 9b2e7c4a-61f0-4d1e-8f55-0c2a7b9d1e33
Content-Type: application/json
 
{ "seats": [ { "section": "VIP", "quantity": 2 } ], "payment_method_id": "pm_77" }

Bare objects or envelopes? For single resources, returning the object itself is simplest. For lists, use an envelope that leaves room for pagination and metadata:

{
  "data": [ { "id": "evt_1", "name": "Cup final" }, { "id": "evt_2", "name": "Jazz night" } ],
  "has_more": true,
  "next_cursor": "ZXZ0XzI"
}

Returning a bare JSON array for lists is a trap: you cannot add pagination fields later without breaking clients.

Data types that cause bugs:

  • Money: integers in the smallest currency unit plus an ISO 4217 currency code ("amount": 4999, "currency": "EUR"). Floating point cannot represent 0.10 exactly, and currencies differ in their number of decimal places (the Japanese yen has none).
  • Time: ISO 8601 in UTC with an explicit zone (2026-12-01T10:15:00Z). For things that happen at a local time, such as a concert starting at 19:30 in Paris, also store and return the time zone name (Europe/Paris), because offsets change with daylight saving.
  • Enums: strings ("status": "shipped"), not integers whose meaning lives in documentation. Tell clients to expect new values and to handle unknown ones gracefully.
  • Null versus absent: decide and document. In responses, include fields with null rather than omitting them unpredictably. In PATCH requests, absent means "do not change" and null means "clear this field".
  • Large integers and IDs: strings, for the JavaScript precision reason above.

Partial updates. Two standards exist. JSON Merge Patch (RFC 7396) sends an object with only the fields to change, and null deletes a field. It is simple and covers most cases. JSON Patch (RFC 6902) sends a list of operations (add, remove, replace, move, test) addressed by path, which handles arrays precisely and can include a test operation as a precondition. Most APIs use merge-patch semantics, usually without naming them.

Returning the result. After a create or update, return the full new state of the resource, including fields the server computed (ID, timestamps, status, totals), so the client does not need a second request and does not guess.

Large and binary data. Do not send multi-megabyte files through JSON APIs. Return a signed URL for uploading straight to object storage, then let the client confirm the upload with a small API call. Downloads work the same way in reverse.

Pagination: offset, cursor and keyset#

Every list endpoint must be paginated; an unbounded list will one day return a million rows.

MethodRequestProsCons
Offset?limit=20&offset=40Simple, jump to page NSlow at deep offsets (DB scans skipped rows); items shift when data changes
Cursor?limit=20&cursor=eyJpZCI6...Stable under inserts, fast at any depthNo "jump to page 50"; cursor is opaque
Keyset (seek)?limit=20&after_created=...&after_id=...The SQL technique behind cursors; uses an indexRequires a unique, ordered sort key

A cursor is usually an encoded keyset position. The query "seeks" past the last row seen using an index, so page 1,000 is as fast as page 1:

-- Index: (user_id, created_at DESC, id DESC)
SELECT id, total_cents, status, created_at
FROM orders
WHERE user_id = $1
  AND (created_at, id) < ($2, $3)      -- position from the decoded cursor
ORDER BY created_at DESC, id DESC
LIMIT 21;                              -- fetch 1 extra to know if there is a next page

The response returns next_cursor (the last row's created_at and id, base64-encoded) and has_more. Including id breaks ties when timestamps are equal.

Pagination in depth#

Why offset breaks down, with numbers. SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 1000000 asks the database to find and throw away a million rows before returning 20. Even with an index on created_at, it walks a million index entries; on a busy table that can take hundreds of milliseconds to seconds, and it gets worse with every page. Most users never go that deep, but crawlers, exports and integrations do.

Why offset shows duplicates and gaps. A user reads page 1 (items 1-20 of a newest-first feed). Three new items are inserted. Page 2 with offset=20 now starts at what used to be item 18, so the user sees items 18-20 twice. Deletions cause the opposite: items are skipped. For a feed that changes constantly, this is visible and confusing.

How cursors fix both. A cursor records where the last page ended, as the sort-key values of the last row, so the next query starts from that point using the index:

New rows inserted at the top do not shift the position, and page 1,000 costs the same as page 1.

Designing cursors well:

  • Make them opaque. Encode the position (base64 of the sort values, or an encrypted token) and document it as "pass back what we gave you". Clients that parse cursors would break the day you change the encoding.
  • Always include a unique tiebreaker (the ID) after the sort key. Without it, rows with identical timestamps can be skipped or repeated at page boundaries.
  • Bind the cursor to the query. If a client changes the filters but sends an old cursor, reject it with a 400 rather than returning nonsense. Including a hash of the filters in the cursor makes this check easy.
  • Sign or encrypt cursors if they contain anything a client must not tamper with.
  • Defaults and caps: a default page size (such as 20 or 50) and a maximum (such as 100 or 200), enforced on the server.
  • has_more instead of a total count. Counting all matching rows in a large table can cost more than fetching the page. Fetch one row more than the limit to learn whether another page exists. Offer counts only where they are cheap, or provide an estimate.
  • Both directions if the UI needs "previous": encode the direction, or return both next and previous cursors. Stripe's starting_after and ending_before parameters are an example.

Feeds that grow at the top. For "show me what is new since I last looked", give clients a way to ask for items newer than a known one (a since cursor or a newer_than ID), separate from paging backwards through history. Chat and notification APIs need both.

Choosing. Offset pagination is fine for small, slow-changing collections and for admin screens that need page numbers. Cursor pagination is better for large or fast-changing collections, infinite scroll, public APIs and data exports. In an interview, remembering to paginate matters far more than which method you choose; mention cursors when the data is large or changes in real time, or when asked.

Filtering and sorting#

  • Filter with query parameters: ?status=open&created_after=2026-11-01.
  • Sort with an explicit parameter: ?sort=-created_at (minus for descending).
  • Only allow filters and sorts you have indexes for; an arbitrary sort on a large table is a hidden full scan. Document the allowed list and return 400 for others.
  • For complex search (full text, many facets), use a search endpoint backed by a search engine rather than overloading the list endpoint.

Filtering and sorting in depth#

One convention, everywhere. Filters are query parameters named after fields (?status=upcoming&city=NYC), and sorting uses one parameter with a minus for descending order (?sort=-starts_at). The design effort goes into consistency: if events filter by status, bookings must too, never state. In an interview, show one filtered endpoint and say the same conventions apply across the API.

Ranges and multiple values need a convention as well. Common choices are suffixes (created_after, created_before, price_min), bracket operators (created_at[gte]=2026-11-01, used by several large APIs), or comma-separated values for "any of" (status=open,paid). Pick one style and document it.

Keep queries backed by indexes. Every allowed filter and sort combination is a query the database must answer quickly at full scale. Offer only the combinations you have indexes for, reject others with a clear 400, and add new ones deliberately. A free-form sort on any column of a 500-million-row table is a hidden full scan waiting for a client to discover it.

Stable sorting. Sorting by a non-unique field (price, name) must add a tiebreaker (ID), or pages will overlap and items will move between requests. This is the same rule as for cursors.

When filtering becomes search. Full-text matching, relevance ranking, typo tolerance, facets ("120 results in Rock, 45 in Jazz") and geographic queries belong in a search endpoint backed by a search engine such as Elasticsearch or OpenSearch, not in ever more list parameters. Very complex filter expressions can be sent in the body of POST /events/search. This is not a pure REST read, but it is widely used and avoids URLs that exceed length limits.

Versioning strategies#

StrategyExampleProsCons
URL path/v1/ordersObvious, easy to route and cacheVersion applies to whole API
HeaderAccept: application/vnd.shop.v2+jsonClean URLs, per-resource versionsLess visible, harder to test in a browser
Query parameter/orders?version=2Easy to tryEasy to forget, messy caching
Date-basedApi-Version: 2026-11-01Fine-grained, pins each client to a snapshotServer must maintain transformations between versions

URL versioning is the most common choice for public APIs. Stripe is a well-known example of date-based versioning, where each account is pinned to the version it first used.

Versioning in depth#

Version as rarely as possible. A new version doubles the surface you must run, test, document and secure. Most change should be additive and need no version at all. Versions are for breaking changes you cannot avoid.

How versions are served. Two broad implementations exist:

  • Separate code paths per major version: the gateway routes /v1 and /v2 to different handlers or services. This is simple to understand, but bug fixes must be applied to each version, and old versions rot.
  • One current implementation plus translation layers: requests and responses for older versions pass through small transformations that convert between the old and current shapes. Stripe has described working this way: each dated version is a set of transformations applied to responses, so the core code only knows the newest shape, and each account is pinned to the version it integrated with until it chooses to upgrade.

The deprecation lifecycle. A responsible removal looks like this:

  1. Announce the change and the date in a changelog, documentation and email to affected API key owners.
  2. Mark responses from the old version with a Deprecation header and a Sunset header (RFC 8594) giving the removal date, and link to a migration guide.
  3. Measure who still calls the old version, per API key or client version, and contact the largest users directly.
  4. Optionally run "brownouts", short planned periods when the old version returns errors, so forgotten integrations are found before the final date.
  5. Remove the old version on the announced date.

Public APIs commonly give 6-24 months. Mobile apps make this harder, because an app version installed two years ago still calls your API. Many companies therefore force upgrades for very old app versions, or keep the mobile-facing API stable behind a Backend-for-Frontend while services behind it change freely.

In an interview, /v1/ in the paths is enough, and many good answers omit versioning entirely. That reflects what interviewers prioritise, not that versioning is unimportant in real systems.

Backward compatibility#

Most changes should not need a new version. Safe (additive) changes: adding a new endpoint, a new optional request field, a new response field, or a new enum value that clients are told to tolerate. Breaking changes: removing or renaming fields, changing types or meaning, making an optional field required, changing default behaviour or error codes.

Rules that keep clients working: clients ignore unknown fields; servers never remove fields without a deprecation period; announce deprecations with a Deprecation or Sunset header and docs; track which clients still call old versions before removing them.

Backward compatibility in depth#

The tolerant reader. The cheapest compatibility rule is for clients: ignore fields you do not recognise, and do not fail on new enum values. Servers do the matching half: never remove or change what exists. State this in your documentation so that clients written later follow it.

Hyrum's law. Hyrum Wright of Google observed that, with enough users, every observable behaviour of an API will be depended on by somebody, whatever the documentation promises. Field order, the exact wording of error messages, the default sort order and response timing all end up in someone's code. Hence the rules: document what is guaranteed, avoid leaking what is not (for example, by sorting results explicitly instead of returning them in whatever order the database produced), and treat behaviour changes as carefully as schema changes.

Expand, then contract. To rename zip to postal_code without a new version:

  1. Expand: add postal_code, accept both on input, return both on output.
  2. Migrate: update the SDKs and documentation, and tell clients to switch.
  3. Measure reads of zip and writes using it, per client.
  4. Contract: stop returning zip only when usage is near zero, or keep it forever if removing it is not worth the risk.

The same pattern works for moving data between databases and for protobuf and GraphQL fields.

Changes that are breaking even though they look safe:

  • Adding a required request field.
  • Making validation stricter, such as a shorter maximum length.
  • Changing a default (page size, sort order, the currency assumed).
  • Returning a new error code for a situation clients already handle.
  • Turning a synchronous operation into an asynchronous one (200 becomes 202).
  • Adding a value to an enum that clients use in a switch without a default case.

The last one is technically additive but breaks real clients, which is why the tolerant reader rule must be stated clearly.

Contract testing in CI. Diff each new OpenAPI document against the published one (openapi-diff, oasdiff and similar) and fail the build on breaking changes unless they are explicitly approved. Consumer-driven contract tests (Pact) catch the behavioural changes that schemas miss.

Error format#

Use one structured error shape everywhere, with a machine-readable code and a human message. A common standard is RFC 9457 "Problem Details":

{
  "type": "https://api.shop.example/errors/insufficient-stock",
  "title": "Insufficient stock",
  "status": 422,
  "code": "insufficient_stock",
  "detail": "Only 2 units of sku_123 are available.",
  "errors": [{ "field": "items[0].quantity", "message": "must be <= 2" }],
  "request_id": "req_7Hk29a"
}

Include a request_id so support can find the request in logs. Never leak stack traces or internal hostnames.

Error format in depth#

Status codes give the category of failure; the body says exactly what happened and what to do. The essential parts are:

  • A stable, machine-readable code that client code branches on. If a booking fails with seat_unavailable, the app can reopen the seat picker; on payment_declined, it can ask for another card. Codes are part of the contract, so never rename them.
  • A human-readable message for developers and logs. It may change at any time, so clients must not parse it. Messages shown to end users should be produced by the client from the code, in the user's language.
  • Field-level details for validation errors, listing every invalid field at once instead of one per round trip.
  • A request ID, echoed in a response header too, which support teams can look up in logs and traces.
  • Retry guidance where useful: Retry-After on 429 and 503, or a retryable flag.

Keep the shape identical on every endpoint, including errors produced by gateways and load balancers, so clients write error handling once. RFC 9457 Problem Details (the successor to RFC 7807) is a ready-made standard shape, and many teams extend it with their own code field. In an interview this is one sentence: "errors use one envelope with a machine-readable code and a message".

What not to return: stack traces, SQL fragments, internal host names or library versions. They help attackers and confuse clients. Log those details on the server, tagged with the request ID.

Idempotency keys#

POST is not idempotent, so a retried "create order" after a timeout can create two orders. Clients send an Idempotency-Key header (a UUID); the server stores the result per key and returns the same response on a retry. See Idempotency.

Idempotency keys in depth#

A favourite interview scenario: the user taps "Buy", the request times out, and the app retries. Did the first attempt succeed? If it did and the server processes the retry too, the user has two bookings and two charges. "Do not retry" is not an answer, because timeouts happen every day at scale.

The details that make it work:

  • The client generates the key (a UUID) once per logical operation and reuses it for every retry of that operation.
  • Keys are scoped to the caller (API key or user), so two customers cannot collide.
  • The server stores the key with the request's fingerprint and the response, usually for about 24 hours. A retry with the same key and a different body is a client bug and gets a 422 or 409 rather than the old response.
  • Concurrent duplicates: if a retry arrives while the first attempt is still in progress, return 409 (or wait briefly) rather than running it twice.
  • Atomicity: recording the key and creating the booking should happen in one database transaction where possible, so a crash between them cannot leave a booking without its key.

Mention idempotency keys whenever a design has payments, bookings or orders. It shows you are designing for failure, not only for the happy path. Stripe's API popularised this exact header. The full mechanics are in Idempotency.

Rate-limit headers#

Tell clients their limits so they can slow down before being blocked:

HTTP/1.1 429 Too Many Requests
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30
Retry-After: 30

Many APIs use X-RateLimit-* names; an IETF draft standardises RateLimit-*. See Rate Limiting.

Reading the headers as a client. RateLimit-Remaining tells a well-behaved client to slow down before it hits zero. RateLimit-Reset (seconds until the window resets) and Retry-After on a 429 tell it exactly when to try again, which beats blind exponential backoff. Return the headers on every response, not only on 429s, so clients can pace themselves. If different endpoints have different limits, the IETF draft lets a server describe several policies, and many APIs simply document a limit per endpoint group. Never let rate-limit responses depend on expensive work: the check should run before authentication-heavy or database-heavy processing, so a flood of rejected requests stays cheap.

Security in the API design#

In most interviews, authentication and authorisation are not the focus. Say which endpoints need a signed-in user, that you will use JWTs or server-side sessions, and move on. You should still know the main options and where they fit.

Authentication: API keys or tokens.

  • API keys are long random strings that identify an application, not a person. The server looks the key up (store only a hash, like a password) to find the client, its permissions and its rate limits. They suit server-to-server calls and third-party developers integrating programmatically. They are the wrong choice for end users: people should not manage long secrets, and keys do not expire or carry session context.
  • JWTs (JSON Web Tokens) are signed tokens that carry claims such as the user ID, role and expiry. Any service with the verification key can check the signature and read the claims without a database lookup, which suits distributed systems: the gateway verifies the token and passes the identity on. The trade-off is revocation. A JWT stays valid until it expires, so keep access tokens short-lived (minutes) and pair them with refresh tokens, or keep a deny-list for urgent revocation.
  • Server-side sessions store a random session ID in a cookie, with the state in a store such as Redis. They are easy to revoke, at the cost of a lookup per request.
GET /v1/users/me/bookings
Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1XzEyMyIsInJvbGUiOiJjdXN0b21lciIsImV4cCI6MTc2NzIyNTYwMH0.sig

Authorisation: roles and ownership. Role-based access control (RBAC) assigns permissions to roles and roles to users. For ticketing: customers book and view their own bookings, venue managers create events and see sales for their venues, and admins can do everything. Every request then answers two questions: is the caller authenticated (a valid token), and may this caller act on this object (they own booking 555, manage this venue, or are an admin)? The second check, at the level of the individual object, is the one most often forgotten. Broken object-level authorisation, where changing an ID in the URL reveals someone else's data, is the top item on the OWASP API Security Top 10. In an interview, a sentence on which roles can call which endpoints is usually plenty.

Rate limiting and throttling. Limits protect the system from abuse and from accidents (a client stuck in a retry loop). Typical layers:

  • Per authenticated user or API key: for example 1,000 requests per hour.
  • Per IP address for anonymous traffic: stricter, for example 100 per hour.
  • Per endpoint for sensitive actions: for example 10 booking attempts per minute against scalping bots, or 5 login attempts per minute against password guessing.

Limits are usually enforced at the API gateway or in middleware. Over the limit, return 429 with Retry-After and the rate-limit headers below. In an interview, "rate limiting at the gateway, per user and per IP" is normally enough unless the interviewer wants the algorithms.

Deriving an API from core entities in an interview#

Example, a ticket booking product. Requirements: browse events, view one event's seats, reserve seats, pay to confirm.

GET  /v1/events?city=london&date_from=2026-12-01&cursor=...   -> list events (paginated)
GET  /v1/events/{eventId}                                     -> event details
GET  /v1/events/{eventId}/seats?section=A                     -> seat map with availability
POST /v1/bookings            {eventId, seatIds}               -> 201 hold seats for 10 min
                             Idempotency-Key: 6f1c...
POST /v1/bookings/{bookingId}/confirm  {paymentToken}         -> 200 confirmed booking
GET  /v1/bookings/{bookingId}                                 -> booking status
GET  /v1/users/me/bookings?cursor=...                         -> my bookings
Auth: Bearer token; user identity comes from the token, never from the request body.

Note that the user ID comes from the auth token, not from the body: trusting a client-supplied userId is a classic security bug.

More worked derivations#

The same routine works for any product: requirement, entity, resource, method, then the cross-cutting additions.

URL shortener. Requirements: create a short link, optionally with a custom alias and an expiry; redirect visitors.

POST /v1/urls            body: long_url, custom_alias?, expires_at?   -> 201 short_url, code
GET  /:code                                                           -> 302 Location: long_url
GET  /v1/urls/:code/stats                                             -> click counts (owner only)

The redirect is not part of the JSON API: it lives at the root of the short domain, answers with a 302 (or 301 if analytics do not matter, since browsers cache 301s) and must be extremely fast, so it is served from a cache or CDN.

Chat. Requirements: create conversations, send messages, load history, receive messages live.

POST /v1/conversations                     body: member_ids          -> 201 conversation
POST /v1/conversations/:id/messages        body: text, client_msg_id -> 201 message
GET  /v1/conversations/:id/messages?before=cursor&limit=50           -> older messages
WebSocket /v1/live                         server pushes new messages, typing, receipts

Sending through REST or through the socket are both reasonable; the client_msg_id makes retries safe either way. History uses cursor pagination backwards from the newest message. Live delivery is a persistent connection, not a REST endpoint. See Real-time Communication.

News feed. Requirements: post, follow, read a feed.

POST   /v1/posts                           body: text, media_ids     -> 201 post
POST   /v1/users/:id/followers             (follow; the caller comes from the token) -> 201
DELETE /v1/users/:id/followers/me          (unfollow)                -> 204
GET    /v1/feed?cursor=...&limit=20                                  -> posts for the caller

The feed is a cursor-paginated read of a precomputed or merged timeline; media is uploaded beforehand through signed URLs to object storage, and the post only references media IDs.

Common mistakes in derivations: putting user_id in the body or path for the caller's own data; verbs in paths; forgetting pagination on lists; designing internal service APIs nobody asked for; and spending fifteen minutes on endpoint details. Five minutes and a short, consistent list is the target.

When to Use It#

  • Designing any new public, partner or internal HTTP API.
  • Reviewing an API before release; changes after release are expensive.
  • In interviews, right after requirements and core entities, before the high-level design.

When NOT to Use It#

  • Do not over-design internal APIs between two services owned by one team; keep them simple but still paginated and consistent.
  • Do not spend more than ~5 minutes on endpoint details in an interview; cover the core endpoints and move on.
  • Do not force resource-style REST onto workloads that are really streams or calls. Live updates belong on WebSockets or server-sent events, high-volume internal calls often fit gRPC better, and screens that combine many entities may fit GraphQL or a backend-for-frontend. The principles on this page still apply to those styles: consistent naming, explicit errors, pagination, idempotent writes and careful evolution. See API Styles for choosing between them.
  • Do not publish a public API before you know who will call it. Every public field is a promise you may have to keep for years.

How to Implement It#

  1. List core entities from the requirements and make each a resource.
  2. Map each user action to a method and path; use sub-resources for non-CRUD actions.
  3. Define request and response bodies with consistent naming, types and money handling.
  4. Paginate every list with cursors; whitelist indexed filters and sorts.
  5. Add idempotency keys to creates and payments, a standard error format, and rate-limit headers.
  6. Write an OpenAPI spec, generate docs and SDKs, and add contract tests so changes stay backward compatible.
TechnologyFits when
OpenAPI 3 + Swagger UI / RedocSpecifying and documenting REST APIs
Spectral, openapi-diffLinting specs and detecting breaking changes in CI
Postman, BrunoExploring and testing endpoints
Kong, AWS API GatewayEnforcing auth, rate limits and versions at the edge

Trade-offs#

ChoiceGainCostPick when
Offset paginationPage numbers, simpleSlow deep pages, unstable resultsSmall admin tables
Cursor paginationFast and stable at any depthNo random page accessFeeds, large lists, public APIs
URL versioningVisible, simple routingCoarsePublic APIs
Date/header versioningFine-grained evolutionServer complexityLarge platforms with many clients
Rich expansions (?expand=)Fewer round tripsHarder caching and performance limitsMobile clients, heavy resources
Thin vs fat webhooksThin: never stale; fat: one fewer callThin: extra fetch; fat: ordering issuesThin for state changes, fat for logs
Header vs URL versioningHeader: clean URLs, fine-grainedURL: visible, simple to route and cacheURL for public APIs, dates for Stripe-style

Common Pitfalls#

  • Unpaginated list endpoints.
  • Verbs in URLs (/getOrders, /createUser) instead of methods on resources.
  • Returning 200 with {"error": ...} in the body.
  • Accepting the user ID from the request body instead of the auth token.
  • Floating-point money, inconsistent timestamp formats, or breaking changes shipped without a version.
  • Returning object IDs as JSON numbers above 2^53, which JavaScript clients silently round.
  • Treating 4xx and 5xx the same in clients, so they retry validation errors forever or never retry real outages.
  • Sending webhook deliveries without signatures, or receivers that process duplicates twice.

Real-World Examples#

Stripe's public API is widely cited for consistent resource naming, idempotency keys on POST requests, cursor-based pagination (starting_after) and date-based versioning.

GitHub's REST API returns rate-limit information in X-RateLimit-* response headers on every request.

  • Google publishes API design guidance (the AIP documents) covering resource names, standard methods, custom methods with a colon suffix, and long-running operations.
  • Twitter added string IDs (id_str) next to numeric IDs because its 64-bit IDs lost precision when JavaScript parsed them.

In the Interview#

Where the API step fits in an interview#

In a typical structured approach, you clarify requirements, list core entities, define the API, and then draw the high-level design. The API step turns each functional requirement into one or two endpoints and gives the rest of the interview a shared vocabulary. Spend about five minutes on it. Candidates more often hurt themselves by spending too long on API details than too little. Front-end, product and junior roles may get more API questions, because those roles work with APIs every day.

What a strong API step contains:

  • The style in one sentence (REST unless there is a reason).
  • One endpoint per user action, written as method, path, key inputs and output.
  • The user taken from the auth token, never from the body.
  • Pagination on lists, and an idempotency key on bookings and payments.
  • A sentence on errors and rate limiting if time allows.

What it should not contain: every status code, every field, internal service APIs, or a debate about URL style.

Follow-up questions to expect#

  • "Page 500 of search results is slow." Offset scans skipped rows; switch to keyset or cursor pagination, or cap the depth and ask users to refine the search.
  • "Two admins edit the same event at once." ETags with If-Match and 412 responses for optimistic concurrency.
  • "Mobile clients on old versions break after a release." Additive changes only, a tolerant-reader rule, a BFF for mobile, and deprecation headers with usage tracking.
  • "An export takes ten minutes." 202 Accepted with a job resource to poll or a webhook on completion, and a signed URL to download the result.
  • "How do clients know they are being rate limited?" 429 with Retry-After and RateLimit-* headers on every response.
Deep Dive: Consistency, long-running operations and API governanceShow

Optimistic concurrency. Return an ETag (or version field) with each resource; clients send If-Match on updates. If someone else changed it first, return 412 and let the client re-read. This prevents lost updates without locks, which matters for collaborative edits and admin tools.

Long-running operations. For work taking more than a few seconds (exports, video processing), return 202 Accepted with an operation resource (/operations/{id}) that clients poll, or notify them by webhook. Never hold an HTTP request open for minutes.

Bulk endpoints. Clients that create 10,000 items one call at a time hit rate limits and waste round trips. Offer batch endpoints with per-item results, and define whether a batch is all-or-nothing or partial.

Partial responses and sparse fieldsets reduce payloads for mobile clients, but every combination must be supported and tested, and caching gets harder. Many teams prefer a BFF that returns screen-shaped responses instead.

Governance at scale. Large organisations publish an API style guide (naming, errors, pagination, versioning), lint every spec in CI, and review new APIs. Consistency across hundreds of services is what makes a platform easy to use; without it, every team's API feels different.

HTTP caching for APIsShow

Most API traffic is reads, and HTTP already defines a full caching model that browsers, CDNs and reverse proxies understand. Using it well can remove most repeated reads from your servers.

Cache-Control decides who may cache and for how long. Cache-Control: public, max-age=60 lets any cache, including a CDN, keep the response for a minute. private limits caching to the end user's browser, which is right for anything personalised. no-store forbids caching entirely, which is right for secrets and payment details. s-maxage sets a separate lifetime for shared caches only. stale-while-revalidate=30 lets a cache serve a slightly old copy while it fetches a fresh one in the background, which hides refresh latency from users.

Validators make revalidation cheap. When a cached copy expires, the client sends If-None-Match with the stored ETag. If nothing changed, the server answers 304 Not Modified with no body. That still costs a round trip but saves bandwidth and serialisation. A cheap ETag is a version number or an update timestamp from the row; hashing the whole serialised body works but still means doing the work you wanted to avoid.

Vary prevents serving the wrong variant. If the response depends on a header such as Accept-Language or Authorization, the Vary header must list it, or a shared cache may hand one user's response to another. The safest rule: never let shared caches store authenticated, per-user responses. Make public data public and cacheable, and keep private data private.

Design endpoints to be cacheable. Caching works best when URLs are stable and responses are the same for everyone. A public product page at GET /v1/products/123 caches well. The same data mixed with "is this in my cart" does not, so split the personal part into its own call. Query-string order matters to many caches, so normalise parameters. Rich ?expand= options multiply the number of distinct URLs and reduce hit rates.

Invalidation remains the hard part. Short TTLs plus stale-while-revalidate are the simplest approach. When a change must show up immediately, purge the CDN by URL or by tag on write. See CDN for purge mechanics and HTTP and HTTPS for the protocol details.

A worked number. A product API serves 20,000 reads per second on a few thousand hot products. With a 60-second shared-cache TTL and a 95% CDN hit rate, the origin sees about 1,000 requests per second. That is twenty times less capacity to provision, and the hot keys get a latency of tens of milliseconds from the edge.

Bulk, asynchronous and webhook API patternsShow

Simple CRUD endpoints stop fitting once operations get large, slow or event-driven. Three patterns cover most of these cases.

Bulk endpoints. Creating 10,000 records with 10,000 requests wastes round trips and makes rate limits painful. A batch endpoint such as POST /v1/contacts:batchCreate accepts an array and returns a result per item. You must decide what happens when some items fail:

  • All-or-nothing: one transaction, simple meaning, but one bad row rejects the whole batch.
  • Partial success: the response lists each item's status, often with an overall 207 Multi-Status or a 200 whose body holds per-item errors.

Cap the batch size, for example 100 to 1,000 items, so one request cannot hold a database transaction for minutes. Give each item its own idempotency key, or give the whole batch one, so a retried batch cannot create duplicates.

Long-running operations. When work takes longer than a request should stay open (a few seconds at most), accept it and hand back a job:

POST /v1/reports            -> 202 Accepted, Location: /v1/operations/op_77
GET  /v1/operations/op_77   -> state: running, progress: 40
GET  /v1/operations/op_77   -> state: succeeded, result_url: signed link

The operation resource has a small state machine (pending, running, succeeded, failed, cancelled) and may support POST /v1/operations/op_77:cancel. Google's API design guidance describes a standard long-running operation resource along these lines. Clients poll with backoff, or subscribe to a webhook so they do not have to poll at all.

Webhooks. A webhook is an HTTP callback: your server calls a URL the customer registered whenever an event happens, such as payment.succeeded. Webhooks turn polling into push, but they invert the reliability problem, because now you are the client of someone else's server. Production webhook systems share several traits:

  • Signed payloads. An HMAC signature over the body and a timestamp, sent in a header, lets the receiver check that the call came from you and is not a replay. Stripe and GitHub both sign webhook deliveries.
  • At-least-once delivery with retries. Failed deliveries retry with exponential backoff over hours or days. Receivers must deduplicate by event ID, because duplicates will happen. See Delivery Semantics.
  • Thin or fat events. A thin event carries only the ID and type, and the receiver fetches the current state. That avoids acting on stale data when events arrive out of order. A fat event carries the full object and saves a call.
  • Fast acknowledgement. Receivers should return 2xx quickly and do the work asynchronously. Otherwise a slow handler causes timeouts, retries and duplicate processing.
  • A replay tool and delivery log, so customers can see what was sent and resend after an outage.

Internally, the webhook sender is a queue consumer: events go to a queue, workers deliver them, and failures go back with delay. This is the same pattern as Event-driven Architecture, with the internet in the middle.

Mobile clients change the trade-offs. Mobile networks have high and variable latency (often 100 to 300 ms round trips on cellular), and old app versions stay installed for years. That pushes API design towards fewer, coarser calls per screen, often through a backend-for-frontend; compressed and compact payloads; idempotency on every write, because connections drop mid-request; and strict backward compatibility, since you cannot force every user to upgrade. A minimum supported version check, returned as a clear error that prompts the app to update, gives you an escape hatch for truly breaking changes.

The API lifecycle: design-first specs, review, testing and operationShow

An API is a product with a lifecycle, not a side effect of code. The teams with the most consistent APIs treat the contract as the first artefact and automate every check around it.

Design-first versus code-first. In code-first, you write handlers and generate the spec from annotations. It is quick and the spec never drifts from the code, but the API shape follows whatever the framework makes easy, and reviewers only see the contract after it is built. In design-first, you write the spec, review it, and then generate server stubs and client SDKs from it. Front-end and mobile teams can start against a mock server on day one, and design mistakes are caught when they cost a text edit instead of a migration. Most large platforms land on design-first for public APIs and accept code-first for internal ones.

A tiny spec fragment shows how much of this page becomes machine-checkable:

paths:
  /v1/orders:
    get:
      parameters:
        - { name: cursor, in: query, schema: { type: string } }
        - { name: limit, in: query, schema: { type: integer, maximum: 100 } }
      responses:
        "200": { $ref: "#/components/responses/OrderPage" }
        "429": { $ref: "#/components/responses/RateLimited" }
components:
  schemas:
    Order:
      type: object
      required: [id, status, total_cents, currency, created_at]
      properties:
        id: { type: string }
        status: { type: string, enum: [pending, paid, shipped, cancelled] }
        total_cents: { type: integer }
        currency: { type: string, minLength: 3, maxLength: 3 }
        created_at: { type: string, format: date-time }

Linting encodes the style guide. A linter such as Spectral runs rules on every pull request: paths use plural kebab-case nouns, every list operation has cursor and limit, every operation declares the shared error schema, IDs are strings, money fields end in _cents with a sibling currency, and every response has a description. A rule that fails the build is worth far more than a guideline in a wiki, because nobody has to remember it.

Diffing catches breaking changes mechanically. Comparing the new spec to the published one flags removed fields, new required request fields, narrowed types and removed enum values. The rules are not symmetric, which is the key insight. Adding an optional request field is safe, but adding a required one breaks old clients. Adding a response field is safe, but removing one breaks clients that read it. Adding an enum value to a response can break clients that switch on it exhaustively, which is why style guides tell clients to handle unknown values.

Review focuses on what tools cannot judge. Is this the right resource? Does the name match the domain language? Will this pagination scale? Is the action idempotent, and if not, does it take a key? Is the authorisation check on the object, not just the route? A short checklist built from the principles near the top of this page keeps reviews fast and consistent.

Contract tests keep implementation and spec honest. Provider tests replay recorded consumer expectations against the real service. Consumer-driven tools such as Pact capture what each client actually uses, so you know whether "removing" a field breaks anyone. Schema validation in staging, or on a sample of production responses, catches drift that unit tests miss.

Operate per endpoint, not per service. Track request rate, error rate split into 4xx and 5xx, and p50, p95 and p99 latency for each method and path template (GET /v1/orders/:id, not each raw URL, or the metrics explode in cardinality). A typical internal target is p99 under a few hundred milliseconds for reads, while a list endpoint may get a looser target than a point read. Log the API version and the client or SDK version with each request. That turns deprecation from guesswork into a query: you can see exactly which customers still call the old field and contact them before the sunset date.

Worked example: retiring a field. Suppose GET /v1/orders/:id returns shipping_address as a flat string, and you want a structured object. First, add shipping_address_v2 (the expand step). Then mark the old field deprecated in the spec and docs, and send a Deprecation header. Next, measure: suppose 3% of calls come from SDK versions that read the old field. Email those customers and publish a sunset date six to twelve months out. Run short brownouts that return the field as null for an hour, so hidden dependencies surface while you are watching. Finally, remove the field (the contract step) in a new version, or for date-versioned APIs, in a new dated version with a transform that keeps old versions working. No client breaks without warning, and every step is backed by data.

Key Takeaways#

  • Model core entities as plural-noun resources, map actions to HTTP methods, and use sub-resources for non-CRUD actions.
  • Use correct status codes and one structured error format with a request ID.
  • Paginate every list, preferably with cursors backed by keyset queries, and allow only indexed filters and sorts.
  • Prefer additive, backward-compatible changes; version only for breaking ones and announce deprecations.
  • Add idempotency keys to creates and payments, rate-limit headers, and take user identity from the auth token.
  • Derive endpoints from entities and requirements in about five minutes; take the user from the token.
  • Use cursor or keyset pagination for anything large, ETags for concurrency and caching, and 202 plus a job for slow work.
  • Evolve APIs additively, deprecate with headers and usage data, and treat every observable behaviour as part of the contract.