Skip to content

Core system concepts · Concept lesson

API design

Design stable interfaces around resource meaning, explicit operation semantics, validation, compatibility, and reliable client behavior.

Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.

Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.

What you will be able to explain

  • Choose request and response semantics that clients can safely interpret.
  • Design validation, pagination, versioning, and error behavior.
  • Explain compatibility and idempotency decisions for an API change.

How an API contract works

An API is a contract between independently changing programs. Its design defines what a caller may ask, what the service promises to do, and how both sides interpret success, conflict, and failure. Start from domain operations rather than endpoint fashion: identify the resource or command, authorization boundary, input constraints, and durable effect. HTTP method semantics provide useful expectations, but the application must still define details such as whether a delete is reversible or whether a create returns a canonical resource. Responses should distinguish validation errors, missing resources, conflicts, and temporary unavailability in a predictable shape. Pagination, filtering, and sorting need explicit limits so one request cannot demand unbounded work. Document units, nullability, time zones, and enum evolution. The contract is not merely an OpenAPI file: clients also depend on ordering, idempotency, rate limits, and consistency guarantees. A good interface makes correct use easier than accidental misuse.

API contract and implementation
1. Client

Sends a request using the published contract.

2. API contract

Defines input, output, errors, limits, and operation semantics.

3. Service boundary

Authenticates, validates, and applies domain rules.

4. Authoritative state

Persists the result under domain invariants.

5. Response

Communicates result or actionable failure.

  1. Client → API contract: request
  2. API contract → Service boundary: defined semantics
  3. Service boundary → Authoritative state: validated operation
  4. Authoritative state → Response: durable outcome
  5. Response → Client: status and representation

Worked example: creating a reservation

Consider POST /reservations with a seat identifier and a client-generated operation key. The server validates the identifier, authenticates the user, checks availability, commits a unique reservation, and returns 201 with a resource location and reservation representation. If the same key and same request are repeated after a dropped response, return the recorded outcome; if the same key is reused with different content, return a documented conflict. A request limit of 100 results per page means a client can never ask for an unbounded list. If 2,350 reservations match, a cursor can return at most 100 per request, requiring at least ceiling(2,350 ÷ 100) = 24 pages if the result set remains stable. In a changing dataset, an opaque continuation token may encode a consistent position rather than an offset. Include units (for example, durationSeconds) instead of an ambiguous number, and use an explicit UTC timestamp representation. These details prevent client teams from guessing at behavior.

Alternative interface styles

Resource-oriented HTTP APIs fit independently addressable entities and standard tooling. RPC-style endpoints can make commands explicit, especially when an operation is not naturally CRUD, but should still name stable semantics and authorization rules. GraphQL lets clients select response fields and can reduce over-fetching, while requiring depth, complexity, and resolver-load controls. Event APIs communicate durable facts asynchronously, but consumers need schema evolution and delivery semantics. A synchronous API is useful when callers need an immediate decision; an accepted job plus status resource is better for work that can take minutes. Versioning can use additive changes, media types, or explicit major versions; no strategy removes the need to identify breaking changes. Choose based on client diversity, operational limits, and domain shape. Avoid placing every use case into a generic endpoint that becomes an unversioned query language, or multiplying endpoints so every presentation concern becomes a permanent server contract.

Failure and recovery

A client may disconnect after the server commits, so a failed transport does not establish a failed operation. Define idempotency or operation-status behavior for effects clients might retry. Validation errors should identify the field and constraint without returning stack traces or sensitive internals. Rate limiting should explain whether the caller can retry and when, while retries remain bounded and respect the original deadline. A stale client may send an enum value or field the new server does not understand; reject or ignore unknown values according to the schema's documented evolution policy. If a response is partially available, do not silently claim complete success. For APIs backed by several services, a partial failure may need a structured result or asynchronous workflow rather than a misleading 200. Preserve correlation IDs for support, but do not expose internal topology. Recovery should be possible through a stable read or status endpoint, not by requiring clients to infer state from an error string.

When not to add API complexity

Do not introduce a public, versioned API for an internal function that has one owner and can be changed atomically with its caller; an in-process interface may be simpler. Do not expose every database column just because it exists. Public contracts become difficult to remove, and clients may rely on accidental behavior. Avoid speculative filters, arbitrary sort expressions, or caller-controlled query plans without resource bounds. A separate version for a harmless additive field can fragment clients and operations unnecessarily; a shared compatibility policy is usually more effective. Conversely, do not disguise a semantic change as an additive field if existing clients interpret the result differently. Choose the simplest contract that meets real consumer needs while making authorization and workload costs explicit. An API should not become an abstraction that hides an unstable domain model behind vague names such as “process” or “data.”

Senior followups

Review whether each operation has a clear owner, authorization check, and state transition. Ask how clients recover after an ambiguous timeout, whether idempotency keys are scoped and retained long enough, and what happens when two requests use the same key differently. Check pagination under inserts and deletes, maximum page size, query cost, and cursor confidentiality. For compatibility, inventory client versions and define deprecation communication before removing fields. Inspect schema generation against actual runtime validation; a declarative contract that differs from code can create false confidence. Consider error stability: clients should branch on a documented code, not prose. Evaluate resource exhaustion from expensive filters and nested queries. Finally, test an old client against the new service and a new client against the old service where deployment order can vary. Senior API design spends effort on the lifecycle of the contract, not only on its first successful request.

Operational practice

Publish examples for success, validation failure, conflict, throttling, and ambiguous operation recovery. Validate requests at the boundary, enforce authorization on the server, and apply request-size and query-cost limits before expensive work. Record route templates and bounded result codes in metrics. Maintain dashboards for latency percentiles, status categories, throttling, and client-version distribution; do not make a metric label from arbitrary user input. Contract tests can verify schema compatibility, while integration tests prove important state transitions and authorization. Add a new field in a way that old clients can ignore, then observe adoption before considering removal of its predecessor. Treat a generated API schema as an artifact to review with consumers. During an incident, communicate which operations are safe to retry and offer a status lookup for writes. Clear operational guidance is part of the API contract because callers need to respond correctly when the happy path ends.

Terms in plain language

Idempotent method
A method whose intended effect from repeated identical requests is the same as from one request, under its defined semantics.
Compatibility
The ability of existing clients and servers to continue interacting correctly after a change.
Pagination
A protocol for returning a bounded portion of a larger result set and continuing through it.
Contract
The documented request, response, error, and behavioral expectations shared by API producers and consumers.

Preparing practice controls…

Check your understanding

These checks explain concepts. They do not measure architecture seniority or update readiness.

1. A client loses its connection after a create request may have committed. Which API behavior most directly supports safe recovery?
2. Why should a paginated API enforce a maximum page size?

Design independently

Design an API for creating and retrieving a long-running report. Include request and response behavior, pagination or status, retry safety, validation, and one compatibility strategy.

Hints, not a solution
  • Separate acceptance of work from completion of work.
  • Define behavior if the acceptance response is lost.
  • Bound report size and protect sensitive fields at both read and creation boundaries.

0 / 20,000 characters · Not saved

Your learning notes

Sign in to save

Marking a lesson read and reviewing an exercise are separate actions. Neither implies mastery. Saved work is account-owned; saves are explicit and do not queue offline.

References and boundaries

Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.

RFC 9110: HTTP Semantics

Primary standard for HTTP method and status semantics.

OpenAPI Specification

Primary specification for describing HTTP API contracts.

Back to curriculum