Skip to content

Codegen Routes

openapi_first.codegen_routes

Summary

Route handler code generation from OpenAPI specifications.

This module generates Python route handler stubs from an OpenAPI 3.x specification. Each resource (derived from the first path segment) gets its own file under the output directory. Every OpenAPI operation must define an operationId, which becomes the handler function name.

Notes

Design constraints:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
- ``operationId`` is required on every operation (matching
  ``binder.bind_routes``).
- Handlers are stubs raising ``NotImplementedError``.
- Sub-resources (e.g. ``/pets/{id}/photo``) are grouped with their
  parent resource (``pets``).
- Parameter types and defaults are inferred from the spec.
- ``response: Response`` is injected for non-200 success codes.
- Resource names are sanitized to valid Python module identifiers,
  so a path such as ``/fetch-requests`` yields ``fetch_requests.py``.
- Passing ``inject_request=True`` prepends ``request: Request`` to
  every handler (the composition-root / DI convention).
- ``multipart/form-data`` and
  ``application/x-www-form-urlencoded`` request bodies expand to one
  parameter per schema property (``UploadFile`` / ``File`` / ``Form``)
  instead of an opaque ``payload: dict``.
- Passing ``package=True`` writes ``<resource>/routes.py`` (with
  ``__init__.py`` sidecars) instead of a flat ``<resource>.py``.

Functions

generate_routes

1
2
3
4
5
6
7
8
9
generate_routes(
    spec_path: Path,
    output_dir: Path,
    *,
    use_models: bool = False,
    models_module: str = "models",
    inject_request: bool = False,
    package: bool = False
) -> list[Path]

Generate route handler stubs from an OpenAPI specification.

Creates one route module per resource in output_dir. Resources are derived from the first path segment (e.g. /pets and /pets/{id} both group under pets) and sanitized to valid module identifiers.

Parameters:

Name Type Description Default
spec_path Path

Path to the OpenAPI specification file (YAML or JSON).

required
output_dir Path

Directory where the generated route files are written. Created automatically if it does not exist.

required
use_models bool

If True, import Pydantic models from models_module for request-body schemas referenced via $ref.

False
models_module str

Dotted Python module path from which to import models (e.g. "models", "app.models").

'models'
inject_request bool

If True, prepend request: Request to every handler so the stub can later resolve services from request.app.state.

False
package bool

If True, emit <resource>/routes.py packages (each with an __init__.py) instead of flat <resource>.py modules.

False

Returns:

Type Description
list[Path]

list[Path]: Absolute paths of every generated route file.

Raises:

Type Description
OpenAPISpecLoadError

If the spec cannot be loaded or validated.

ValueError

If any operation is missing operationId.