0
# Programmatic API
1
2
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.
3
4
## Capabilities
5
6
### Main Generation Function
7
8
The primary function for generating OpenAPI Python clients programmatically.
9
10
```python { .api }
11
def generate(
12
*,
13
config: Config,
14
custom_template_path: Optional[Path] = None,
15
) -> Sequence[GeneratorError]:
16
"""
17
Generate the client library.
18
19
Parameters:
20
- config: Configuration object containing all generation settings
21
- custom_template_path: Optional path to custom Jinja2 templates
22
23
Returns:
24
List containing any errors encountered when generating
25
"""
26
```
27
28
### Project Class
29
30
Represents a Python project to generate, providing low-level control over the generation process.
31
32
```python { .api }
33
class Project:
34
def __init__(
35
self,
36
*,
37
openapi: GeneratorData,
38
config: Config,
39
custom_template_path: Optional[Path] = None,
40
) -> None:
41
"""
42
Initialize a new project for generation.
43
44
Parameters:
45
- openapi: Parsed OpenAPI data structure
46
- config: Generation configuration
47
- custom_template_path: Optional custom template directory
48
"""
49
50
def build(self) -> Sequence[GeneratorError]:
51
"""
52
Create the project from templates.
53
54
Returns:
55
List of errors encountered during generation
56
"""
57
58
# Properties
59
openapi: GeneratorData
60
config: Config
61
env: Environment # Jinja2 environment
62
project_name: str
63
package_name: str
64
project_dir: Path
65
package_dir: Path
66
package_description: str
67
version: str
68
errors: list[GeneratorError]
69
```
70
71
### Configuration Creation
72
73
Create configuration objects for programmatic use.
74
75
```python { .api }
76
class Config:
77
@staticmethod
78
def from_sources(
79
config_file: ConfigFile,
80
meta_type: MetaType,
81
document_source: Union[Path, str],
82
file_encoding: str,
83
overwrite: bool,
84
output_path: Optional[Path],
85
) -> "Config":
86
"""
87
Create a Config from various sources.
88
89
Parameters:
90
- config_file: ConfigFile object with file-based settings
91
- meta_type: Type of project metadata to generate
92
- document_source: URL or Path to OpenAPI document
93
- file_encoding: Text encoding for generated files
94
- overwrite: Whether to overwrite existing directories
95
- output_path: Custom output directory path
96
97
Returns:
98
Configured Config object
99
"""
100
```
101
102
## Usage Examples
103
104
### Basic Programmatic Generation
105
106
```python
107
from pathlib import Path
108
from openapi_python_client import generate
109
from openapi_python_client.config import Config, ConfigFile, MetaType
110
111
# Create basic configuration
112
config_file = ConfigFile()
113
config = Config.from_sources(
114
config_file=config_file,
115
meta_type=MetaType.POETRY,
116
document_source="https://api.example.com/openapi.json",
117
file_encoding="utf-8",
118
overwrite=True,
119
output_path=Path("./my-client")
120
)
121
122
# Generate client
123
errors = generate(config=config)
124
125
# Handle errors
126
if errors:
127
for error in errors:
128
print(f"Error: {error.header}")
129
if error.detail:
130
print(f"Detail: {error.detail}")
131
else:
132
print("Client generated successfully!")
133
```
134
135
### Advanced Configuration
136
137
```python
138
from pathlib import Path
139
from openapi_python_client import generate
140
from openapi_python_client.config import Config, ConfigFile, MetaType, ClassOverride
141
142
# Create advanced configuration
143
config_file = ConfigFile(
144
class_overrides={
145
"VeryLongModelName": ClassOverride(
146
class_name="ShortName",
147
module_name="short_name"
148
)
149
},
150
project_name_override="my-awesome-client",
151
package_name_override="my_awesome_client",
152
post_hooks=["ruff check --fix .", "ruff format ."],
153
field_prefix="attr_",
154
http_timeout=30,
155
literal_enums=True
156
)
157
158
config = Config.from_sources(
159
config_file=config_file,
160
meta_type=MetaType.PDM,
161
document_source=Path("./openapi.yaml"),
162
file_encoding="utf-8",
163
overwrite=True,
164
output_path=Path("./generated-client")
165
)
166
167
# Generate with custom templates
168
errors = generate(
169
config=config,
170
custom_template_path=Path("./custom-templates")
171
)
172
```
173
174
### Loading Configuration from File
175
176
```python
177
from pathlib import Path
178
from openapi_python_client import generate
179
from openapi_python_client.config import Config, ConfigFile, MetaType
180
181
# Load configuration from YAML/JSON file
182
config_file = ConfigFile.load_from_path(Path("./config.yaml"))
183
184
config = Config.from_sources(
185
config_file=config_file,
186
meta_type=MetaType.POETRY,
187
document_source="https://api.example.com/openapi.json",
188
file_encoding="utf-8",
189
overwrite=False,
190
output_path=None
191
)
192
193
errors = generate(config=config)
194
```
195
196
### Direct Project Creation
197
198
For advanced use cases, you can work directly with the Project class:
199
200
```python
201
from pathlib import Path
202
from openapi_python_client import Project
203
from openapi_python_client.config import Config
204
from openapi_python_client.parser import GeneratorData
205
from openapi_python_client.config import ConfigFile, MetaType
206
207
# Assume you have parsed OpenAPI data
208
# openapi_data = GeneratorData.from_dict(openapi_dict, config=config)
209
210
config_file = ConfigFile()
211
config = Config.from_sources(
212
config_file=config_file,
213
meta_type=MetaType.POETRY,
214
document_source="https://api.example.com/openapi.json",
215
file_encoding="utf-8",
216
overwrite=True,
217
output_path=None
218
)
219
220
# Create project directly
221
project = Project(
222
openapi=openapi_data,
223
config=config,
224
custom_template_path=Path("./custom-templates")
225
)
226
227
# Build the project
228
errors = project.build()
229
230
# Access project properties
231
print(f"Generated project: {project.project_name}")
232
print(f"Package name: {project.package_name}")
233
print(f"Output directory: {project.project_dir}")
234
```
235
236
### Error Handling
237
238
```python
239
from openapi_python_client import generate
240
from openapi_python_client.parser.errors import ErrorLevel
241
242
errors = generate(config=config)
243
244
# Categorize errors
245
warnings = [e for e in errors if e.level == ErrorLevel.WARNING]
246
errors_only = [e for e in errors if e.level == ErrorLevel.ERROR]
247
248
if errors_only:
249
print("Generation failed with errors:")
250
for error in errors_only:
251
print(f" ERROR: {error.header}")
252
if error.detail:
253
print(f" {error.detail}")
254
elif warnings:
255
print("Generation completed with warnings:")
256
for warning in warnings:
257
print(f" WARNING: {warning.header}")
258
if warning.detail:
259
print(f" {warning.detail}")
260
else:
261
print("Generation completed successfully!")
262
```