Software Engineering
REST API Design Best Practices: Status Codes, Idempotency, Pagination and Errors
A good API is predictable. Learn the HTTP rules that make clients easier to write and bugs easier to avoid, grounded in the actual standards.
By Philip Mutuku · Published · Updated · 5 min read
Most API pain comes from surprises: a 200 status with an error inside the body, a POST that creates duplicates on retry, a list endpoint that returns everything and crashes the phone. The antidote is boring consistency, and HTTP already defines most of the rules.
Model resources, not actions
Use nouns for URLs and let HTTP methods express the action. Plural, lowercase, hyphenated names keep things tidy.
| Goal | Request | Typical success |
|---|---|---|
| List invoices | GET /invoices | 200 OK |
| Read one | GET /invoices/42 | 200 OK |
| Create | POST /invoices | 201 Created + Location header |
| Replace | PUT /invoices/42 | 200 OK or 204 No Content |
| Partial update | PATCH /invoices/42 | 200 OK |
| Delete | DELETE /invoices/42 | 204 No Content |
Use status codes honestly
Clients, proxies and monitoring tools all rely on status codes. RFC 9110 defines their meaning, and ignoring it breaks tooling.[1]
- 200 / 201 / 204 for success, creation and “done, nothing to return”.
- 400 malformed request; 401 not authenticated; 403 authenticated but not allowed; 404 not found.
- 409 conflict with current state (duplicate email, stale version); 422 well-formed but semantically invalid.
- 429 too many requests, ideally with a Retry-After header.[2]
- 500-series only for genuine server faults. Never return 200 with an error message inside.
Design for retries: idempotency
Networks fail, and clients retry. RFC 9110 defines GET, PUT and DELETE as idempotent: repeating them has the same effect as doing them once. POST is not, which is exactly why retrying a payment POST can charge a customer twice.[1]
The standard fix is an idempotency key: the client sends a unique ID with the request, and the server remembers the result for that key so a retry returns the original outcome rather than repeating the work.[4]
router.post('/payments', authenticateToken, async (req, res) => {
const key = req.get('Idempotency-Key');
if (!key) return res.status(400).json({ message: 'Idempotency-Key header required' });
// Same key + same user => return the stored response instead of charging again.
const previous = await db.idempotency.find(req.user.id, key);
if (previous) return res.status(previous.status).json(previous.body);
const payment = await payments.create(req.body, req.user.id);
const body = { id: payment.id, status: payment.status };
await db.idempotency.save(req.user.id, key, 201, body);
res.status(201).json(body);
});
Paginate every list
An unbounded list endpoint works on day one and becomes an outage on day 300. Always set a default and a maximum page size. Two common approaches:
- Offset pagination (?page=3&limit=20) is simple and supports jumping to a page, but gets slower on large tables and can skip or repeat items when data changes.
- Cursor pagination (?after=abc123&limit=20) is stable and fast for feeds and infinite scroll, because it continues from a known position rather than counting rows.
{
"data": [ { "id": 101, "title": "..." }, { "id": 100, "title": "..." } ],
"page": { "limit": 20, "nextCursor": "eyJpZCI6MTAwfQ", "hasMore": true }
}
Versioning and changing an API safely
The moment other people depend on your API, every change is a risk. Prefer additive changes: new fields, new endpoints and new optional parameters rarely break existing clients. Removing or renaming a field, changing a type or tightening validation does. When a breaking change is unavoidable, introduce a new version, run both for a stated period, tell consumers early and publish a deprecation date.
- Put the version in the path (
/v2/orders) or a header, and choose one convention for the whole API. - Never reuse a field name with a different meaning.
- Return unknown fields gracefully on input, or reject them clearly. Either is fine if documented.
- Add a
Deprecationnotice in documentation and responses before removal.
Security belongs in the design
Authenticate every request and authorise every action on the server, using the identity from the token rather than an ID sent in the body. Apply rate limiting to protect against abuse and accidental floods, validate and size-limit all input, and use HTTPS everywhere. Return the same error for “not found” and “not yours” where revealing existence would leak information.
| Concern | Practical measure |
|---|---|
| Broken object-level access | Check ownership on every read and write |
| Excessive data exposure | Return only the fields the client needs |
| Abuse and floods | Rate limits and request size limits |
| Leaky errors | Stable error codes and no stack traces in responses |
| Mass assignment | Whitelist writable fields explicitly |
Documentation is part of the product
An API without good documentation is slow to adopt and expensive to support. Describe it with the OpenAPI specification, generate reference docs from it, and include a short “first request in five minutes” guide with working examples. Show real success and error responses, authentication steps and rate limits. Keep a changelog so integrators can see what moved.
Testing and monitoring a live API
Design decisions only pay off if you can see how the API behaves in production. Write contract tests that check each endpoint returns the documented shape, status codes and error format, and run them on every deploy. Add a few tests that deliberately misbehave: missing fields, wrong types, oversized bodies and expired credentials. These catch the regressions that frustrate integrators most.
In production, track request rate, error rate by status code, and latency percentiles, not just averages. A rising share of 4xx responses often signals a confusing contract or a client bug; a rising share of 5xx signals your own problem. Include a request ID in every response and log line so a customer’s “it failed at 14:32” can be traced to one request in seconds.
Frequently asked questions
Should we use REST, GraphQL or gRPC?
REST is a sensible default for public and mobile-facing APIs because tooling and knowledge are everywhere. GraphQL helps when many clients need flexible shapes of data, and gRPC suits internal service-to-service calls where performance matters. Pick for your actual constraints, not for fashion.
PUT or PATCH for updates?
Use PUT to replace a whole resource and PATCH for partial changes. Whichever you choose, document it and keep behaviour predictable, including how missing fields are treated.
Return errors people can act on
Pick one error shape and use it everywhere. RFC 9457 defines a standard “problem details” format with fields for a type, title, status and detail, which many clients and libraries already understand.[3]
{
"type": "https://api.example.com/problems/validation-error",
"title": "Your request parameters didn't validate.",
"status": 422,
"detail": "amount must be greater than 0",
"errors": [ { "field": "amount", "message": "must be greater than 0" } ]
}
Never leak stack traces or SQL errors to clients; log those server-side. And version your API from the start, whether in the URL or a header, because changing the contract later without a version breaks every integration you cannot see.
References & further reading
- IETF, RFC 9110: “HTTP Semantics” (methods, safe and idempotent methods, status codes). https://www.rfc-editor.org/rfc/rfc9110
- IETF, RFC 6585: “Additional HTTP Status Codes” (429 Too Many Requests). https://www.rfc-editor.org/rfc/rfc6585
- IETF, RFC 9457: “Problem Details for HTTP APIs”. https://www.rfc-editor.org/rfc/rfc9457
- Stripe, “Idempotent requests”. https://docs.stripe.com/api/idempotent_requests