Imagine your mobile app fires off a checkout POST request, and right at that second, the user walks into an elevator and drops connection. The client has no idea if the card was charged or if the server ever saw the packet. If the app blindly fires off a retry, congratulations: your customer just paid twice.
Designing a production-ready REST API goes way beyond wiring up straightforward CRUD endpoints. You have to build defensively around network hiccups, concurrent writes, and live data shifting under your feet.
Pagination: Stick to cursor-based pagination so concurrent writes don't shift data mid-scroll
Error handling: Adopt RFC 9457 (Problem Details) so clients get structured, predictable failures
Idempotency: Enforce
Idempotency-Keyheaders on state-mutating requests to protect retriesVersioning: Lean toward
Accept/Content-Typeheaders, falling back to/v1in the path if neededRate limiting: Throw an HTTP 429 backed by an explicit
Retry-Afterheader
Resource Naming and URL Structure
Plural Nouns Over Verbs
Think of your endpoints as resource collections, not function calls. The HTTP method should explain the action, while the URL path simply identifies the thing you're touching. Sticking to plural nouns keeps your routing clean, whereas peppering verbs through your routes turns your URL schema into a messy guessing game for anyone integrating with it.
Skip paths like /getCustomers or /createOrder and just route to /customers. If a client sends a GET request there, they fetch existing records; if they send a POST, they create a fresh one. Sticking to plural forms across the board establishes an intuitive mental model for your entire surface area.
The One-Level Nesting Rule
Resist the urge to turn your database's foreign key hierarchy directly into a URL tree. When you start building deep tunnels like /customers/123/orders/456/items/789, you're setting yourself up for brittle routes that are annoying to construct and painful to refactor.
Keep your nested paths capped at a single level. When an item has its own globally unique identifier, there is no reason not to fetch it straight from /items/789. Save nesting strictly for when you need to represent real parent-child scoping, such as pulling a specific customer's purchase history via /customers/123/orders.
HTTP Methods and the Reality of CRUD
Mapping Actions to HTTP Verbs Effectively
HTTP verbs give consumers an unambiguous vocabulary for their actions. POST creates a brand-new entity, while GET reads data strictly without causing any server-side side effects.
PUT and PATCH solve two completely different problems, and mixing them up causes real headaches. A PUT represents a full replacement, meaning the caller must pass the entire resource state. PATCH, on the other hand, updates only the specific fields passed along.
If a user just wants to update their email address, you want a PATCH: sending PATCH /customers/123 with {"email": "new@site.com"} will leave their existing profile untouched. If you ran that same payload against a true PUT handler, you might wipe out their name, phone, and billing details. Relying on POST for basic edits or GET for state mutations also breaks caching layers and confuses downstream proxies.
Choosing the Exact 2xx, 4xx, and 5xx Status Codes
Whatever you do, please stop returning an HTTP 200 with {"error": "..."} buried inside the JSON payload. Proper status codes let client networking stacks, proxies, and edge gateways route errors and trigger retry logic without having to decode your entire response body first.
201 Created: Send this back whenever a POST successfully spins up a new resource, and include a
Locationheader pointing directly to it.202 Accepted: Reach for this when a valid job has entered your queue for background processing, but the actual work isn't done yet.
400 Bad Request: Use this when the payload fails basic schema validation or the client sent unparseable syntax.
422 Unprocessable Entity: Perfect for when the JSON is syntactically sound, but the values violate a specific business rule.
404 Not Found: Reserve this for resources that genuinely do not exist, rather than using it to mask permission issues.
Standardizing Error Responses with RFC 9457
Moving Beyond Generic Error Messages
Spitting back an unhandled stack trace or a lazy {"error": "Something went wrong"} leaves whoever is integrating against your backend completely in the dark. Having a predictable, strongly typed error schema makes debugging issues exponentially faster for both teams.
This is exactly why RFC 9457 (Problem Details for HTTP APIs) exists. It provides a formal, industry-standard blueprint for surfacing failures cleanly across your service.
Structuring the Problem Details JSON Envelope
An RFC 9457 payload hands the calling code structured fields it can inspect programmatically. At a minimum, you'll want to include:
type: A URI reference that acts as a stable identifier for the error category, like
https://example.com/probs/out-of-credit.title: A short, human-readable summary that never changes between occurrences of this error type.
status: The actual HTTP status code returned by the origin server, mirrored inside the payload for convenience.
detail: A clear, contextual explanation pointing out exactly why this particular call blew up.
instance: A URI reference pinpointing the exact request or resource occurrence that triggered the problem.
Make sure to deliver this payload with a Content-Type: application/problem+json header so downstream libraries immediately parse it as a problem document. A validation issue usually looks something like this:
JSON
{
"type": "https://api.example.com/probs/validation",
"title": "Your request parameters did not validate.",
"status": 422,
"detail": "The field 'email' must be a valid email address.",
"instance": "/customers/123"
}Pagination: Why Cursor Beats Offset in Production
The Data Drift Problem in Offset Pagination
Offset pagination (?limit=20&offset=40) tells your database engine to count rows sequentially from the start of the query. That approach falls apart fast the moment people are actively writing new records to the table you're reading from.
Picture this: someone pulls down the first 20 rows. While they're skimming that data, five new rows land at the top of the feed. When they fire off the request for page two (offset=20), the whole window has slipped downward by five slots.
The user ends up seeing the last five rows from page one all over again. That's the classic data drift trap.
Implementing Scalable Cursor-Based Filtering and Sorting
Cursor-based pagination sidesteps this entirely by anchoring your query to a specific spot in the dataset rather than counting raw offsets. The client simply hands back a token showing where its previous page ended.
The client starts with ?limit=20. Your API delivers those rows alongside an opaque next_cursor string - often a base64-encoded combination of an indexed timestamp and an ID.
For the next batch, the client sends that back (?limit=20&cursor=XYZ). Your database then does a quick index seek to jump right past that boundary, keeping query performance snappy no matter how deep someone pages:
SQL
SELECT * FROM orders
WHERE created_at < :cursor
ORDER BY created_at DESC
LIMIT 20;Filtering on an indexed column skips the records instantly instead of forcing the database engine to grind through thousands of skipped rows with an expensive OFFSET.
Idempotency Keys in POST Requests
Preventing Duplicate Transactions
Networks drop packets all the time. A client fires off a POST to process a payment, your server charges the card cleanly, but the network connection cuts out before the confirmation reaches the client.
The client times out, assumes the request died in transit, and retries. Without an idempotency layer, your customer just bought two identical items.
Idempotency guarantees that firing the exact same request three or four times yields the exact same state change as sending it once.
Handling Retries with Idempotency Keys
Have your clients send a unique Idempotency-Key header - typically a UUID generated on their end - whenever they issue a mutating POST or PATCH request.
Your server caches that incoming key alongside the eventual response body and status code. If an identical key hits your server a few seconds later, you short-circuit the execution and return the cached response without running your business logic again. This takes the danger out of network timeouts and aggressive client retries.
Watch out for two common edge cases here: make sure your stored keys expire after a reasonable window like 24 hours, and reject the request with a 409 Conflict if someone attempts to reuse an existing key with a totally different payload. That almost always indicates a client-side bug. This is the exact safeguard infrastructure companies like Stripe rely on to guarantee safe billing operations.
Authentication, Security, and CORS
Enforcing HTTPS and Bearer Tokens
Stick to battle-tested standards like OAuth2 or signed JSON Web Tokens (JWT) rather than trying to invent your own custom authentication handshake.
Clients need to pass credentials inside standard headers via Authorization: Bearer <token>, and you should reject any plaintext HTTP traffic at your load balancer before it ever reaches your application code.
Why Credentials Never Belong in Query Strings
Tacking secrets, API tokens, or session identifiers onto URL parameters (?api_key=secret) is an accident waiting to happen.
URLs end up logged everywhere: browser histories, intermediate proxy records, web server access logs, and your application monitoring dashboards. When an access token lives in a query string, it gets scattered across plain-text logs across your infrastructure. Always keep sensitive credentials inside HTTP headers or within the encrypted request body.
Versioning Strategies and Deprecation Policies
URL Versioning vs. Accept Header
Every API evolves, and eventually you have to ship a breaking change. The two primary schools of thought for handling this are path-based versioning and header-based content negotiation.
Path versioning (/v1/customers) is dead simple to inspect, works effortlessly with CDNs, and saves your sanity when debugging logs. Using the Accept header (Accept: application/vnd.company.v1+json) keeps your URIs clean and represents the pure REST approach, but it forces clients to manage custom headers for every call. Pick whichever strategy fits your ecosystem better, but commit to it across your whole team.
Sunsetting APIs Gracefully
Give teams plenty of runway and explicit cues long before you pull the plug on an older endpoint.
Signal obsolescence by injecting the standard Deprecation HTTP header into responses for flagged endpoints. Pair that with a Sunset header that specifies the exact timestamp when that route will stop answering traffic. Client applications can log these headers in their own environments, giving teams an early heads-up before their integrations break.
Rate Limiting, Caching, and Observability
Protecting the Gateway with 429 Too Many Requests
A single poorly written loop in a client script can saturate your database pool in seconds. Enforce rate limiting right at your reverse proxy or API gateway before that traffic ever touches your application workers, whether you run services on a Docker alternative or deploy on top of managed cloud infrastructure.
When a consumer exceeds their threshold, return a 429 Too Many Requests status alongside a clear Retry-After header. That header tells their client exactly how many seconds to back off, stopping stampedes before they spiral. Set these quotas based on empirical metrics: running some database load testing ahead of time will show you exactly where your bottleneck points live.
Keeping OpenAPI Documentation in Sync
Your documentation starts lying to your consumers the second it drifts away from your codebase. Relying on someone remembering to update an internal wiki after a pull request merges is a recipe for broken integrations.
Automate your OpenAPI (Swagger) spec generation directly from your route definitions and code schemas. If you're building with JavaScript, keeping your Node.js version current makes sure your schema generator plugins don't break during CI pipelines. This keeps your playground docs, auto-generated SDKs, and production runtime behavior completely in sync across deployments.
These patterns build on each other. Cursor-based pagination stabilizes your reads, idempotency keys protect your database from duplicate writes, and RFC 9457 gives your users understandable error payloads when things go sideways. Nail those three from the start, and you'll sidestep the vast majority of production firefights that teams stumble into with their first public API.
