Skip to content

    System Design

    OpenAPI, Contract-First Design and API Contracts

    Write the API contract before the code: what an OpenAPI description holds, how to test an implementation against it, and how to spot a breaking change.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: API Design

    What you'll learn: By the end of this lesson you will be able to say what an OpenAPI description contains and what the specification requires of it, explain contract-first against code-first and when each fits, test a Spring implementation against its contract and catch drift, check a client's fixtures against the same file, tell an additive change from a breaking one, and read the captured output of a lab that does all of this with a deliberately small checker.

    Before a builder lays a brick, the architect draws the plans, and the electrician, plumber and joiner all read the same drawing. If the plumber works from a memory of an older drawing, the pipe meets a wall. An API contract is the drawing: one file that says which doors exist, what goes through them and what comes back, written before and checked after.

    API design covers the choices inside an API: resources, status codes, pagination, versioning and errors. This lesson is about writing those choices down in a form machines can read, and keeping the code honest against it. Choosing between REST, gRPC and GraphQL is in API styles, and the gRPC equivalent of a contract is in gRPC and Protocol Buffers.

    Verified with the OpenAPI Specification 3.2.1 (published 10 September 2026), the OpenAPI Generator documentation, Spring Boot 4.1.2 and Eclipse Temurin 25.0.3, on 2026-12-01.

    The core idea

    An API contract is a machine-readable description of an API's operations, inputs and outputs that both sides treat as the source of truth. Contract-first means the description is written and agreed before the code; either way it is only worth anything if something checks the code against it.

    Three illustrations run through the lesson: the minimal example is a small contract and a checker in a lab; the realistic example is ShopStream's mobile app and order service agreeing a change; the failure example is an implementation that has quietly drifted from its description.

    What an OpenAPI description contains

    OpenAPI is a specification for describing HTTP APIs. At the time of writing the latest version is 3.2.1, dated 10 September 2026; its revision history also lists 3.2.0, 3.1.2 and 3.0.4. A description may be written in JSON or YAML. The parts that matter for design:

    • Paths and operations. Each operation can carry an operationId, which must be unique among all operations in the description. The lab's checker uses it to refer to an operation.
    • Request body. Its required field defaults to false, so a body is optional unless you say otherwise.
    • Responses. The Responses object must contain at least one response code, a default can cover every code not listed, and documentation is expected to cover a successful response and any known errors. Status codes should come from the IANA registry. Each response maps media types to schemas.
    • Schemas and components. Reusable pieces live under components, which have no effect until something references them with a $ref, whose value is a URI. Schema parsing follows JSON Schema draft 2020-12.
    One contract, several readersDesign review to OpenAPI file (pull request); OpenAPI file to Provider tests (is the spec); OpenAPI file to Consumer code (is the spec); OpenAPI file to CI diff check (old vs new)OpenAPI file: in the repositoryOpenAPI filein the repositoryProvider tests: conform to itProvider testsconform to itConsumer code: client or mockConsumer codeclient or mockCI diff check: breaking changesCI diff checkbreaking changesDesign review: changes start hereDesign reviewchanges startherepull requestis the specis the specold vs new

    Figure 1. The contract at the centre. How to read this: a change starts as a change to the file, is reviewed there, and is read by the provider's tests, the consumer's code and a compatibility check.

    Contract-first and code-first

    Contract-first starts with the description; code-first starts with annotated controllers and generates the description from them. The Spring generator in OpenAPI Generator supports the first route: it generates a Spring Boot server from a description, with an interfaceOnly option (generate only API interface stubs, off by default) and a delegatePattern option (generate server files using the delegate pattern, off by default), and a useSpringBoot4 option for Spring Boot 4.x (off by default). The page's own description says the generator uses the SpringDoc integration. The lab in this lesson does not run a generator or any code-first tool.

    Contract-first Code-first
    Source of truth the description file the controllers
    Design review happens on the description, before code happens on a generated file, after code
    Consumers can start as soon as the contract is agreed when the code exists
    Risk the description is not implemented as written the description is a by-product nobody reads
    Fits public and partner APIs, several teams one team owning both sides, fast iteration

    Both fail the same way if nothing compares the two sides. The comparison is a test.

    Checking an implementation against its contract

    A contract test takes real exchanges and asks two questions of each: is this status documented for the operation, and does the body fit the schema for that status? The lab's checker does exactly that, with a small subset of schema rules (type, required properties, enum values, a numeric minimum, array items, local references).

    sequenceDiagram accTitle: A contract test of one operation accDescr: The test calls the controller through MockMvc and receives a status and a body. The checker looks up the operation by its id in the contract, checks the status is documented, finds the schema for that status and validates the body, returning a list of violations. participant T as Test participant C as Controller participant K as Contract checker T->>C: GET /products/apple-1kg C-->>T: 200 and a JSON body T->>K: check getProduct, 200, body K->>K: is 200 documented? find schema, validate body K-->>T: violations (empty means it conforms)

    Figure 2. One contract test. How to read this: the test never inspects the controller's code, only what crosses the wire, which is what a consumer sees.

    The same checker works on the other side. A consumer's test fixtures, the sample JSON its mocks return or its tests send, can be validated against the contract, so a consumer cannot test against a payload the provider would never produce.

    Drift

    Drift is the gap that opens between a description and the code. It comes from small, reasonable changes: a field is renamed in a refactor, an enum gains a value, an error handler returns a different shape, an id becomes a number. None fails a compile; each breaks a consumer.

    Evolving a contract

    Every change to the file is either safe for existing clients or it is not. The specification does not define breaking changes, so the rules are a team's own. The lab applies five, labelled as its own judgement: an operation was removed; a response property was removed or changed type; a request gained a required property or a property changed type; a request enum lost a value; a response enum gained a value or a response property is no longer guaranteed (the last two are warnings, because clients may not expect them).

    flowchart TD accTitle: Is a contract change safe accDescr: A decision tree. Removing an operation or a response property is breaking. Adding a required request property is breaking. Adding an optional property or a new operation is safe. Adding a response enum value is a warning. A["Change to the contract"] --> B{"Removes something a client uses?"} B -->|yes| X["Breaking: operation, response property, request enum value"] B -->|no| C{"Makes a request stricter?"} C -->|yes| Y["Breaking: new required request property, changed type"] C -->|no| D{"Widens what a client may receive?"} D -->|yes| W["Warning: new response enum value"] D -->|no| Z["Safe: optional field, new operation"]

    Figure 3. A sorting of contract changes. How to read this: ask what an existing client sends and expects to receive; anything that makes its old request fail or its old reading wrong is breaking.

    Safe changes still deserve a version bump in info.version so humans can see them; breaking ones need a migration path. Versioning strategies are in API design, and the data-side counterpart is schema evolution and zero-downtime migrations.

    What a contract cannot say

    A description says nothing about whether a quantity is actually in stock, how fast a response arrives, how many calls a client may make, or what a retry does. Those belong to other lessons: idempotency keys for retries, and the rate limiter lesson for limits. Documented error bodies are covered by the problem-details lesson, written separately.

    Build it: a contract-first check in Spring

    This is the minimal example. Goal: read a contract, test an implementation against it, catch drift, check client fixtures and compare two versions. What it is not: it generates no code, serves no documentation and runs no mock server. It is not an OpenAPI parser or a JSON Schema validator: Contract reads only paths, operations, request bodies, responses and local $ref schemas, the schema checker follows only type, required, properties, items, enum and minimum (the JSON Schema keywords of those names), and the five change rules are the lab's own. The contracts are JSON files, and the controllers run behind standalone MockMvc, with no network and no Docker. In a real project use an established validator and a diff tool.

    Setup. From the repository (Docker is not needed):

    cd examples/spring-labs
    ./gradlew :labs:openapi-contract-first:test

    It runs 13 tests, one of which compares the report below with the golden file examples/spring-labs/golden/openapi-contract-first.txt. The code is in examples/spring-labs/labs/openapi-contract-first/. The contract is shopstream-v1.json; this is the placeOrder operation's responses, with each body pointing at a reusable schema:

            "responses": {
              "201": {
                "description": "The order was created",
                "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Order" } } }
              },
              "400": {
                "description": "The request was not valid",
                "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
              }
            }

    The whole conformance check of a response is this:

            List<String> violations = new ArrayList<>();
            if (!contract.documentsStatus(op, status)) {
                violations.add("status " + status + " is not documented for " + operationId);
                return violations;
            }
            JsonNode schema = contract.responseSchema(op, status);
            if (schema == null) {
                return violations;
            }
            try {
                violations.addAll(schemas.check(schema, Contract.parse(body)));
            } catch (JacksonException e) {
                violations.add("body is not JSON");
            }
            return violations;

    Scenario 1: what the machine reads. The loader also refuses a description with a missing or duplicate operationId, which a test covers.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, 2026-12-01):

    == 1. What the machine reads from the contract
    contract: ShopStream catalogue and orders 1.0.0 (OpenAPI 3.2.1)
    getProduct  GET   /products/{id}  responses: 200, 404
    placeOrder  POST  /orders         responses: 201, 400

    Scenarios 2 and 3: an implementation written from the contract, and one that drifted. The drifted copy renamed priceCents to a decimal price, added a status value, changed its error shape and made the order id a number.

    Expected output, captured from a real run (the same run):

    == 2. The implementation written from the contract
    GET  /products/apple-1kg -> 200  conforms
    GET  /products/nope      -> 404  conforms
    POST /orders qty 2       -> 201  conforms
    POST /orders qty 0       -> 400  conforms
    
    == 3. An implementation that has drifted from the contract
    GET  /products/apple-1kg -> 200  DOES NOT CONFORM
        $: missing required property "priceCents"
        $.status: "AVAILABLE" is not one of [IN_STOCK, SOLD_OUT]
    GET  /products/nope      -> 404  DOES NOT CONFORM
        $: missing required property "status"
        $: missing required property "title"
    POST /orders qty 2       -> 201  DOES NOT CONFORM
        $.orderId: expected string, got integer
    POST /orders qty 0       -> 201  DOES NOT CONFORM
        $.orderId: expected string, got integer

    Scenario 4: a client's fixtures against the same contract.

    Expected output, captured from a real run (the same run):

    == 4. A client's test fixtures checked against the same contract
    {"sku":"apple-1kg","qty":2} -> valid
    {"sku":"apple-1kg"} -> $: missing required property "qty"
    {"sku":"apple-1kg","qty":"two"} -> $.qty: expected integer, got string
    {"sku":"apple-1kg","qty":0} -> $.qty: 0 is below the minimum 1

    Scenario 5: two next versions. v1.1.0 adds a new operation and optional fields; v2.0.0 renames a field, adds a required request property, changes a type and adds an enum value.

    Expected output, captured from a real run (the same run):

    == 5. What changed between versions of the contract
    v1.0.0 -> v1.1.0: no findings
    v1.0.0 -> v2.0.0: 4 findings
        BREAKING getProduct 200: property 'priceCents' was removed
        WARNING getProduct 200: value BACKORDER was added to 'status'
        BREAKING placeOrder request: new required property 'deliverySlot'
        BREAKING placeOrder 201: property 'qty' changed type from integer to string

    Break it. In ShopController, rename the record component priceCents of Product to price: everyDocumentedOperationIsImplementedByTheController fails and prints the violation. Restore the name and run the tests again.

    Left out: YAML, code generation, a mock server, oneOf and allOf, parameters, security schemes, content types other than JSON, and any real validator.

    Trade-offs

    Choice Gain Cost Wrong when
    Contract-first Review before code; parallel work Discipline to keep the file as the source One person owns both sides and changes daily
    Code-first Fast, no second file The description follows the code Other teams rely on it as a promise
    Contract tests in CI Drift found in the pull request Tests to write for error paths too You only test the happy path
    A strict diff check Breaking changes cannot slip in False alarms; rules need tuning Nobody owns the rules
    Generated server stubs The signature matches the contract Generated code to manage The generator's style fights your design

    In practice: the mobile app and the order service

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's mobile team and its order team are different teams. The mobile team wants a delivery slot on every order. The order team wants to rename a price field. Both changes ship in the same quarter, and the mobile team found out about the last change from a customer's screenshot of a blank price.

    Starting architecture

    ShopStream order contractMobile app to Order contract (reviews changes); Order service to Order contract (implements)Mobile app: client teamMobile appclient teamOrder contract: OpenAPI fileOrder contractOpenAPI fileOrder service: provider teamOrder serviceprovider teamreviews changesimplements

    Figure 4. Two teams, one file. How to read this: neither team edits the other's code; both edit and review the contract.

    Options considered

    Option Behaviour Risk
    A. Announce changes in chat Cheap Easy to miss; no check
    B. Version every change as v2 Clear Every consumer migrates for each small change
    C. Contract in the repository, reviewed by both teams, with a diff check in CI Breaking changes are visible before merge A review step and rules to maintain

    The decision

    Option C. The contract lives next to the order service, and a change to it needs a review from the mobile team. The CI job compares the new file with the last released one and fails on a breaking finding unless the pull request carries a deliberate approval. The delivery slot is added as an optional request property first, becomes required only after the app sends it, and the price field is added next to the old one, not instead of it, until the app has moved.

    Rollout and verification

    Run the diff in report-only mode for two weeks to learn how noisy it is. Then make it blocking. Add a contract test for each operation's success and error responses, and run the mobile team's fixtures through the checker. In production the checks are the 4xx rate per operation after a release and the app's crash-free rate.

    The 2 a.m. failure

    A refactor changes how the order service serialises money: priceCents becomes price in a decimal. The contract test covers the success path of getProduct but not its 404, and the diff check only runs when the contract file changes, which it did not, because the code changed and the file did not. The app shows blank prices. The checks are the contract test results and the error rate by app version. The mitigation is to roll back the refactor. The lasting fix is a contract test that runs on every build, success and error paths, so a code change that disagrees with an unchanged file fails.

    Architect's notes

    • Make the contract file reviewable and owned, with both sides in the review.
    • Test the provider against it on every build, including error responses.
    • Validate consumer fixtures against it too.
    • Write your own list of breaking changes; the specification does not define one.
    • Add before you remove: optional first, required later, old and new side by side.

    Common mistakes

    • Describing only the happy path. The specification expects known errors documented too.
    • Generating the file from code and never reading it. It becomes a by-product, not a contract.
    • Running the diff only when the file changes. Code can drift from an unchanged file.
    • A required request field added in place. Existing clients start failing.
    • Treating the contract as proof of behaviour. It says nothing about stock, speed or limits.

    Key takeaways

    • An OpenAPI description is JSON or YAML; operation ids must be unique and a request body is optional unless marked required.
    • Contract-first puts the file first; code-first generates it; both need a test that compares code and file.
    • A contract test checks that the status is documented and the body fits the schema, on success and error paths.
    • Drift is small, reasonable changes that compile and break consumers.
    • Breaking-change rules are the team's own; add before you remove.
    • The lab's checker is deliberately small: use a real validator in a real project.

    Practice exercises

    Exercise 1 (30 min). Take one ShopStream endpoint and write its operation, request schema and its 200 and 404 responses as an OpenAPI fragment.

    Exercise 2 (45 min). Run the lab. Add a field to Product in the contract and make the controller return it as the wrong type; read the violation.

    Exercise 3 (1 hour). Add the rule "a documented response status code was removed" to BreakingChanges, decide its severity and write a test.

    Exercise 4 (1 hour). List five behaviours of the order service that no OpenAPI description can express and say where each would be tested.

    The other side of this topic is the consumer's: it generates or hand-writes types from the contract, validates its fixtures against it, and treats an unexpected field or value as something to tolerate rather than crash on.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments