Card 07/ 10
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.
| Property | Contract-first | Code-first |
|---|---|---|
| The contract exists | Before the code | After the code |
| Owned by | Everyone who reviews the document | The server team |
| Client teams can start | At once, against mocks generated from the contract | Once the server is built |
| Review of the design | Before anything is built, when changes are cheap | After, when changes cost rework |
| Drift risk | Code that does not match the contract, caught by validating against it | Generated contract that leaks internal details |
| Starting speed | Slower; the document comes first | Faster for one team |
| Suits | Several teams, public APIs, partners | One 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.
← → move through sections and cards