API design principles and best practices for long-lived APIs

API design principles that keep interfaces stable as they grow: consistent errors, versioning, cursor pagination, idempotency keys, OAuth scopes and webhooks.

Written by
DevTech365 Engineering
Published
Reading time
7 minutes

An API is a promise. Once another team, a partner or a mobile app depends on it, every design decision becomes expensive to change. Mobile clients are especially unforgiving, because old app versions stay installed long after you ship a new one.

Good API design is mostly about keeping the next change cheap. The principles below cover the decisions that are hardest to undo: how you model resources, how consistent you are, how you version, paginate and secure the API, how you send webhooks, and how you document and test the contract.

Design around resources and use cases

Start from what clients need to do, not from your database tables. List the use cases first (a customer places an order, a warehouse marks it shipped, finance exports invoices), then design resources that serve them. An API that mirrors your schema leaks internal decisions and breaks every time you refactor.

Model resources as nouns and use HTTP methods for what they mean: GET /orders, POST /orders, GET /orders/ord_123. When an operation is a business action rather than a field update, give it a name. POST /orders/ord_123/cancel is clearer than patching a status field, and it gives you one place to enforce the rules about when an order can be canceled.

Shape responses for the client's job. If every order screen needs the customer's name, include a small customer summary or support an expand parameter, so clients do not need extra round trips.

Keep naming and errors consistent

Consistency makes an API learnable. After using two endpoints, a developer should be able to guess how the third one works. Decide your conventions once and enforce them in review:

  • One casing style for fields, either snake_case or camelCase, used everywhere.
  • Timestamps in ISO 8601 with an explicit offset, ideally UTC.
  • IDs as opaque strings, even if they are integers internally today.
  • Money as an integer amount in minor units plus a currency code, never a float.
  • Plural nouns for collections and the same filter syntax on every list endpoint.

Errors deserve the same care, because developers read them when something has already gone wrong. Use HTTP status codes correctly, then return one error shape everywhere. RFC 9457 (Problem Details for HTTP APIs) is a sensible base, served as application/problem+json:

{
  "type": "https://api.example.com/errors/validation-failed",
  "title": "Validation failed",
  "status": 422,
  "detail": "Two fields in the request body are invalid.",
  "errors": [
    { "field": "email", "code": "invalid_format", "message": "Must be a valid email address." },
    { "field": "quantity", "code": "out_of_range", "message": "Must be between 1 and 100." }
  ],
  "request_id": "req_7f3a9c"
}

Clients should branch on stable codes such as invalid_format, never on the human-readable message. The request ID lets your support team find the exact log entry.

Version deliberately and deprecate in public

Most changes should not need a new version. Adding an endpoint, an optional parameter or a response field is backward compatible, provided clients ignore fields they do not recognize. Say that in your documentation so client developers write tolerant parsers, and warn them that enums may gain new values.

Breaking changes include removing or renaming fields, changing types, making optional inputs required, changing defaults and tightening validation. When one is unavoidable, version explicitly. A major version in the path, such as /v1/, is the easiest for clients to see and for gateways to route. Date-based versions sent in a header allow finer-grained changes but need more infrastructure to support.

Treat deprecation as a process, not an announcement:

  • Track which clients still call the old version, so you know whom to contact.
  • Publish a timeline in the changelog and tell affected consumers directly.
  • Add a Deprecation header to old responses, plus a Sunset header (RFC 8594) with the retirement date.
  • Keep the old version working until that date, then retire it as promised.

Paginate and retry safely

Two problems appear as soon as an API sees real traffic: collections grow, and networks drop responses.

Cursor versus offset pagination

Offset pagination is the obvious first choice and works well for small, stable lists. As collections grow, the differences start to matter:

ConcernOffset paginationCursor pagination
Request shape?limit=50&offset=200?limit=50&cursor=...
Jump to an arbitrary pageYesNo
Deep pagesSlower, skipped rows are still readConsistent, served by an index
Data changing between requestsDuplicates or skipped itemsNo duplicates or skipped items
Good fitSmall admin lists with page numbersFeeds, sync jobs, large or growing collections

