← All articlesMUMITUL
Research Desk · RD-09

API Design and Development

13 min read·2,590 words

An API is a long-lived contract expressed in requests and responses. Once consumers build against an endpoint, its resource names, methods, status codes, and error shapes become commitments that are expensive to revise. Design quality is therefore less a property of the framework than of how predictably the interface behaves: whether a new consumer can infer the model from a few examples, and whether failures arrive in a form a program can act on.

This guide treats API design as applied protocol literacy: a synthesis of Fielding’s account of the REST architectural style, the IETF’s HTTP specifications, the OpenAPI Specification, and OWASP’s API security risk analysis. [1–8] Its scope is resource modeling, HTTP semantics, compatibility, structured errors, authorization, executable contracts, and privacy-conscious observability. Recommendations marked as synthesis are engineering practice derived from those sources, not requirements the sources impose. Where a specification leaves a decision open, the guide says so.

01 · Model resources around the domain, not the database

Fielding’s uniform interface constraint begins with the identification of resources. A resource is a conceptual mapping — an order, an invoice, a device — identified by a URI and manipulated through representations. [1] Paths should therefore name what the API is about, in consumers’ vocabulary, rather than mirroring the tables, queues, or services that store the data.

Collections and items form the basic grammar: a collection path names the set, and an item path adds the identifier. Relationships can be expressed by nesting, for genuine containment, or by links between resources. Deep nesting is fragile: it hard-codes one navigation path into every URL. Operations that do not map onto the standard operations on an item are usually better modeled as a resource of their own — a cancellation, a payment attempt, an export — than as a verb appended to a path.

Synthesis recommendation: derive the resource model from the tasks consumers perform, not from the current schema. Name resources that make the consumer’s questions and state changes addressable. If a consumer who knows two endpoints cannot guess a third, the model is probably encoding internal structure instead of domain structure.

02 · Let HTTP methods carry their specified meaning

RFC 9110 defines the semantics that methods and status codes carry. Safety means essentially read-only: GET, HEAD, OPTIONS, and TRACE qualify. Idempotency means repeated application has the same intended effect as one: PUT, DELETE, and the safe methods qualify, while POST is defined as neither safe nor idempotent. [2] These are not optional conventions; intermediaries, crawlers, and client libraries already act on them.

The consequences are operational. A GET endpoint that changes state can be fired by prefetching or automatic retries, producing changes nobody requested. A non-idempotent operation retried after a timeout can duplicate its effect, since the client cannot tell whether the first attempt succeeded. Status codes are equally specific: 201 with a Location header reports creation, 202 work accepted but not completed, 204 success with no content. The 4xx and 5xx classes tell a consumer whether resending the same request could ever succeed.

Synthesis recommendation: audit every operation against the specification’s definitions. Record each endpoint’s safety, idempotency, success code, and failure classes. Where a genuine requirement conflicts with the defaults — a query too large or sensitive for a URL, submitted with POST — document the deviation explicitly rather than redefining a method whose meaning the rest of the stack assumes.

03 · Design representations deliberately

A resource is not identical to any single representation of it. Content negotiation lets a client indicate acceptable media types and a server select a representation, returning 406 when it cannot comply and 415 when a request body arrives in an unsupported format. [2] Fielding makes the same distinction: components exchange representations of resource state, not the resource itself. [1]

Most representation defects are consistency defects. Field names that change convention between endpoints, identifiers serialized as numbers here and strings there, timestamps in mixed formats, and absent fields used interchangeably with null all force consumers to write defensive code the provider could have eliminated once. Identifiers should be treated as opaque strings, preserving the provider’s freedom to change how they are generated. Timestamps are better exchanged in the Internet date and time format defined by RFC 3339 than in local or ambiguous forms.

Synthesis recommendation: publish a short set of representation rules and apply them uniformly — naming convention, identifier handling, timestamp format, the meaning of null versus absent, and how errors differ from data. Consumers forgive a small vocabulary of shapes, not the same concept in a new shape at every endpoint.

04 · Preserve compatibility as the API evolves

Compatibility is a property of the consumer’s experience, not of the provider’s intentions. A change is breaking when an existing, correct consumer fails or silently misinterprets a response. Adding an optional field is normally safe; removing or renaming a field, changing its type, or narrowing accepted input is not. The hardest breaks are semantic: a field that keeps its name and type but begins returning values in different units passes schema checks while misleading consumers.

