Skip to content

Codegen

openapi_first.codegen

Summary

Core logic for generating Python source code from OpenAPI specifications.

This module provides reusable utilities for code generation, specifically generating Pydantic models and route handler stubs from OpenAPI 3.x schema definitions.

Functions

generate_models

1
2
3
4
5
generate_models(
    spec_path: Path,
    output_path: Path,
    pydantic_version: int = 2,
) -> None

Generate Pydantic models from an OpenAPI specification.

Parameters:

Name Type Description Default
spec_path Path

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

required
output_path Path

Path where the generated Python code should be written.

required
pydantic_version int

The Pydantic version to target (1 or 2). Defaults to 2.

2
Notes

Reusability: This function is designed to be used by the CLI and can be exposed as an MCP tool without modification.

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.