Design an application programming interface by deciding who consumes it, what resources and operations it exposes, and what contract every request and response must honor before you write endpoint code. Then name things consistently, version the surface, and test the contract against real client flows. The key condition is that the interface must be designed from the consumer's side of the boundary, not from your database schema outward—get that backwards and every later decision inherits the mistake.
That distinction sounds abstract until you've shipped the alternative. Teams that let table structure dictate endpoints end up with URLs like POST /updateUserRecord and payloads that mirror columns, then spend years bolting on awkward compatibility layers. An API is a promise to people you don't control, often in languages and runtimes you'll never run. The design work is mostly about reducing the number of ways that promise can be misread or broken.
This guide walks through the sequence in the order that keeps rework cheap: contract before code, naming before routing, errors before happy paths. It uses HTTP/JSON as the running example because that's the most common surface today, but the reasoning transfers to GraphQL schemas, gRPC service definitions, and SDK-first internal interfaces. Concrete examples are illustrative, not drawn from a specific production system.
Start With Consumers, Not Endpoints
Before choosing a single URL, write down who calls this interface and what they're trying to accomplish. A mobile client fetching a profile screen has different needs than a partner syncing inventory nightly than an internal service reacting to events. Each consumer implies a different tolerance for round trips, payload size, latency, and breaking changes.
A useful exercise: draft the ten most important calls as if you were the client developer, in your own words. "Show the current user's open orders, newest first, with the total in their currency" is a requirement. GET /orders?status=open&sort=-created&include=total is a response to it. Doing the prose first keeps you from over-fitting to your storage.
Write down constraints alongside the call list:
Volume and shape of traffic. A dashboard refresh every 30 seconds is a different design problem than a webhook fan-out to thousands of subscribers. Bursty clients need backpressure signals, pagination, and cached reads; streaming clients need chunked responses or a push channel. Trust boundaries. Public consumers, authenticated partners, and internal services should usually be separate surfaces (separate credentials, separate rate limits) even if they share code. Pretending one surface serves all three invites permission sprawl. Latency budget. If the client screen must paint in 200 ms, an API that requires six sequential calls has already failed, regardless of how clean each endpoint looks. Lifecycle. Will this interface live five years, or is it a pilot with a shelf life measured in weeks? Long-lived surfaces deserve more versioning discipline; short-lived ones can tolerate pragmatism.
Name the consumers and their constraints in a short design note. You'll refer back to it when someone requests "just one more field" for a use case the note never mentioned—that's the signal to ask whether a new consumer category is being smuggled in.
Choose the Style Before the Syntax
The interface style—resource-oriented HTTP, RPC, GraphQL, event streaming—sets what is easy and what is awkward for the rest of the interface's life. This choice is reversible only at significant cost, so make it deliberately.
| Style | Natural fit | Awkward when | Typical cost |
|---|---|---|---|
| Resource-oriented HTTP/JSON | CRUD over identifiable entities; broad client compatibility; caching via HTTP semantics | Highly varied queries, chatty client screens, cross-entity transactions | Many round trips; over/under-fetching |
| RPC (gRPC, JSON-RPC) | Internal service-to-service, strongly typed contracts, low latency | Browser clients without gateways; public surfaces needing broad tooling | Schema/tooling lock-in; harder ad hoc debugging |
| GraphQL | Client-driven data shapes, aggregation across many entities, mobile bandwidth | Simple CRUD; heavy caching at the edge; teams without query governance | Query complexity controls, N+1 risks, schema evolution discipline |
| Event streaming / webhooks | Reacting to state changes, decoupling producers from consumers | Synchronous request/response needs | Delivery guarantees, ordering, idempotency, replay |
Two principles cut across all of them. First, prefer a style your consumers can actually use—a beautiful gRPC contract is a liability if every client is a browser. Second, pick one primary style per surface and add secondary styles via a thin adapter only when a concrete consumer requires it; mixing styles on one surface doubles the surface area you must version and document.
If you're genuinely unsure, HTTP/JSON resource style remains the safest default for a first public interface because the tooling, caching story, and debugging experience are broadly understood. That's a default, not a rule.
Name and Model the Resources
Good names make an API feel obvious a year later. Bad names force every consumer to consult the docs for the most basic operations.
Model resources as nouns representing things with identity: customers, invoices, shipments. Avoid verbs in paths (/getCustomer, /createInvoice) and avoid exposing internal table names (/tbl_cust_rec). Use plural, lowercase, hyphenated segments: /shipping-addresses, not /shippingAddresses or /ShippingAddresses.
Relationships should be readable as paths. GET /customers/{id}/invoices is a sub-collection; GET /invoices?customer_id={id} is a filtered collection. Both can coexist, but decide which is canonical and document the other as a convenience. For nested resources deeper than two levels, flatten: /customers/{cid}/invoices/{iid}/lines is a sign the model should have promoted lines to a top-level resource with its own filter.
Fields deserve the same care. Choose one casing convention (snake_case in JSON is common in HTTP APIs; camelCase is common in JavaScript-heavy ecosystems) and never mix. Name booleans as predicates (is_active, has_shipped) or as flags (active), not as ambiguous nouns. Distinguish timestamps from dates by suffix (created_at vs due_date) and always specify the time zone or format in the contract—RFC 3339 with an explicit offset is the safest default.
A worked naming pass: a model has in a relational database the tables orders, order_items, products. The naive mapping exposes /orders with embedded items. A better resource surface might be:
GET /orders/{id} returns the order header and a summary. Items are a sub-collection at GET /orders/{id}/items. GET /products/{id} returns product detail. Order lines reference products by product_id. POST /orders accepts a customer reference and a list of line items (product, quantity); pricing is computed server-side and returned in the response.
The last rule matters: don't let clients submit prices or totals for anything they don't own. It's the kind of design decision that prevents a class of integrity bugs.
Lock Down the Contract: Requests, Responses, and Types
The contract is everything a client can rely on: paths, methods, parameters, status codes, headers, schemas, types, nullability, defaults, and error formats. If it isn't in the contract, it isn't part of the API, even if it works today.
Use a schema specification (OpenAPI for HTTP/JSON, Protocol Buffers for gRPC, SDL for GraphQL) as the single source of truth and generate docs and client stubs from it. Hand-written docs drift; generated docs don't.
Type decisions to settle once:
Null vs. absent. Decide whether an omitted field means "not provided" or "set to null" and enforce it. JSON has no unsigned integers and no decimal type, so monetary amounts belong in minor units (integers) or strings, never floats. Identifier types. Pick opaque strings or UUIDs over sequential integers for anything exposed publicly; sequential IDs leak volume information and invite enumeration. Document the maximum length. Enumerations. Prefer open string sets with well-known values over closed enums that break clients when a new value appears. If you use an enum, say what a client should do with an unrecognized value (usually "treat as unknown and preserve"). Timestamps and durations. Use RFC 3339 with an offset for timestamps; use ISO 8601 durations or integer milliseconds for durations, and say which. Pagination. Choose cursor-based pagination for large, frequently changing collections and offset-based only where small, stable tables are guaranteed. Return the cursor and a has_more indicator in every list response.
For writes, distinguish partial updates from full replacements explicitly. PATCH with a documented merge semantic (JSON Merge Patch, for example) or a field mask, and PUT only when full replacement is genuinely intended. Document idempotency: which operations are safe to retry, and whether an idempotency key is honored on creates.
Response envelopes are a taste question, but consistency is not. Whether you return a bare object or wrap it as { "data": ..., "meta": ... }, never switch styles within a surface. Wrapping helps when you need to attach metadata (paging cursors, warnings, request IDs); bare responses are slightly friendlier to tooling. Pick one.
Make Errors Part of the Design
Errors are where most APIs become hostile. A well-designed error response tells the caller what went wrong, why, and what to do next, in a machine-readable form.
A workable pattern:
Use HTTP status codes for the broad category (2xx success, 4xx caller error, 5xx server error). Don't invent your own numeric codes in place of status codes. Include a stable, documented error code string for programmatic handling: "card_declined", "rate_limited", "field_required". Include a human-readable message intended for developers, not end users. Include a field path when the error is validation-specific, so the client can surface it next to the right form input. Include a request identifier in every error response (and in X-Request-Id or equivalent on success) so support can trace a single call.
Illustrative shape (invented, for structure only): { "error": { "code": "field_required", "field": "shipping_address.postal_code", "message": "Postal code is required for this country." }, "request_id": "abc123" }.
Also decide the negative-space behaviors up front: What happens on an unknown query parameter (ignored or rejected?), on an oversized payload (which limit and which status?), on a malformed JSON body (400 with a parse error or a specific code?), and on a valid request that targets a resource in a state where the operation is illegal (usually 409 conflict with an explanation). Documenting these makes client error handling predictable, which is the whole point.
Rate limiting deserves a mention in the contract too. Return documented headers for limit and reset, and treat a 429 as expected behavior, not as an anomaly. Clients that can't see their budget will hammer you until they're blocked.
Design for Evolution and Versioning
Every interface that outlives its first release will change. Design for that by making additive change the norm and breaking change the exception.
Additive changes—new optional fields in responses, new optional query parameters, new endpoints—should not break well-behaved clients, provided clients are documented to ignore unknown fields. Say that in the contract, and enforce it in the test suite. Tightening changes—renaming fields, removing values, making optional request fields required, changing types—are breaking and need a deliberate process.
Versioning options, and where each fits:
URL versioning (/v1/orders): simple, visible, easy to route and document. Wastes some path entropy and encourages big-bang version bumps. Reasonable default for public HTTP APIs. Header/media-type versioning (Accept: application/vnd.example.v2+json): keeps URLs stable, suits surfaces where clients can manage headers. Harder to inspect in a browser and easy for intermediaries to mangle. No version, additive-only: viable for internal services and event schemas with strict compatibility rules, but requires genuine discipline and a strong deprecation process.
Whichever you choose, write a deprecation policy: minimum notice window, how deprecation is signaled (a Deprecation and Sunset header, or an email, or both), and what happens to traffic after the cutoff. Public APIs and partner APIs generally need longer windows than internal ones, but a policy with no stated duration is not a policy.
For event-driven interfaces, evolution means field-level compatibility: consumers must tolerate unknown fields and unrecognized enum values, and producers must never reuse a field name for a different meaning. Schema registries exist to enforce this; use one if you're going to have multiple producer teams.
Enforce Consistency, Security, and Limits
Consistency across endpoints is what makes an API learnable. Once you know how one endpoint paginates, errors, and authenticates, you should be able to guess the rest. Write a short style guide—pagination shape, error shape, header usage, naming—and run it in review.
Security belongs in the design, not after. Decide, and document:
Authentication: bearer tokens, API keys, mutual TLS, or OAuth flows, and when each is acceptable. Never allow credentials in query strings (they leak into logs and referrers). Authorization: resource-scoped permissions checked on every request, not only at the endpoint level. A common found-by-testing bug is an endpoint that checks "is a member" but not "is a member of this tenant." Input limits: maximum body size, maximum page size, maximum field length, maximum nesting depth on structured filters. Every limit must be enforced server-side; client-side checks are convenience only. Idempotency and abuse: idempotency keys on creates, rate limits per credential, and a documented process for rotating compromised credentials.
A quick check on the authorization design: for every endpoint, ask "what stops a caller from changing the resource ID to one they don't own?" If the answer is "the UI doesn't offer that," the endpoint is not designed—it's accidental.
Checklist Before You Ship
The contract should be testable before any implementation exists. Because the schema is the source of truth, you can generate a mock server from it and put it in front of client teams while the backend is built. That forces disagreements—missing fields, wrong nullability, awkward pagination—into design time, when they're cheap.
Prerequisites before you start coding against the design:
A written list of consumer categories and their constraints. A style and naming guide the team agrees on. A schema document in the chosen specification format. A list of breaking changes considered and the evolution policy that applies.
Then work through this sequence, checking each item as it's done:
1: Draft the schema for the ten most important consumer flows, based on the prose call list. 2: Validate the schema mechanically (a linter, format validation, and a generated mock server). 3: Walk through error cases for each endpoint: unknown ID, unauthorized caller, invalid body, conflicting state, rate limit hit. 4: Serve the mock to at least one real client developer and revise the schema before implementation. 5: Implement against the schema, and add contract tests that fail when the live server drifts from the schema. 6: Publish generated docs alongside the schema and include a changelog that distinguishes additive from breaking changes. 7: Add deprecation headers and a documented sunset process before the first consumer is in production.
A concrete success check: an external developer can build a working integration against the mock server, without asking your team a question, and then switch the base URL to production and have it work unchanged. If that holds, the contract is doing its job. A failure signal to watch for: any endpoint whose documentation requires a paragraph of explanation about why it behaves differently from its neighbors.
Iterate on the schema, not on the docs. If the docs are long and the schema is messy, the schema is the problem.
FAQ
How much detail does the API contract need to include?
Enough that a competent developer can implement a client without contacting you. That means types, nullability, defaults, error codes, pagination semantics, rate-limit headers, and the stated policy for unknown fields and unrecognized enum values. It does not need to document internal implementation details or performance characteristics that might change.
Should a first interface support multiple authentication methods?
Usually no. Each additional method is another thing to test, rotate, and audit, and it multiplies the ways a consumer can accidentally be insecure. Pick one method per consumer category (public, partner, internal) and add others only when a real consumer with a real need appears.
When is it worth introducing a second protocol (for example, adding gRPC behind a REST surface)?
When a specific consumer's constraints cannot be met by the primary style—typically when internal service-to-service traffic needs lower overhead or stronger typing. Add the second protocol as a thin adapter and treat it as a distinct surface for versioning and documentation purposes—don't pretend it's the same API.
Does the resource/permission model need to be completed before the first endpoint ships?
The permission model for the endpoints you're shipping does, because retrofitting authorization is far riskier than designing it. The full model for every future resource can be sketched; what cannot wait is the answer to "what proves a caller may touch this specific resource."