No HTTP specification mandates a versioning strategy. [2] Providers choose among a URI version identifier, media-type versioning, or disciplined additive evolution under one unversioned interface. Each trades visibility against longevity: an explicit version is easy to route and reason about but invites permanent parallel versions, while additive-only evolution avoids version sprawl at the cost of never correcting early modeling mistakes in place.

Deprecation is the managed end of compatibility: a process — announcement, migration guidance, a stated date, measured removal — not a surprise. The Sunset response header field, defined in RFC 8594, gives that date a machine-readable form. Removal decisions should rest on observed usage, which is why section 10’s observability practices belong to compatibility.

Synthesis recommendation: write the compatibility policy down. Define which changes need no new version, which require one, how long deprecated behavior runs, and how consumers will be told. Enforce it mechanically where possible: section 07’s contract diffing can flag a breaking change in review.

05 · Return errors a client can act on

RFC 9457 defines a standard format for HTTP API errors, obsoleting the earlier RFC 7807. A problem detail object carries five standard members: type (a URI identifying the problem kind), title (a short summary, stable for the type), status (mirroring the HTTP status), detail (specific to this occurrence), and instance (a URI identifying the occurrence). The media type is application/problem+json, and extension members let a problem kind carry structured data of its own. [5]

A validation failure, a rate limit, and an authorization failure arrive in the same shape at every endpoint, so consumers write one error-handling path instead of per-endpoint parsing. An extension member can, for example, list the fields a validation failure rejected and why, where client code can find it without reading prose. The type URI should be stable and documented, because programs will branch on it.

The detail member is written for people; programs that parse it for keywords will break when wording changes, so behavior should key on type and status instead. Error responses must not leak internals: stack traces, query text, and internal hostnames help an attacker map the implementation and help a legitimate consumer not at all. The instance member can carry a correlation identifier, letting a consumer quote a reference that support staff can match to server records.

Synthesis recommendation: adopt RFC 9457 as the single error format for the whole API. Exercise error paths in tests, not only success paths. An error model that differs between teams recreates, inside the failure case, the unpredictability the format exists to remove.

06 · Authenticate callers and authorize every request

The OAuth 2.0 authorization framework, RFC 6749, defines how a client obtains a scoped access token from an authorization server and presents it to a resource server. [7] Two distinctions are routinely blurred: OAuth 2.0 is an authorization framework, not an authentication protocol — identity layers such as OpenID Connect build on it — and a bearer token confers authority on whoever presents it, which is why the framework assumes protected transport and a leaked token is a credential leak.

Scopes answer a general question — what may this token do — but not the specific one: may this caller act on this object? OWASP’s API Security Top 10 for 2023 places Broken Object Level Authorization first among API risks. It describes endpoints that accept object identifiers from the client without verifying the authenticated caller’s rights to the object. [8] The failure is common because the code looks correct — caller authenticated, object found, operation successful — while ownership was never checked.

Synthesis recommendation: evaluate authorization on the server, on every request, at the point where the object is accessed. Deny by default, grant the least privilege a token’s purpose requires, and test authorization as rigorously as functionality: for each endpoint, attempt the operation with another consumer’s identifier and confirm refusal. An API whose object graph can be walked by changing an identifier has published its data, whatever its documentation says.

07 · Publish an executable contract and test against it

The OpenAPI Specification defines a standard way to describe an HTTP API: paths, operations, parameters, request and response schemas, and security schemes. Version 3.1.0 aligned the schema language with JSON Schema draft 2020-12, so payloads are described with a widely implemented standard. [6]

A contract is executable when tools consume it. The same document can render reference documentation, generate client libraries, stand up a mock server, and drive validators that check test traffic against the declared schemas. These uses impose a discipline prose never does: imprecision surfaces as a tooling failure, not as a consumer’s support ticket months later.

The recurring failure mode is drift. A description maintained by hand gradually stops describing the API as the code changes, and consumers learn to distrust it. Two working patterns prevent this: generate the description from the implementation, or test the implementation against a description maintained as the source of truth. Comparing successive versions of the document also operationalizes section 04, since breaking changes can be detected mechanically in review.

Synthesis recommendation: treat the OpenAPI document as a release artifact — versioned, reviewed, and diffed like code, with contract tests running in the delivery pipeline. Keep its limits in view: a schema validates shape, not meaning, so contract testing complements rather than replaces tests of behavior.

08 · Use caching and conditional requests intentionally

HTTP caching is standardized behavior, not an optimization added afterward. RFC 9111 defines how responses are stored and reused by private caches (one user) and shared caches (many users), together with the freshness model that governs reuse. [3] The mechanism only works because section 02’s semantics hold: defined safety and idempotency make reuse predictable.