A cursor is an opaque token that encodes the position of the last item returned, usually its sort key plus its ID. The next request asks for items after that position. Keep the cursor opaque so you can change its encoding later, cap the page size, and return the next cursor in the same place on every list endpoint.

Idempotency keys for retries

Networks fail at the worst moment: after the server has done the work but before the client receives the response. If the client retries a POST that created a payment, you might charge twice. HTTP defines PUT and DELETE as idempotent, but not POST, so add that guarantee explicitly with an idempotency key.

The client generates a unique key per logical operation and sends it in an Idempotency-Key header. The server stores the key, a fingerprint of the request and the response for a documented retention period, and a retry with the same key gets the stored response without repeating the work. Reusing a key with a different payload is a client error. A retry that arrives while the original is still running should get a conflict response, not a second execution.

Scope access with OAuth 2.0 and rate limits

Authentication establishes who is calling. Authorization decides what they may do, and it is where the most serious API vulnerabilities live. Broken object level authorization, where a caller reads someone else's record by changing an ID, sits at the top of the OWASP API Security Top 10.

For third-party and machine access, use OAuth 2.0. The client credentials grant suits server-to-server integrations, and the authorization code flow with PKCE suits apps acting on behalf of a user. Define scopes around capabilities, such as orders:read and orders:write, so each integration gets only what it needs.

Rate limits protect the system, and your other customers, from one misbehaving client. Apply them per API key or per tenant, return 429 Too Many Requests with a Retry-After header when a client exceeds them, and publish the limits. Reporting remaining quota in response headers lets well-behaved clients slow down before they hit the limit.

Treat webhooks as part of the API

Webhooks are an API you call, so they need the same discipline as the ones you serve.

  • Sign every delivery. Send an HMAC signature over a timestamp and the body, and tell receivers to reject stale timestamps to prevent replays.
  • Deliver at least once. Retry failures with exponential backoff, and give each event a unique ID so receivers can discard duplicates.
  • Do not promise ordering. Include a timestamp or version so receivers can ignore events older than the state they hold.
  • Keep payloads small. Sending the event type and resource ID, and letting the receiver fetch current state, avoids acting on stale data.
  • Give integrators tools. A delivery log, manual replay and test events make problems diagnosable without a support ticket.

Document with OpenAPI and test the contract

An OpenAPI description should be the source of truth for the API, not an artifact generated once before launch. Whether you write the spec first or generate it from code, keep it in the repository, review changes to it like code, and build documentation, mock servers and client SDKs from it.

Then make the contract enforceable:

  • Lint the spec with a tool such as Spectral, so naming and error conventions are checked automatically.
  • Run a breaking-change check, for example with oasdiff, on every pull request that touches the spec.
  • Validate real responses against the schema in integration tests, so the implementation cannot drift from the document.
  • Where you own both sides, add consumer-driven contract tests with a tool such as Pact.

Reference documentation is not enough on its own. Add guides for authentication, rate limits, idempotency and webhook verification, and keep a changelog.

Design for the clients you have not met yet

Most API pain comes from decisions that were cheap to make and expensive to reverse: an inconsistent error format, offset pagination on a table that kept growing, payment endpoints without idempotency keys. Getting them right at the start costs little. Fixing them after clients depend on the API means a new version and a migration for every consumer.

Write your conventions down, encode them in the spec and a linter, and let automated checks catch drift. DevTech365 designs and builds APIs with these principles in place from the first endpoint.

  • API development
  • backend development
  • API design

DevTech365 Engineering

Software engineering team

The engineers who build DevTech365's mobile apps, web platforms, APIs and AI systems, writing about the decisions behind production software.

Have a software idea?Let's turn it into something real.

Tell us what you want to build and where you are today. We'll reply with questions, next steps and an honest view of how we can help.