Card 07/ 10

ComparisonDifficulty: Intermediate2 min

Contract-First vs Code-First

Write the contract and build to it, or build and generate the contract from the code.

Contract-first means writing the OpenAPI document before any code and building both server and clients against it. Code-first means writing the server and generating the document from its code, often from annotations or types. Both end with a contract; they differ in who owns it and when it exists, which decides how well they suit several teams working at once.

Contract-first and code-first compared
PropertyContract-firstCode-first
The contract existsBefore the codeAfter the code
Owned byEveryone who reviews the documentThe server team
Client teams can startAt once, against mocks generated from the contractOnce the server is built
Review of the designBefore anything is built, when changes are cheapAfter, when changes cost rework
Drift riskCode that does not match the contract, caught by validating against itGenerated contract that leaks internal details
Starting speedSlower; the document comes firstFaster for one team
SuitsSeveral teams, public APIs, partnersOne team that owns both sides, internal tools

Where contract-first wins. When two client teams start the same week as the server team, they all need the same agreement on day one. A mock server generated from the contract lets them build and test before the real one exists, and a review of the document catches design mistakes before anyone codes them.

Where code-first wins. A single team building an internal service and its only client can move faster by writing the code and generating documentation, because there is nobody to coordinate with.

Where each drifts. Contract-first fails if nobody checks the code against the document; validate requests and responses against it in tests. Code-first fails when the generated document mirrors internal models, exposing fields nobody chose to publish.

The rule for choosing. If more than one team, or anyone outside the company, depends on the API, write the contract first.