Cache-Control carries the policy. Per-user or sensitive responses can be marked private or no-store; stable reference data can carry an explicit freshness lifetime. Validators complete the model: an ETag identifies a response’s current representation, and RFC 9110’s conditional requests let a client present it back. If-None-Match on a retrieval returns 304 when nothing changed. If-Match on a write returns 412 when the resource changed underneath the client, giving optimistic concurrency control without application-specific locking endpoints. [2]

Caching also intersects with authorization. Under RFC 9111, a shared cache must not store a response to an authorized request unless the response explicitly permits it: one consumer’s private representation must never reach another. [3]

Synthesis recommendation: decide the cache policy per class of resource, not per incident. Record which responses are public, which private, and which must never be stored; assign validators to representations consumers poll; use conditional writes wherever concurrent editing is possible. Then test the directives actually emitted.

09 · Make large collections and repeated requests safe

Collections need bounded responses, so pagination is part of the interface contract. Offset pagination is simple and adequate for small, stable sets, but it can skip or repeat items as the collection changes, and grows expensive deep into large sets. Cursor pagination anchors each request to the previous response’s last item, keeping iteration consistent while data changes, at roughly constant cost. No HTTP specification mandates either approach. [2] A stable ordering is not optional: pagination over an unordered collection is meaningless.

Overload needs an equally explicit contract. RFC 6585 added the 429 status code; combined with the Retry-After header, it converts a failure into an instruction about when to try again. [2,4] The goal is graceful degradation, not retry storms that amplify the load that caused the rejection.

Because POST is not idempotent, a client that times out cannot know whether its request was processed. The practical remedy is a client-supplied idempotency key: the server records the key with the outcome, and a duplicate request returns that outcome instead of executing twice. A proposal before the IETF would standardize an Idempotency-Key header field; until then it is a local convention that only protects consumers who are told about it, so it belongs in the contract, not in folklore.

Synthesis recommendation: define the collection contract once — pagination mechanism, ordering guarantee, filtering conventions, and how totals are reported — and apply it everywhere. Treat idempotent retry as designed behavior wherever duplication would cost money, send messages, or create records.

10 · Observe the API without recording what should stay private

Observability data is itself data about consumers. Logs, metrics, and traces reveal who called what, when, and often with which parameters. Privacy-conscious observability therefore starts with restraint about content: record route templates such as /orders/{id} rather than raw URLs, which can carry tokens and personal values; never log authorization headers or credentials; and treat request and response bodies as personal data until shown otherwise.

What should be measured follows from the earlier sections. Request volume and error rates by status class and problem type show where consumers struggle; latency distributions show whether the interface performs as documented; adoption by API version and by endpoint supplies the evidence that deprecation decisions in section 04 require. The correlation identifier carried in a problem detail’s instance member connects a consumer’s report to server-side records without exposing internal detail. [5] Vendor-neutral instrumentation such as OpenTelemetry lets this evidence be collected in standard shapes.

Retention completes the discipline. Observability records are a secondary store of consumer behavior, deserving their own access controls and retention limits; a log kept forever for debugging convenience is a liability with no corresponding benefit.

These commitments support one another. Resource modeling supplies the vocabulary; HTTP semantics, the grammar; compatibility and structured errors, intelligibility as the contract changes; authorization, its boundaries; the executable contract, testability; caching and safe repetition, economy; and restrained observability, evidence that it works — without betraying the consumers it serves. Remove any layer and the others weaken; keep them together, and the interface can evolve without asking consumers to relearn it.

Sources

[1] R. T. Fielding, “Architectural Styles and the Design of Network-based Software Architectures,” doctoral dissertation, University of California, Irvine, 2000. [2] R. Fielding, M. Nottingham, and J. Reschke, “HTTP Semantics,” RFC 9110, IETF, 2022. [3] R. Fielding, M. Nottingham, and J. Reschke, “HTTP Caching,” RFC 9111, IETF, 2022. [4] M. Nottingham and R. Fielding, “Additional HTTP Status Codes,” RFC 6585, IETF, 2012.

[5] M. Nottingham, E. Wilde, and S. Dalal, “Problem Details for HTTP APIs,” RFC 9457, IETF, 2023. [6] OpenAPI Initiative, “OpenAPI Specification,” version 3.1.0, Linux Foundation, 2021. [7] D. Hardt, ed., “The OAuth 2.0 Authorization Framework,” RFC 6749, IETF, 2012. [8] OWASP Foundation, “OWASP API Security Top 10,” 2023 edition.

More articles at mum.name/blog