An API contract is the formal, shared agreement between an API provider and its consumers that defines which operations exist, what requests they accept, what responses and errors they return, and which behavioral guarantees hold. In the field of APIs within programming, the contract is the stable boundary that lets independent teams build against a service without reading its implementation.
A contract can live only in prose documentation, but mature teams express it in a machine-readable specification such as OpenAPI, AsyncAPI, a Protocol Buffers schema or a GraphQL schema. That form allows validation, code generation, mocking and automated compatibility checks in the delivery pipeline.
What an API contract specifies
An API contract specifies every observable interaction a client may rely on, not merely the shape of the payloads. The structural part covers endpoints, methods, parameters, field types and status codes, while the semantic part covers meaning, ordering, idempotency and limits that a schema alone cannot express.
The following table lists the main elements and why each one matters to a consumer.
| Element | What it defines | Why consumers depend on it |
|---|---|---|
| Operations | Paths, methods, RPC names or event channels | Clients must know what they can call |
| Request schema | Required and optional fields, types, formats | Invalid input is rejected predictably |
| Response schema | Fields, nullability, enumerations | Parsers and generated models stay correct |
| Error model | Status codes, error bodies, retry hints | Clients can recover or report failures |
| Security | Authentication schemes, scopes, API key placement | Access is granted consistently |
| Behavioral rules | Idempotency, ordering, pagination, rate limits | Retries and paging do not corrupt data |
| Service levels | Latency, availability, deprecation notice period | Consumers can plan capacity and migrations |
The implicit contract is often larger than the written one. Clients start to depend on field order, default sort order or timing, an effect often called Hyrum’s law: with enough users, every observable behavior becomes something somebody relies on. Good contracts therefore state explicitly which behaviors are guaranteed and which are incidental.
Contract formats and specification languages
The choice of specification language follows the API style, because each format models a different interaction pattern. Request and response APIs, event-driven APIs and query APIs each have a dominant description format.
| Format | API style | Typical artifact | Strength |
|---|---|---|---|
| OpenAPI | REST API over HTTP | YAML or JSON document | Broad tooling for docs, mocks and clients |
| AsyncAPI | Event-driven messaging | Channel and message definitions | Describes topics, brokers and payloads |
| Protocol Buffers | gRPC | .proto files | Compact binary encoding with field numbers |
| GraphQL SDL | GraphQL | Schema definition file | Strong typing and introspection |
| WSDL | SOAP | XML service description | Strict typing for legacy enterprise systems |
| JSON Schema | Payload validation | Schema per message | Reusable across many transports |
These formats describe structure well but capture behavior only partially. Idempotency, consistency and side effects usually need written documentation or executable examples next to the formal specification.
Contract-first and code-first development
Teams produce an API contract either before the implementation (contract-first) or from the implementation (code-first). The contract-first approach is closely tied to API-first design, in which the specification is reviewed with consumers before any server code exists.
- Contract-first: the specification is the source of truth; server stubs, client SDKs and API mocking servers are generated from it, so frontend and backend work can proceed in parallel.
- Code-first: annotations or reflection in the server code generate the specification; this is faster for small internal services but tends to leak implementation details into the public interface.
- Hybrid: a reviewed specification drives development, and a pipeline step fails the build when generated output and code drift apart.
Whatever the workflow, the contract is only trustworthy when it is verified automatically. Consumer-driven contract testing, in which each consumer publishes its expectations and the provider verifies them in continuous integration, catches breaking changes before deployment rather than in production.
Breaking and non-breaking changes
A change breaks an API contract when an existing, correctly written client stops working or starts producing wrong results. The general rule is that providers may widen what they accept and add to what they return, but may not narrow inputs or remove outputs.
| Change | Compatibility | Reason |
|---|---|---|
| Add an optional request field | Non-breaking | Existing requests remain valid |
| Add a response field | Usually non-breaking | Tolerant readers ignore unknown fields |
| Make an optional field required | Breaking | Old requests now fail validation |
| Remove or rename a response field | Breaking | Clients reading it receive nothing |
| Add an enumeration value | Often breaking | Strict switch statements may fail |
| Change a field type | Breaking | Parsers and generated models fail |
| Tighten a rate limit | Behaviorally breaking | Working clients start receiving errors |
Breaking changes are handled through API versioning, a deprecation period and clear communication. In gRPC, the equivalent rule is never to reuse or renumber field numbers, because the binary encoding identifies fields by number rather than by name.
How an API contract relates to neighboring concepts
The API contract is often confused with API documentation or with the specification file itself. Documentation is a human-readable presentation of the contract, and the specification is one encoding of it; the contract is the underlying promise that both should represent faithfully.
| Concept | Relationship to the contract | Main audience |
|---|---|---|
| API documentation | Explains the contract with guides and examples | Developers integrating the API |
| OpenAPI document | Machine-readable encoding of the contract | Tools and pipelines |
| SDK | Client code generated or written against the contract | Application developers |
| Contract testing | Verifies that both sides honor the contract | Provider and consumer teams |
| Service level agreement | Commercial commitment on availability and support | Business stakeholders |
Common mistakes with API contracts
Most contract failures come from drift between the documented and actual behavior, not from a missing specification. The following mistakes recur across teams and API styles.
- Undocumented error formats: clients cannot distinguish retryable errors from permanent ones.
- Exposing database models directly, so every schema migration becomes a contract change.
- Strict deserialization on the client, which turns harmless additive changes into outages.
- Silent behavior changes, such as a new default sort order, made without a version or notice.
- Specifications that are never validated against the running service in continuous integration.
A non-technical view
An API contract works like the menu and house rules of a restaurant. The menu says which dishes exist, what each one contains and what it costs. The house rules say how to order and what happens when a dish is unavailable. Guests do not need to see the kitchen to order successfully.
If the kitchen quietly removes a dish or changes an ingredient, regular guests are surprised and some leave unhappy. The key idea is predictability: as long as both sides respect the written agreement, each side can change its own internals freely.
A concrete example
A logistics company runs a shipment-tracking service used by its own mobile app and by about forty partner integrations. The team writes the contract first as an OpenAPI 3.1 document, reviews it with two partner developers and generates a mock server, so the mobile team builds its screens two weeks before the backend is ready.
Six months later, a developer proposes renaming the eta field to estimatedArrival. The compatibility check in the pipeline flags the change as breaking and blocks the merge. The team instead adds the new field, marks eta as deprecated with a six-month removal date and announces the change. No partner integration fails, and the old field is removed on schedule after traffic logs show it is no longer read.