Skip to content
javahacks.dev
Spring MVC

How to Do Contract First API Development With OpenAPI

Write the OpenAPI document first, then generate Java interfaces and models from it, implement them, and fail the build when code and contract drift apart.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring, Spring Boot, PostgreSQL and Apache Maven logos.

In code first development the annotations on controllers produce the specification. In contract first the specification comes first and the code follows from it. The practical difference is who can start: with a reviewed contract, a mobile team can build against a mock on day one, and a security reviewer can read what the API exposes without reading Java. This post uses OpenAPI 3.1, Spring Boot 4 and the OpenAPI Generator Maven plugin on JDK 25. The code-first route is in documenting an API with OpenAPI.

Write the contract

src/main/resources/openapi/orders.yamlYAML
openapi: 3.1.0
info:
  title: Orders API
  version: 1.0.0
paths:
  /orders/{id}:
    get:
      operationId: getOrder
      parameters:
        - { name: id, in: path, required: true, schema: { type: string } }
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '404':
          description: Not found
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/Problem' }
components:
  schemas:
    Order:
      type: object
      required: [id, status]
      properties:
        id: { type: string }
        status: { type: string, enum: [NEW, PAID, SHIPPED] }
    Problem:
      type: object
      properties:
        title: { type: string }
        status: { type: integer }

Give every operation an operationId. The generator turns it into the Java method name, and an omitted one produces a name derived from the path that nobody will like. Put the error responses in the contract as well, in the shape described in problem details. Contracts that only describe the happy path produce clients that cannot handle a 404 without guessing.

Generate the interfaces

XML
<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>7.12.0</version>
  <executions><execution>
    <goals><goal>generate</goal></goals>
    <configuration>
      <inputSpec>${project.basedir}/src/main/resources/openapi/orders.yaml</inputSpec>
      <generatorName>spring</generatorName>
      <configOptions>
        <interfaceOnly>true</interfaceOnly>
        <useSpringBoot3>true</useSpringBoot3>
        <useTags>true</useTags>
      </configOptions>
    </configuration>
  </execution></executions>
</plugin>

Pick the generator release that supports your Spring Boot line, and check its release notes when you upgrade Boot, because the Jakarta and Jackson changes land at different times. interfaceOnly generates the API interface and the models, without controller bodies, so there is no generated logic to maintain. The generated sources go to target/generated-sources and are added to the compile path by the plugin. Do not copy them into src/main.

Implement the interface

java
@RestController
class OrdersController implements OrdersApi {
    private final OrderService service;
    OrdersController(OrderService service) { this.service = service; }

    @Override
    public ResponseEntity<Order> getOrder(String id) {
        return service.find(id).map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}

If the contract changes, OrdersApi changes and this class stops compiling until you update it. That compile failure is the main benefit of the whole approach: drift between document and code becomes a build error and not a support ticket. Decide early whether the generated model classes are your domain model. We keep them at the edge and map to domain types in the controller, because a contract change should not ripple into persistence. The return types are covered in ResponseEntity usage.

Guard the contract

Two checks belong in the build. The first is linting the document with a ruleset, such as Spectral, for naming, required error responses and the presence of descriptions. It is where an argument about orderId versus order_id ends, because the ruleset decides and not the reviewer. The second is a test that calls the running server and validates the response against the schema. Without it the implementation can return a field the document never mentioned, and consumers who trust the document will not notice until the field disappears.

Share the contract with consumers

The same file generates a client for Java or TypeScript, as in generating clients. Consumers can also run a mock server from the document and build against it before the real server exists. That is the workflow that pays for the extra up-front effort, and it only works when the document is reviewed before implementation starts and not reverse-engineered from it.

Keeping the contract honest

The risk of a generated approach is a team that edits the generated output by hand, or an implementation that quietly diverges from the document. Both go away with one rule: the YAML is the only file people edit, and generated sources live under target and stay out of version control. Review a change to the YAML the way you review a change to a public method signature, because for your consumers it is exactly that.

Versioning follows. A new optional field is a compatible change. Removing a field, renaming it or tightening a type is breaking, and a tool such as openapi-diff can fail the pull request when a breaking change is not paired with a new path version. Run it against the contract on the main branch. Also decide whether unknown properties are allowed in requests: a strict server rejects typos, while a lenient one lets old clients keep working when you add a field, and the choice belongs in the document and not in a Jackson setting somebody toggled.

A review checklist for the contract

Before the first line of Java, we read the document once with four questions. Does every operation have a stable operationId, since it becomes a method name that consumers will call for years? Does every list endpoint say how it pages and how it sorts, because adding paging later breaks every client that assumed a bare array? Are identifiers strings, not integers, so a move from sequence numbers to UUIDs does not change a type? And does every error response name the shape clients should parse? Four minutes spent on these questions removes most of the arguments that would otherwise happen after a release, when changing a name costs a version bump.

Treat the example values as part of the contract too. The example fields feed mock servers and documentation, and a wrong example teaches consumers the wrong thing faster than any prose. When an example is wrong, the mock server returns it faithfully, and a front end team builds against that mistake for a week.

What goes wrong in practice

The first thing that goes wrong is the generator upgrade. A new generator release changes how nullable fields or enums are rendered, and a build that was green yesterday fails on a method signature today. Pin the plugin version, upgrade it on a branch and read the diff of the generated sources once, and you can see exactly what changed.

The second is the temptation to make the generated model your entity. A contract field that is required becomes a validation annotation on the generated class, and the moment you add a persistence annotation to the same class, a change to the API changes the table. Keep the two apart and write the mapping by hand, or with MapStruct if the model is large.

The third is a document that grows to five thousand lines in one file. Split it by resource with $ref to separate files under a shared components file, and have the build bundle them before generating. Reviewers will read a 200 line change to orders.yaml, and they will not read a 5,000 line file.

When this does not apply

For a small internal service with one consumer on the same team, generating code adds a build step for little gain. Annotating controllers and publishing the resulting spec is enough, and a code-first spec is easier to keep current when the same two people change both sides. Contract first earns its cost when two or more teams share the interface, or when a public API must stay stable across releases. The standard itself is the OpenAPI specification, and the generator documentation lists the Spring options.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.