Video in progress
What does generating code from an OpenAPI specification (API-first) give you, and what are the traps?
The contract is agreed in openapi.yaml before the code, and DTOs and interfaces are generated from it. This guarantees the client and the server use the same contract, but generator settings, the quality of the generated code and versioning of the specification need separate attention.
📖 Answer
In code-first, the contract is whatever springdoc generates from the controller annotations. It's convenient, but the contract changes by accident: someone refactors a field name in a DTO and the API breaks, and nobody notices.
In API-first the specification is written and reviewed first:
paths:
/customers/{id}:
get:
operationId: getCustomer
parameters:
- { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
responses:
"200":
content:
application/json:
schema: { $ref: "#/components/schemas/Customer" }
Then openapi-generator-maven-plugin generates, at build time, an interface for the server (interfaceOnly: true) and ready-made client classes for the client. The controller implements the interface; if the specification and the code diverge, compilation fails.
What's good: the frontend and other teams can start working against a mock server as soon as the specification is ready, and a breaking change shows up in the specification diff (you can put a tool like openapi-diff in CI).
Traps:
- the generated client may pick an old or inconvenient HTTP library: set the
libraryoption explicitly; - don't edit generated code by hand, the next build wipes it all;
- the generator interprets
nullableandrequiredin its own way, and unexpected types likeJsonNullableshow up; configure this early; - decide in advance where the specification lives and how it's versioned (a separate repo, an artifact, or the server's repo).
Sign up to mark studied questions and save your progress.