API Design
An API is a promise between independently failing programs.
What, why, when and how
What is it?
API design specifies how callers request operations, provide inputs, receive results and interpret failures.
Why is it needed?
Without an explicit contract, a retry can create duplicate work and different clients can interpret the same timeout or status differently.
When should I use it?
Use it at every service boundary and whenever independent clients need pagination, versioning, authorization or asynchronous status.
When should I choose something else?
Do not expose internal tables as an API by default. Avoid a new protocol or service boundary when an in-process interface meets the requirement.
How do I use it?
Define resources and tenant scope, validate inputs, choose synchronous or asynchronous responses, and specify idempotency, errors, pagination and concurrency preconditions.
Can you show a concrete example?
Two editors read notice n40 at version 3. The first conditional update produces version 4. The second sends the old version and receives a conflict response instead of silently overwriting the first change.
Read the diagram
A and B both read notice n40 at version 3; A submits v3: accepted; record becomes v4; B submits v3: conflict; v4 is preserved
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
An API is a promise between independently failing programs. Its path names are less important than what a successful response means, which errors can be retried, and how callers discover the result after a timeout. Design the contract before distributing implementation work. A precise contract makes both the happy path and the uncertain path understandable.
Learning goals
Resources and commands; request/response contracts; authentication versus authorization; validation; cursor pagination; idempotency scope; retryable errors; versioning.
Choose an interface by the caller's work
REST models resources and uses HTTP semantics. For our notice service, GET /notices/n40 reads a representation; query parameters select fields, filters and continuation. POST /notices creates a new intent. PUT /notices/n40 replaces the defined representation; PATCH changes fields under a declared patch format. DELETE requests removal under the retention contract. Safe means the client did not request a state change. Idempotent means repeating the same intended operation has the same intended effect, not necessarily the same response or zero logging. POST can be made retryable with a scoped key; that is an application contract, not a property of every POST.
Put the identity in the path, search controls in query parameters and a structured new resource in the body. Put authentication and conditional request metadata in headers. Sensitive tokens do not belong in URLs that proxies and analytics commonly record. Validate sizes, types and supported fields before accepting work. An illustrative contract is:
GET /notices/n40?fields=id,state HTTP/1.1
Authorization: Bearer <token>
HTTP/1.1 200 OK
ETag: "notice-v3"
Content-Type: application/json
{"id":"n40","state":"draft","version":3}Read the diagram
A and B read notice n40 at version 3; A: If-Match v3 -> commit version 4; B: If-Match v3 -> 412; version 4 preserved; REST: bounded notice representation; GraphQL: selected fields; bounded nested work; RPC: typed method; safe retry still required
Two editors read version 3. A edits the title using If-Match: "notice-v3"; the authority commits version 4. B's later request with the old ETag receives 412 Precondition Failed under this contract. B fetches version 4 and decides whether to merge. The server must couple the version comparison to the update; reading version 3 and later writing without a condition recreates the race.
GraphQL lets the caller select a typed response shape. This is useful when different clients need different combinations of data, but the schema is not a free database join. This selection might return only the ID and two deliveries:
query NoticePage($id: ID!) {
notice(id: $id) { id deliveries(first: 2) { nodes { id state } } }
}Authorize both the notice and nested deliveries. Cap first, query depth and estimated work; batch related resolver reads to avoid one lookup per row. Decide how partial field errors and cached representations behave. A simple resource endpoint is easier when clients need one stable bounded representation.
RPC models named operations and typed messages. A protobuf sketch for an internal caller is:
service Notices { rpc GetNotice(GetNoticeRequest) returns (Notice); }
message GetNoticeRequest { string id = 1; }
message Notice { string id = 1; string state = 2; int64 version = 3; }gRPC commonly carries protobuf messages over HTTP/2 and supports deadlines and streaming. Types help integration, but do not prove authorization or safe retries. Keep field-number evolution compatible; never recycle an old field number for a different meaning. Prefer this when internal typed operations or streaming justify its tooling cost.
Make errors and page boundaries usable
Return a stable machine code and a request ID, for example {"code":"idempotency_conflict","requestId":"q7"}. Distinguish validation failure, authentication, denied access, missing resources, state conflict, precondition failure and throttling. Avoid revealing another tenant's existence where the access policy requires indistinguishable denial. A retryable 503 still requires a safe operation identity, a deadline and a retry budget. A 429 identifies the quota scope and gives retry guidance.
Filter and sort fields must be allowlisted and indexed where needed. An opaque cursor binds (created_at,id) to the tenant and filter; it does not grant access. Offset 100,000 can require walking many earlier rows, and concurrent inserts shift page boundaries. Keyset continuation avoids that particular shift; deletions and changing ranking still require a declared snapshot or best-effort browsing contract.
Show answer and explanation
Answer: If the second editor retries with the old ETag, keep version 4 intact and return the conflict. A new idempotency key cannot bypass the version check. If a GraphQL request asks for 10,000 deliveries, enforce the same bounded access promise rather than trusting its typed syntax.
Primary documentation: HTTP methods, conditional requests and status semantics, GraphQL security and demand controls, and gRPC methods and call lifecycles. These contracts do not make an arbitrary application operation safe to retry.
Step-by-step reasoning
1. Define resources and scope
For a notice service, POST /notices creates an intent and GET /notices/{id} reads its status. The authenticated principal supplies the tenant context; do not trust a tenant ID in the body as proof of access. Authentication identifies the caller. Authorization checks whether that caller may perform this action on this particular notice, including every read and download.
2. Make creation retryable
Accept an idempotency key scoped to tenant and operation. Store a request fingerprint and the resulting resource ID atomically with creation. A repeated key with the same payload returns the original outcome; a changed payload conflicts. Define retention explicitly: an expired deduplication record cannot protect retries forever. Concurrent requests using the same key must meet a unique constraint or equivalent atomic decision.
3. Return honest states and errors
A 202 response should mean the job was durably accepted, not that it was delivered. Provide a status resource for queued, processing, completed, and failed outcomes. Distinguish malformed input, denied access, state conflicts, throttling, and temporary dependency failure. Do not automatically retry every 4xx or every non-idempotent request. Document rate-limit scope and retry guidance.
4. Paginate and evolve
Use a stable ordering with a tie-breaker, such as created_at and id. A cursor encodes the position plus relevant filter or snapshot context; validate it and avoid exposing sensitive internals. Offset pagination can skip or duplicate entries when rows shift. Add optional fields compatibly, tolerate unknown response fields, and version semantics when their meaning changes rather than renaming paths for every addition.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
POST /notices
Idempotency-Key: school42-announcement7
{ "audienceId": "grade8", "templateVersion": 3 }
202 Accepted
{ "id": "n_92", "status": "queued" }
GET /notices/n_92/deliveries?after=<opaque-cursor>Worked example
Two requests arrive with the same creation key before either sees a saved result. A preliminary lookup is insufficient: both may observe “missing.” Put the idempotency record and notice creation in one transaction with a unique key on tenant, operation, and key. One request wins. The other waits or receives an in-progress response and later resolves to the same notice. If the API publishes a queue message too, close the database-to-broker gap with an outbox.
Failure walkthrough
Authorization is not inherited from a list page. A caller can change an ID manually and ask for another tenant’s notice. Recheck object ownership on the read endpoint. Similarly, a cursor from one tenant must not be usable to cross tenant boundaries. Log denials without recording message bodies or secret tokens; diagnostics should not create a second data leak.
Read the diagram
Request key K arrives → Create notice + key atomically → Response times out → Retry K with same body → Return original notice ID
Decisions and trade-offs
| Contract | Decision | Why |
|---|---|---|
| Creation | Durable acceptance | Separates API latency from delivery time |
| Duplicate key | Return original result | Protects ambiguous retries |
| Changed payload | Conflict | Prevents accidental reuse of an old identity |
| Pagination | Stable cursor | Bounds scans and describes continuation |
Check your understanding
A client retries a notice with the same key but a changed audience. Should the service overwrite the first notice?
Show answer and explanation
Answer: No. Reject the mismatched fingerprint and require a new key for new intent. Silently overwriting changes the meaning of an operation the first caller may already believe was accepted.
Transfer to a new scenario
Create a notice with an idempotency key, reject a changed payload using the same key, and paginate deliveries.
A caller knows another tenant's notice ID. Which authorization check prevents access?
Continue the connection
Study Data Modeling and explain which guarantee from this lesson carries into that topic.
Design a retryable resource contract
Consider creating an export job. The first POST authenticates the caller, validates tenant ownership and stores both the job and its idempotency key in one transaction. A retry with the same key and fingerprint returns the same job ID. A different body under that key returns a conflict. A 202 response means durable acceptance under the stated contract, not completed export. Expose queued, running and terminal states through a separate resource.
For pagination, use a stable ordering such as (created_at,id). Encode the last pair in an opaque cursor and keep the tenant and filter context bound to it. Offset pagination gets expensive at large offsets and can skip or repeat rows as new data arrives. An opaque cursor is not an authorization token: every page still needs access checks.
Version the contract when meaning changes. Adding an optional field is often compatible; reinterpreting an existing enum value may not be. Publish error semantics, retry hints, rate limits and maximum request size. Use conditional updates with a version or ETag to avoid overwriting another editor’s change.
Read the diagram
Contract / Decision / Why; Creation / Durable acceptance / Separates API latency from delivery time; Duplicate key / Return original result / Protects ambiguous retries; Changed payload / Conflict / Prevents accidental reuse of an old identity; Pagination / Stable cursor / Bounds scans and describes continuation
Operational sketch
POST /exports
Idempotency-Key: tenant42-export17
{format:"csv", filter:{schoolId:"s1"}}
202 {id:"e17",state:"queued",statusUrl:"/exports/e17"}
PATCH /exports/e17 with expectedVersion=3A tempting mistake
A successful HTTP status alone does not define durability. Likewise, GET should not trigger an irreversible business mutation merely because it is convenient. Distinguish malformed input, forbidden access, state conflict, quota rejection and temporary service failure so clients can act safely.
Transfer exercise
A client reuses an idempotency key with a different export filter. Should you return the old result?
Show answer and explanation
Answer: No. Compare the stored request fingerprint and reject the conflicting reuse. Otherwise the caller may believe the returned export matches the new request.
Shared foundation: Idempotency and Delivery Semantics
Idempotency and Delivery Semantics: Scope operation identities, couple deduplication to effects and resolve uncertain provider outcomes. Work its failure history before extending this design.
Shared foundation: Security and Tenant Isolation
Security and Tenant Isolation: Enforce trusted tenant, object and field permissions across APIs, caches, projections and asynchronous work. Work its failure history before extending this design.
Shared foundation: Schema, API and Event Evolution
Schema, API and Event Evolution: Test mixed-version contracts, semantic meaning, retained replay and identity-preserving rollout or rollback. Work its failure history before extending this design.
A client retries a notice with the same key but a changed audience. Should the service overwrite the first notice?
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.