Generate modern Python clients from OpenAPI 3.0 and 3.1 documents
npx @tessl/cli install tessl/pypi-openapi-python-client@0.26.00
# OpenAPI Python Client
1
2
A command-line tool and Python library for generating modern Python client libraries from OpenAPI 3.0 and 3.1 specifications. It focuses on creating type-safe, well-documented Python clients with modern Python features like type annotations, dataclasses, and comprehensive error handling.
3
4
## Package Information
5
6
- **Package Name**: openapi-python-client
7
- **Language**: Python
8
- **Installation**: `pip install openapi-python-client`
9
- **Recommended Installation**: `pipx install openapi-python-client --include-deps`
10
11
## Core Imports
12
13
```python
14
from openapi_python_client import generate, Project, __version__
15
from openapi_python_client.config import Config, ConfigFile, MetaType, ClassOverride
16
```
17
18
CLI usage:
19
```bash
20
openapi-python-client generate --url https://api.example.com/openapi.json
21
```
22
23
## Basic Usage
24
25
```python
26
from pathlib import Path
27
from openapi_python_client import generate
28
from openapi_python_client.config import Config, ConfigFile, MetaType
29
30
# Create configuration
31
config_file = ConfigFile()
32
config = Config.from_sources(
33
config_file=config_file,
34
meta_type=MetaType.POETRY,
35
document_source="https://api.example.com/openapi.json",
36
file_encoding="utf-8",
37
overwrite=True,
38
output_path=None
39
)
40
41
# Generate client library
42
errors = generate(config=config)
43
44
# Handle any errors
45
if errors:
46
for error in errors:
47
print(f"Error: {error.header}")
48
if error.detail:
49
print(f"Detail: {error.detail}")
50
```
51
52
CLI usage:
53
```bash
54
# Generate from URL
55
openapi-python-client generate --url https://api.example.com/openapi.json
56
57
# Generate from local file
58
openapi-python-client generate --path ./openapi.yaml
59
60
# Generate with custom configuration
61
openapi-python-client generate \
62
--url https://api.example.com/openapi.json \
63
--config config.yaml \
64
--meta poetry \
65
--overwrite \
66
--output-path ./my-client
67
```
68
69
## Architecture
70
71
The generator follows a pipeline architecture:
72
73
- **Document Parsing**: Fetches and validates OpenAPI documents from URLs or files
74
- **Schema Analysis**: Parses OpenAPI schemas into internal data structures using Pydantic models
75
- **Code Generation**: Uses Jinja2 templates to generate Python client code with proper type annotations
76
- **Post-processing**: Automatically formats generated code using Ruff for consistency
77
78
The generated clients follow a structured pattern:
79
- **Client Classes**: Both authenticated and non-authenticated HTTP clients
80
- **API Modules**: One module per OpenAPI tag containing endpoint functions
81
- **Model Classes**: Type-safe dataclasses for request/response schemas
82
- **Error Handling**: Comprehensive error types and validation
83
84
## Capabilities
85
86
### CLI Interface
87
88
Command-line interface for generating Python clients from OpenAPI specifications. Supports various options for customization, configuration files, and output formats.
89
90
```python { .api }
91
def generate(
92
url: Optional[str] = None,
93
path: Optional[Path] = None,
94
custom_template_path: Optional[Path] = None,
95
meta: MetaType = MetaType.POETRY,
96
file_encoding: str = "utf-8",
97
config_path: Optional[Path] = None,
98
fail_on_warning: bool = False,
99
overwrite: bool = False,
100
output_path: Optional[Path] = None,
101
) -> None: ...
102
```
103
104
[CLI Interface](./cli-interface.md)
105
106
### Programmatic API
107
108
Python API for integrating client generation into other tools and workflows. Provides full control over configuration and error handling.
109
110
```python { .api }
111
def generate(
112
*,
113
config: Config,
114
custom_template_path: Optional[Path] = None,
115
) -> Sequence[GeneratorError]: ...
116
117
class Config:
118
@staticmethod
119
def from_sources(
120
config_file: ConfigFile,
121
meta_type: MetaType,
122
document_source: Union[Path, str],
123
file_encoding: str,
124
overwrite: bool,
125
output_path: Optional[Path],
126
) -> "Config": ...
127
```
128
129
[Programmatic API](./programmatic-api.md)
130
131
### Configuration System
132
133
Comprehensive configuration system supporting file-based configuration, class overrides, project customization, and post-generation hooks.
134
135
```python { .api }
136
class ConfigFile(BaseModel):
137
class_overrides: Optional[dict[str, ClassOverride]] = None
138
content_type_overrides: Optional[dict[str, str]] = None
139
project_name_override: Optional[str] = None
140
package_name_override: Optional[str] = None
141
package_version_override: Optional[str] = None
142
use_path_prefixes_for_title_model_names: bool = True
143
post_hooks: Optional[list[str]] = None
144
docstrings_on_attributes: bool = False
145
field_prefix: str = "field_"
146
generate_all_tags: bool = False
147
http_timeout: int = 5
148
literal_enums: bool = False
149
150
@staticmethod
151
def load_from_path(path: Path) -> "ConfigFile": ...
152
```
153
154
[Configuration System](./configuration.md)
155
156
### Template System
157
158
Extensible Jinja2-based template system for customizing generated code structure, formatting, and content. Supports custom templates and filters.
159
160
```python { .api }
161
class Project:
162
def __init__(
163
self,
164
*,
165
openapi: GeneratorData,
166
config: Config,
167
custom_template_path: Optional[Path] = None,
168
) -> None: ...
169
170
def build(self) -> Sequence[GeneratorError]: ...
171
```
172
173
[Template System](./templates.md)
174
175
### Utility Functions
176
177
String manipulation and validation utilities used internally and available for custom templates and extensions.
178
179
```python { .api }
180
class PythonIdentifier(str):
181
def __new__(cls, value: str, prefix: str, skip_snake_case: bool = False) -> PythonIdentifier: ...
182
183
class ClassName(str):
184
def __new__(cls, value: str, prefix: str) -> ClassName: ...
185
186
def snake_case(value: str) -> str: ...
187
def pascal_case(value: str) -> str: ...
188
def kebab_case(value: str) -> str: ...
189
def sanitize(value: str) -> str: ...
190
def fix_reserved_words(value: str) -> str: ...
191
def get_content_type(content_type: str, config: Config) -> str | None: ...
192
```
193
194
## Types
195
196
```python
197
from openapi_python_client.config import MetaType, ClassOverride
198
from openapi_python_client.parser.errors import GeneratorError, ErrorLevel
199
from openapi_python_client.parser import GeneratorData
200
```
201
202
```python { .api }
203
class MetaType(str, Enum):
204
NONE = "none"
205
POETRY = "poetry"
206
SETUP = "setup"
207
PDM = "pdm"
208
UV = "uv"
209
210
class ClassOverride(BaseModel):
211
class_name: Optional[str] = None
212
module_name: Optional[str] = None
213
214
class GeneratorError:
215
header: str
216
detail: Optional[str]
217
level: ErrorLevel
218
219
class ErrorLevel(str, Enum):
220
WARNING = "warning"
221
ERROR = "error"
222
223
# Parser and Schema Types
224
class GeneratorData:
225
"""Parsed OpenAPI specification data"""
226
pass
227
228
def import_string_from_class(class_info) -> str:
229
"""Generate import string for a class"""
230
pass
231
232
# OpenAPI Schema Types
233
class DataType(str, Enum): ...
234
class ParameterLocation(str, Enum): ...
235
class MediaType: ...
236
class OpenAPI: ...
237
class Operation: ...
238
class Parameter: ...
239
class PathItem: ...
240
class Reference: ...
241
class RequestBody: ...
242
class Response: ...
243
class Responses: ...
244
class Schema: ...
245
```