API Design: Resources, Status Codes, Pagination and Idempotency
How to design a clean REST API: resource naming, correct use of HTTP methods and status codes, offset versus cursor pagination, idempotency keys, versioning and rate limiting.
An API is the contract between a service and its clients. Once other teams or external developers build against it, changing it is expensive, so it deserves careful design at the start. In a system design interview, the API step comes right after requirements and shows whether the requirements were understood.
An endpoint named /getAllOrders illustrates several common mistakes at once: a verb in the URL, no pagination, and no thought about growth. These notes cover the conventions of a well-designed REST API.
Resources and HTTP methods
REST models an application as a set of resources, which are the nouns of the system: users, orders, products. Each resource has a URL. The action to perform is expressed by the HTTP method, not by the URL. This gives a uniform, predictable interface: a developer who has seen one endpoint can guess the others.
- Use plural nouns for collections: /orders, and /orders/{id} for one item.
- Do not put verbs in paths. GET /orders replaces /getAllOrders; DELETE /orders/42 replaces /deleteOrder?id=42.
- Express relationships by nesting, one level deep: /users/42/orders.
- Use query parameters for filtering, sorting and field selection: /orders?status=shipped&sort=-createdAt.
- Be consistent in naming style, date formats (ISO 8601 in UTC) and identifiers across the whole API.
# Avoid GET /getAllOrders POST /createOrder POST /updateOrderStatus GET /deleteOrder?id=42 # Prefer GET /v1/orders?status=shipped&limit=20 list (filtered, paginated) POST /v1/orders create GET /v1/orders/42 read one PATCH /v1/orders/42 partial update PUT /v1/orders/42 full replacement DELETE /v1/orders/42 delete GET /v1/users/7/orders orders of one user POST /v1/orders/42/cancellation an action modelled as a sub-resource
Method semantics: safe and idempotent
HTTP methods carry defined semantics that clients, proxies and caches rely on. A safe method does not change state. An idempotent method has the same effect whether it is called once or many times, which means it can be retried without harm.
Method Purpose Safe Idempotent Notes -------------------------------------------------------------------------------- GET read yes yes cacheable; never changes data POST create / trigger action no no retry may create a duplicate PUT replace the resource no yes same request twice = same state PATCH partial update no not always depends on the operation DELETE remove no yes deleting twice leaves it deleted
Status codes
The status code tells the client the outcome without parsing the body. An API that returns 200 OK with an error message inside breaks every generic client, retry policy and monitoring tool. The first digit gives the class: 2xx success, 3xx redirection, 4xx the client made a mistake, 5xx the server failed.
200 OK success with a body 201 Created resource created; include a Location header 202 Accepted accepted for asynchronous processing 204 No Content success with no body (for example after DELETE) 400 Bad Request malformed or invalid input 401 Unauthorized not authenticated (missing or invalid credentials) 403 Forbidden authenticated, but not allowed 404 Not Found resource does not exist 409 Conflict conflicts with current state (duplicate, version mismatch) 422 Unprocessable Entity well-formed but fails validation 429 Too Many Requests rate limit exceeded; include Retry-After 500 Internal Server Error unexpected server fault 502 / 503 / 504 bad gateway / service unavailable / gateway timeout
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Quantity must be at least 1.",
"details": [ { "field": "items[0].quantity", "issue": "min:1" } ],
"requestId": "req_8f31c2"
}
}Pagination
An endpoint that returns a whole collection works with ten rows in development and fails with ten million in production: the query is slow, the response is huge, and the client cannot display it anyway. Every list endpoint must be paginated, with a default and a maximum page size.
Offset pagination uses a limit and an offset: skip the first N rows and return the next 20. It is simple and allows jumping to any page. It has two problems. The database still has to read and discard all the skipped rows, so deep pages become slow. And if rows are inserted or deleted while the user is paging, items shift, and the user sees duplicates or misses items.
Cursor pagination, also called keyset pagination, avoids both. The response includes a cursor that marks the position of the last item returned. The next request sends that cursor, and the query uses an indexed condition to continue from that point. Performance is constant no matter how deep the page, and results are stable when data changes. The limitations are that the client cannot jump to an arbitrary page and the sort order must be based on a unique, indexed key. For feeds, timelines and any large or frequently changing list, cursor pagination is the right choice.
-- OFFSET: reads and throws away 100,000 rows to return 20
SELECT * FROM orders ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;
-- CURSOR (keyset): jumps straight to the position using the index
SELECT * FROM orders
WHERE (created_at, id) < ('2026-11-05T10:15:00Z', 98231)
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- API
-- GET /v1/orders?limit=20&cursor=eyJjIjoiMjAyNi0xMS0wNVQxMDoxNTowMFoiLCJpIjo5ODIzMX0
-- Response: { "data": [ ... ], "nextCursor": "eyJjIjoi...", "hasMore": true }
-- The cursor is an opaque, encoded value; clients must not construct it.Idempotency for POST
A client sends POST /orders and the connection drops before the response arrives. The client cannot know whether the order was created. If it retries and the first request did succeed, there are now two orders. Since POST is not idempotent by definition, the API has to provide idempotency explicitly for any operation where a duplicate is harmful.
The client generates a unique idempotency key for each logical operation and sends it in a header. The server records the key together with the response. If a request arrives with a key it has already processed, the server returns the stored response and does nothing else. Retries become safe, for both clients and intermediate services.
POST /v1/orders
Idempotency-Key: 2b6f7c1e-93a4-4f0b-8a67-51d1c2a9e0f4
Content-Type: application/json
{ "items": [ { "productId": "p_12", "quantity": 1 } ] }
-> first call : 201 Created { "id": "o_5512", "status": "PLACED" }
-> retry : 201 Created { "id": "o_5512", "status": "PLACED" } (same order, not a new one)Versioning
APIs change. Adding an optional field or a new endpoint is backward compatible and needs no new version. Removing or renaming a field, changing a type or changing behaviour breaks existing clients, and mobile apps in particular cannot be forced to update. Breaking changes therefore go into a new version while the old one continues to work for a published deprecation period.
The most common scheme puts the version in the path, such as /v1/orders. It is explicit and easy to route and debug. Alternatives are a version header or a media type parameter. Whichever is chosen, include it from the first release.
Rate limiting and security
- Rate limiting protects the service from abuse and from buggy clients. Requests over the limit receive 429 with a Retry-After header, and limit headers tell clients how much quota remains.
- Authentication establishes who the caller is (tokens over HTTPS); authorisation checks what they may access. Check ownership on every resource: being logged in does not entitle a user to read /orders/43 if it belongs to someone else.
- Validate all input on the server and enforce maximum sizes for bodies and page limits.
- Do not expose internal details in error messages or put sensitive data in URLs, which are logged.
REST, gRPC and GraphQL
REST over JSON is the default for public and browser-facing APIs because it is simple, cacheable and universally supported. gRPC uses a binary format with strictly typed contracts and supports streaming, which makes it efficient for internal service-to-service calls. GraphQL lets the client specify exactly which fields it needs in one request, which helps when different clients need different shapes of data, at the cost of more complex caching and server-side query control. Mention the alternatives where they fit, and default to REST otherwise.
Interview summary
- Model resources as plural nouns and use HTTP methods for actions.
- Return accurate status codes and a consistent error format.
- Paginate every list; prefer cursor pagination for large or changing data.
- Make unsafe operations retry-safe with idempotency keys.
- Version the API from day one and protect it with authentication and rate limiting.
Summary
A good API is predictable. Resources are nouns, HTTP methods state the action, status codes state the outcome, lists are paginated with cursors, creation is made idempotent with a key, and breaking changes are isolated behind a version. These conventions let clients and infrastructure behave correctly without special knowledge of your service.
Puneet Tiwari
Full Stack Developer
