Product engineering

Write an API Contract Before Building the Endpoint

Define an API operation through caller intent, field meaning, error outcomes, authorization, examples and compatibility before implementation.

An API contract describes what a caller can rely on before either side depends on an implementation detail. It should explain the request, the possible outcomes and the meaning of the returned data. Starting with that agreement helps teams find ambiguous behavior while changing it is still inexpensive.

The OpenAPI Specification provides a formal description format for HTTP APIs. A valid description is useful, but it does not automatically establish a good product contract. The team still needs to decide what the operation means, how failures behave and which changes would surprise an existing client.

Begin with one caller’s task

Choose a concrete operation and identify who calls it. For a fictional scheduling product, a client might need to create an appointment for an available time slot. Describe the caller’s goal before selecting a route name or response shape.

Write down the information the caller already has and the information it needs from the operation. Does it know a customer identifier, a service identifier and a timezone? Does it need a confirmed appointment immediately, or only an acknowledgment that the request was accepted for later processing?

Avoid designing a generic endpoint that attempts to satisfy every imagined future workflow. A bounded first operation makes the contract easier to review. Broader reuse can emerge from real requirements rather than from a large collection of optional fields whose interactions nobody has tested.

Define the operation’s success condition

State what must be true when the operation reports success. If the response says an appointment is confirmed, the system should have completed the work required to make that statement. If processing continues asynchronously, use language and a response model that make that state visible.

Distinguish the resource’s state from the transport outcome. A successful HTTP exchange can return an application state such as pending, while a failed exchange may leave the caller uncertain whether the server completed the operation. That uncertainty needs a deliberate retry and lookup strategy.

For the scheduling example, describe whether availability is checked atomically with creation and what happens when two callers request the same slot. The contract should expose a clear result for the losing request rather than leaving clients to infer a race from an undocumented error string.

Choose identifiers and field meanings carefully

Define identifiers as stable references with a documented scope. A display name is usually a poor substitute when names can change or collide. Explain whether an identifier is unique within an account, environment or entire service.

For each field, record its meaning, type and constraints. A timestamp needs a timezone convention. A duration needs a unit. A monetary amount needs a currency and representation. These details are part of the contract, not implementation trivia to be discovered through examples.

Distinguish omitted, empty and null values where the difference matters. A missing optional note may mean leave the existing value unchanged during an update, while an explicit empty value may mean clear it. If the operation does not support that distinction, say so and keep the behavior consistent.

Make request validation predictable

Document required fields, permitted values and relationships between inputs. An end time after a start time is a semantic rule that a basic type declaration may not fully express. Identify those rules in the operation description and tests.

Decide how the server handles unknown fields. Silently ignoring a misspelled field can make clients believe a requested change occurred when it did not. Rejecting unknown fields can improve clarity but may affect compatibility strategies. Choose deliberately and explain the policy.

Keep validation messages useful without exposing internal implementation details. A caller should be able to identify the field or condition it can correct. It should not need to parse a database exception or receive sensitive information about another customer’s resources.

Design errors as part of the interface

List the expected failure categories: invalid input, missing permission, unavailable resource, conflict and temporary service failure. Define a stable machine-readable code where clients need to branch, alongside a human-readable explanation suitable for debugging.

Avoid asking clients to interpret arbitrary message text. Wording may change for clarity or localization. A stable code and structured detail make the contract more durable, provided the team maintains their semantics.

Explain which failures are retryable and under what conditions. A validation error will not improve through immediate repetition. A temporary dependency failure may be retryable, but a create operation also needs a way to avoid duplicate effects. Connect this decision to the operation’s idempotency design rather than treating retries as a client-only concern.

Specify authentication and authorization boundaries

Describe the supported authentication mechanism and the authorization required for the operation. The contract should make clear which account or tenant owns the resource and how that scope is established.

Do not rely on a caller-supplied identifier as proof of permission. The implementation must enforce access, while the contract should explain the legitimate relationships between caller and resource. Include examples that do not expose real credentials or customer identifiers.

Define how unauthorized and unavailable resources are represented according to the service’s security policy. The choice may need to avoid revealing whether another account’s resource exists. Keep that policy consistent so clients receive predictable behavior without gaining unintended information.

Write examples that cover more than the happy path

Provide a minimal valid request and a representative success response. Then add examples for meaningful variations: an optional field, an empty result, a conflict or a request that fails validation. Use synthetic values with clearly fictional identities.

Check that examples match the schema and the prose. A field shown in an example but absent from the description creates an accidental promise. Conversely, a required field omitted from every example teaches callers the wrong shape.

Examples should demonstrate meaning, not merely syntax. For a timestamp, include a clear timezone representation. For a pending operation, show the field or link used to check progress. A compact example that answers a real caller question is more useful than a large payload filled with unexplained fields.

Review the contract from both sides

Ask a prospective client implementer to describe how they would call the operation, handle each outcome and recover from a timeout. This reveals ambiguities that a server-focused review may miss. The reviewer should not need private knowledge of the planned database design.

Ask the server team to identify promises that are expensive or difficult to guarantee. A response field that appears harmless may require an additional dependency call or a consistency guarantee the architecture does not provide. Resolve the mismatch before clients build against it.

Record decisions and open questions. An unresolved item should not quietly become a default behavior because somebody started coding first. Assign an owner and decide whether the operation can proceed without that question being settled.

Use the description to guide implementation checks

Validate the OpenAPI document with tooling appropriate to the selected version, then use it as one input to contract tests. Check request validation, response shape and documented error outcomes. A syntactically valid document is only the beginning of verification.

Test semantic behavior separately. A schema can show that a status field is a string from an allowed set, but it does not prove that confirmed means the appointment was actually reserved. Use application-level tests for the promises that matter to the caller.

Keep generated clients and documentation aligned with the same approved contract where possible. Review generated output for usability rather than assuming generation guarantees a good developer experience. Naming, optionality and error handling still affect the people integrating with the service.

Plan how the contract will change

Decide which changes are compatible for existing clients and how incompatible changes will be introduced. Adding an optional response field may be safe for clients that tolerate unknown fields, but other changes can alter meaning without changing the schema’s shape.

Treat changed defaults, new enum values and altered ordering as deliberate compatibility decisions. A client may have relied on behavior that was poorly documented. Use evidence from real consumers and communicate changes through the service’s maintained process.

Keep a versioned history of the contract and connect it to releases. When a production response differs from the description, investigate which side is wrong and correct it explicitly. Documentation drift should not be normalized as an unavoidable feature of APIs.

Finish with a caller-ready agreement

Before implementation is considered ready, confirm that a new client can understand the operation without asking for hidden conventions. It should know what to send, what success means, how to interpret failures and how to recover from uncertainty.

That agreement does not need to anticipate every future feature. It needs to be precise about the current one. A well-reviewed contract gives both teams a shared target and makes later changes easier to discuss in terms of observable behavior rather than accidental implementation details.

Continue reading

Design Idempotent Requests for Retried Operations

Model a Background Job Before Choosing a Queue