Video in progress

Staff 🌱 Spring

For REST APIs between services, how do you choose between contract-first (generating code from OpenAPI) and code-first (generating OpenAPI from code)?

In contract-first the API is agreed first: teams work in parallel and backward compatibility is checked in CI, but you live with generated code and extra build steps. Code-first is fast and developer-friendly, but the contract is easily broken by accidental code changes.

📖 Answer

Code-first: you write the controller and DTOs, and springdoc-openapi produces the specification from them.

  • It starts fast, and the single source of truth is the code.
  • But the contract is a byproduct: if you refactor a field name in a DTO, the API changes silently. Who notices? Often the consumer, in production.

Contract-first: you first write openapi.yaml and review it, then openapi-generator generates the server interfaces and clients.

paths:
  /orders/{id}:
    get:
      operationId: getOrder
      responses:
        '200':
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
@RestController
class OrderController implements OrdersApi {   // the generated interface
    @Override
    public ResponseEntity<OrderDto> getOrder(Long id) { ... }
}
  • The frontend and other teams start working from the day the specification is agreed (the mock server also comes from the specification).
  • A contract change is a separate, visible diff; in review the question "is this a breaking change?" comes up naturally.
  • The cost: generator configuration, the awkward parts of generated code (names, how nullable is interpreted), build steps.

I usually choose like this:

  • The API is external or consumed by many teams → contract-first.
  • The service is internal, has one consumer (its own frontend) and changes fast → code-first is acceptable.

With both approaches, these are mandatory:

  • The specification is stored in the repo (with code-first, generated at build time and committed or published as an artifact).
  • A backward-compatibility check in CI: a diff against the previous version (for example oasdiff), and if there is a breaking change the build fails or someone has to explicitly approve it.
  • Contract tests from the consumer side (Spring Cloud Contract or Pact): the specification may be correct, but a consumer may be using it differently.

At the organization level, common rules (error format, ProblemDetail, pagination, date format, naming) are checked with a linter (Spectral). That matters even more than the approach for getting APIs that look consistent.