Video in progress

For APIs between services, how do you choose between contract-first (generating code from OpenAPI/Protobuf) and code-first (generating the schema from Java classes)?

For APIs with many consumers, between teams and long-lived, contract-first: the contract is a separate artifact, easy to review and to check for compatibility automatically. For a fast-changing internal API inside one team, code-first is quicker. The main thing is that the generated classes must not turn into your domain model.

📖 Answer

In code-first, the contract comes out of a Java class "by accident": someone renamed a field in OrderResponse, springdoc produced a new schema, the API broke, but in the diff it looks like just a "rename". In other words, the contract change is hidden inside a code refactoring.

In contract-first:

# orders-api.yaml: a separate repo or module, reviewed separately
components:
  schemas:
    Order:
      type: object
      required: [id, status]
      properties:
        id: { type: string }
        status: { type: string, enum: [NEW, PAID, SHIPPED] }
  • a contract change is a separate PR, with the consumer teams as reviewers;
  • openapi-diff or buf breaking (Protobuf) catch breaking changes in CI;
  • consumers can generate a mock and a client before the server is ready.

Costs and traps:

  • generator code isn't pretty, and sometimes upgrading the generator version causes a breaking change by itself;
  • the biggest mistake is using a generated Order class inside the service as the domain model. Then every limitation of the contract enters the domain and vice versa. Generated types belong only in the adapter layer; inside, use your own domain model and a mapper;
  • enums are a special pain: adding a new value can be a breaking change for old consumers, so you should write a "accept unknown values" rule into the contract in advance.

My choice: external and cross-team APIs are contract-first; a BFF or admin API inside one team is code-first, but I keep a snapshot of the schema in the repo and diff it in CI. That way even in code-first a contract change is visible.