Codegen β Generate Models & Routes From Your Spec
TL;DR β point
openapi-first codegenat your spec and getmodels+routesscaffolds you can bind with one line. The codegen output is deterministic, and it's a starting point β not a maintained artifact.
π§ 1. Why Celebrate Codegen?
Two pain points kill OpenAPI projects:
- The "write the spec, then write the same thing as Pydantic models" step β exactly where server/client param types drift (your route says
item_id: int, your client sends a stringβ¦). - Writing the docs/spec catalog by hand, once you have more than a handful of operations.
Codegen collapses both. One command, one source file, same generated shapes everywhere.
π 2. Model Generation
The generated model module mirrors the spec's components.schemas by name:
| Spec | Generated |
|---|---|
components.schemas.User |
class User(BaseModel) |
components.schemas.Item |
class Item(BaseModel) |
every $ref (schema) |
a type: ClassVar alias β |
required + type from schema |
Pydantic Field(...) / type hints β |
Never hand-edit those files. If the spec changes, regenerate β just like you'd re-run cargo build after editing Cargo.toml.
Why constructor-time validation still applies
Codegen doesn't change the design: the generated models are plain Pydantic, and the client/server still validate against the spec at startup. Codegen is a convenience accelerator on top of the fail-fast guarantees in 04 β Design and 06 β Error Handling.
π 3. Route Generation / Verification
Why bother? Because bind_routes (in 02 β Components) needs an operationId β handler exactly matching the spec. Codegen guarantees you never type a handler name wrong β it wears the same operationId as the spec says.
Note:
codegenis build-time tooling. It does not run at runtime, and templates (the Bake-your-stuff section of 02 β Templates) make scaffolding a server out-of-the-box even simpler for greenfield projects.
π§ͺ 4. Idempotent Output
Generated output is deterministic w.r.t. the spec: - Same spec β byte-identical files (unless you hand-edit β you won't) - Ordering follows spec declaration order - No timestamps, no machine names, no hidden randomness
That determinism is what lets you git diff after a spec change and see exactly what moved.