API contract

On this page 8

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.

ElementWhat it definesWhy consumers depend on it
OperationsPaths, methods, RPC names or event channelsClients must know what they can call
Request schemaRequired and optional fields, types, formatsInvalid input is rejected predictably
Response schemaFields, nullability, enumerationsParsers and generated models stay correct
Error modelStatus codes, error bodies, retry hintsClients can recover or report failures
SecurityAuthentication schemes, scopes, API key placementAccess is granted consistently
Behavioral rulesIdempotency, ordering, pagination, rate limitsRetries and paging do not corrupt data
Service levelsLatency, availability, deprecation notice periodConsumers can plan capacity and migrations
Core elements of an API contract

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.

FormatAPI styleTypical artifactStrength
OpenAPIREST API over HTTPYAML or JSON documentBroad tooling for docs, mocks and clients
AsyncAPIEvent-driven messagingChannel and message definitionsDescribes topics, brokers and payloads
Protocol BuffersgRPC.proto filesCompact binary encoding with field numbers
GraphQL SDLGraphQLSchema definition fileStrong typing and introspection
WSDLSOAPXML service descriptionStrict typing for legacy enterprise systems
JSON SchemaPayload validationSchema per messageReusable across many transports
Common contract formats by API style

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.

ChangeCompatibilityReason
Add an optional request fieldNon-breakingExisting requests remain valid
Add a response fieldUsually non-breakingTolerant readers ignore unknown fields
Make an optional field requiredBreakingOld requests now fail validation
Remove or rename a response fieldBreakingClients reading it receive nothing
Add an enumeration valueOften breakingStrict switch statements may fail
Change a field typeBreakingParsers and generated models fail
Tighten a rate limitBehaviorally breakingWorking clients start receiving errors
Typical changes and their compatibility impact

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.

ConceptRelationship to the contractMain audience
API documentationExplains the contract with guides and examplesDevelopers integrating the API
OpenAPI documentMachine-readable encoding of the contractTools and pipelines
SDKClient code generated or written against the contractApplication developers
Contract testingVerifies that both sides honor the contractProvider and consumer teams
Service level agreementCommercial commitment on availability and supportBusiness stakeholders
API contract compared with related concepts

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.