Skip to content

Codegen β€” Generate Models & Routes From Your Spec

TL;DR β€” point openapi-first codegen at your spec and get models + routes scaffolds 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:

  1. 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…).
  2. 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

openapi-first codegen models --module my_project.models --input openapi.yaml

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

1
2
3
4
5
# dry-run verification against your routes module
openapi-first codegen routes --module my_routes --input openapi.yaml --check

# scaffold an operation skeleton (generates the handler with a TODO)
openapi-first codegen routes --module my_routes --input openapi.yaml

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: codegen is 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.