09.05.2026 | Why your API needs a formal contract

1. What is a contract?

A contract is a document defining API capabilities and expectations. It serves as a formal agreement between the client and the server. Frontend applications consume this contract, while the server-side implements it.

Shortcut: Contract -> Interface Agreement -> Decoupled Development.

2. Contents:

  • Definition of endpoints (Paths + Methods)
  • Request parameters (Query, Payload, Headers, Cookies)
  • Responses (Status codes, Schema/Types)
  • Examples & Mock data

3. No contract specified:

Communication without contract

fig 3.1 communication without contract

The client directly depends on the server (Tight Coupling). While manageable for single teams, it creates bottlenecks between separate Frontend and Backend teams.

Drawback: Changes require manual cross-team synchronization -> High risk of breaking changes.

4. Communication based on contract:

Communication with contract

fig 4.1 communication with contract

The contract acts as the Single Source of Truth (SSoT). Teams work independently against the artifact rather than each other.

Benefit: Parallel dev -> Earlier testing via Mocks.
Drawback: "Contract Drift" -> If code changes without updating the doc, the contract becomes a lie.

5. Types of contracts:

  • User-facing (Behavior)
  • Service-to-Service
  • Unit-to-Unit
  • Data / Protocol / Operational

6. Implementation via OpenAPI (OAS):

OpenAPI Specification (OAS) is the standard for describing contracts (YAML/JSON). It is language-agnostic.

  • Swagger Editor -> Authoring tool.
  • Swagger UI -> Documentation visualization.

Drawback: Manual YAML maintenance is tedious for complex APIs -> consider Code-First vs Design-First approaches.

7. Contract Versioning

Contracts are not static. A robust versioning strategy (e.g., SemVer or URL-based) ensures updates do not break active consumers.

Shortcut: Breaking Change -> Version Increment -> Controlled Migration.

Drawback: Maintenance Debt -> Supporting legacy versions increases the testing surface and infrastructure complexity.

8. Further study

Contracts relate to "Design by Contract" (DbC) principles. Modern ecosystems leverage contracts for:

  • Static Typing: OAS -> TypeScript types via openapi-typescript.
  • Runtime Validation: OAS -> Zod / ArkTypes / JSON-Schema.
  • Type-safe Clients: Zodios / TanStack Query integration.

Well-defined specs allow both humans and LLMs to understand service relations more accurately.

Cheers,
Marcin

Komentarze

Popularne posty z tego bloga

23.07.2024 - A comment on comments

15.07.2024 | simplicity

14.04 code-smells