Generate modern Python clients from OpenAPI 3.0 and 3.1 documents
—
Python API for integrating client generation into other tools and workflows. This provides programmatic access to all the functionality available through the CLI, with full control over configuration and error handling.
The primary function for generating OpenAPI Python clients programmatically.
def generate(
*,
config: Config,
custom_template_path: Optional[Path] = None,
) -> Sequence[GeneratorError]:
"""
Generate the client library.
Parameters:
- config: Configuration object containing all generation settings
- custom_template_path: Optional path to custom Jinja2 templates
Returns:
List containing any errors encountered when generating
"""Represents a Python project to generate, providing low-level control over the generation process.
class Project:
def __init__(
self,
*,
openapi: GeneratorData,
config: Config,
custom_template_path: Optional[Path] = None,
) -> None:
"""
Initialize a new project for generation.
Parameters:
- openapi: Parsed OpenAPI data structure
- config: Generation configuration
- custom_template_path: Optional custom template directory
"""
def build(self) -> Sequence[GeneratorError]:
"""
Create the project from templates.
Returns:
List of errors encountered during generation
"""
# Properties
openapi: GeneratorData
config: Config
env: Environment # Jinja2 environment
project_name: str
package_name: str
project_dir: Path
package_dir: Path
package_description: str
version: str
errors: list[GeneratorError]Create configuration objects for programmatic use.
class Config:
@staticmethod
def from_sources(
config_file: ConfigFile,
meta_type: MetaType,
document_source: Union[Path, str],
file_encoding: str,
overwrite: bool,
output_path: Optional[Path],
) -> "Config":
"""
Create a Config from various sources.
Parameters:
- config_file: ConfigFile object with file-based settings
- meta_type: Type of project metadata to generate
- document_source: URL or Path to OpenAPI document
- file_encoding: Text encoding for generated files
- overwrite: Whether to overwrite existing directories
- output_path: Custom output directory path
Returns:
Configured Config object
"""from pathlib import Path
from openapi_python_client import generate
from openapi_python_client.config import Config, ConfigFile, MetaType
# Create basic configuration
config_file = ConfigFile()
config = Config.from_sources(
config_file=config_file,
meta_type=MetaType.POETRY,
document_source="https://api.example.com/openapi.json",
file_encoding="utf-8",
overwrite=True,
output_path=Path("./my-client")
)
# Generate client
errors = generate(config=config)
# Handle errors
if errors:
for error in errors:
print(f"Error: {error.header}")
if error.detail:
print(f"Detail: {error.detail}")
else:
print("Client generated successfully!")from pathlib import Path
from openapi_python_client import generate
from openapi_python_client.config import Config, ConfigFile, MetaType, ClassOverride
# Create advanced configuration
config_file = ConfigFile(
class_overrides={
"VeryLongModelName": ClassOverride(
class_name="ShortName",
module_name="short_name"
)
},
project_name_override="my-awesome-client",
package_name_override="my_awesome_client",
post_hooks=["ruff check --fix .", "ruff format ."],
field_prefix="attr_",
http_timeout=30,
literal_enums=True
)
config = Config.from_sources(
config_file=config_file,
meta_type=MetaType.PDM,
document_source=Path("./openapi.yaml"),
file_encoding="utf-8",
overwrite=True,
output_path=Path("./generated-client")
)
# Generate with custom templates
errors = generate(
config=config,
custom_template_path=Path("./custom-templates")
)from pathlib import Path
from openapi_python_client import generate
from openapi_python_client.config import Config, ConfigFile, MetaType
# Load configuration from YAML/JSON file
config_file = ConfigFile.load_from_path(Path("./config.yaml"))
config = Config.from_sources(
config_file=config_file,
meta_type=MetaType.POETRY,
document_source="https://api.example.com/openapi.json",
file_encoding="utf-8",
overwrite=False,
output_path=None
)
errors = generate(config=config)For advanced use cases, you can work directly with the Project class:
from pathlib import Path
from openapi_python_client import Project
from openapi_python_client.config import Config
from openapi_python_client.parser import GeneratorData
from openapi_python_client.config import ConfigFile, MetaType
# Assume you have parsed OpenAPI data
# openapi_data = GeneratorData.from_dict(openapi_dict, config=config)
config_file = ConfigFile()
config = Config.from_sources(
config_file=config_file,
meta_type=MetaType.POETRY,
document_source="https://api.example.com/openapi.json",
file_encoding="utf-8",
overwrite=True,
output_path=None
)
# Create project directly
project = Project(
openapi=openapi_data,
config=config,
custom_template_path=Path("./custom-templates")
)
# Build the project
errors = project.build()
# Access project properties
print(f"Generated project: {project.project_name}")
print(f"Package name: {project.package_name}")
print(f"Output directory: {project.project_dir}")from openapi_python_client import generate
from openapi_python_client.parser.errors import ErrorLevel
errors = generate(config=config)
# Categorize errors
warnings = [e for e in errors if e.level == ErrorLevel.WARNING]
errors_only = [e for e in errors if e.level == ErrorLevel.ERROR]
if errors_only:
print("Generation failed with errors:")
for error in errors_only:
print(f" ERROR: {error.header}")
if error.detail:
print(f" {error.detail}")
elif warnings:
print("Generation completed with warnings:")
for warning in warnings:
print(f" WARNING: {warning.header}")
if warning.detail:
print(f" {warning.detail}")
else:
print("Generation completed successfully!")Install with Tessl CLI
npx tessl i tessl/pypi-openapi-python-client