0
# Main Generation API
1
2
The core programmatic interface for generating Python data models from various schema formats. The `generate()` function provides extensive configuration options for customizing input processing, output model types, and code generation behavior.
3
4
## Capabilities
5
6
### Primary Generation Function
7
8
Generates Python data models from input schemas with comprehensive configuration options for all aspects of the generation process.
9
10
```python { .api }
11
def generate(
12
input_: Path | str | ParseResult | Mapping[str, Any],
13
*,
14
input_filename: str | None = None,
15
input_file_type: InputFileType = InputFileType.Auto,
16
output: Path | None = None,
17
output_model_type: DataModelType = DataModelType.PydanticBaseModel,
18
target_python_version: PythonVersion = PythonVersionMin,
19
base_class: str = "",
20
additional_imports: list[str] | None = None,
21
custom_template_dir: Path | None = None,
22
extra_template_data: defaultdict[str, dict[str, Any]] | None = None,
23
validation: bool = False,
24
field_constraints: bool = False,
25
snake_case_field: bool = False,
26
strip_default_none: bool = False,
27
aliases: Mapping[str, str] | None = None,
28
disable_timestamp: bool = False,
29
enable_version_header: bool = False,
30
allow_population_by_field_name: bool = False,
31
allow_extra_fields: bool = False,
32
extra_fields: str | None = None,
33
apply_default_values_for_required_fields: bool = False,
34
force_optional_for_required_fields: bool = False,
35
class_name: str | None = None,
36
use_standard_collections: bool = False,
37
use_schema_description: bool = False,
38
use_field_description: bool = False,
39
use_default_kwarg: bool = False,
40
reuse_model: bool = False,
41
encoding: str = "utf-8",
42
enum_field_as_literal: LiteralType | None = None,
43
use_one_literal_as_default: bool = False,
44
set_default_enum_member: bool = False,
45
use_subclass_enum: bool = False,
46
strict_nullable: bool = False,
47
use_generic_container_types: bool = False,
48
enable_faux_immutability: bool = False,
49
disable_appending_item_suffix: bool = False,
50
strict_types: Sequence[StrictTypes] | None = None,
51
empty_enum_field_name: str | None = None,
52
custom_class_name_generator: Callable[[str], str] | None = None,
53
field_extra_keys: set[str] | None = None,
54
field_include_all_keys: bool = False,
55
field_extra_keys_without_x_prefix: set[str] | None = None,
56
openapi_scopes: list[OpenAPIScope] | None = None,
57
include_path_parameters: bool = False,
58
graphql_scopes: list[GraphQLScope] | None = None,
59
wrap_string_literal: bool | None = None,
60
use_title_as_name: bool = False,
61
use_operation_id_as_name: bool = False,
62
use_unique_items_as_set: bool = False,
63
http_headers: Sequence[tuple[str, str]] | None = None,
64
http_ignore_tls: bool = False,
65
use_annotated: bool = False,
66
use_non_positive_negative_number_constrained_types: bool = False,
67
original_field_name_delimiter: str | None = None,
68
use_double_quotes: bool = False,
69
use_union_operator: bool = False,
70
collapse_root_models: bool = False,
71
special_field_name_prefix: str | None = None,
72
remove_special_field_name_prefix: bool = False,
73
capitalise_enum_members: bool = False,
74
keep_model_order: bool = False,
75
custom_file_header: str | None = None,
76
custom_file_header_path: Path | None = None,
77
custom_formatters: list[str] | None = None,
78
custom_formatters_kwargs: dict[str, Any] | None = None,
79
use_pendulum: bool = False,
80
http_query_parameters: Sequence[tuple[str, str]] | None = None,
81
treat_dot_as_module: bool = False,
82
use_exact_imports: bool = False,
83
union_mode: UnionMode | None = None,
84
output_datetime_class: DatetimeClassType | None = None,
85
keyword_only: bool = False,
86
frozen_dataclasses: bool = False,
87
no_alias: bool = False,
88
formatters: list[Formatter] = DEFAULT_FORMATTERS,
89
parent_scoped_naming: bool = False,
90
) -> None:
91
"""
92
Generate Python data models from input schema.
93
94
Args:
95
input_: Input source - can be:
96
- Path: Local file path to schema
97
- str: Raw schema content as string
98
- ParseResult: URL to remote schema
99
- Mapping: Dictionary containing schema data
100
input_filename: Name for input file (used in generated comments)
101
input_file_type: Format of input data (auto-detected if Auto)
102
output: Output file path (None writes to stdout)
103
output_model_type: Python model type to generate
104
target_python_version: Target Python version for generated code
105
base_class: Custom base class for generated models
106
additional_imports: Extra imports to include in generated code
107
custom_template_dir: Directory containing custom Jinja2 templates
108
extra_template_data: Additional data for custom templates
109
validation: Enable Pydantic validation features
110
field_constraints: Include field validation constraints
111
snake_case_field: Convert field names to snake_case
112
strip_default_none: Remove None default values from fields
113
aliases: Custom field name aliases mapping
114
disable_timestamp: Skip timestamp in generated file header
115
enable_version_header: Include package version in file header
116
allow_population_by_field_name: Allow population by original field names
117
allow_extra_fields: Allow extra fields in models
118
extra_fields: How to handle extra fields ('allow', 'forbid', 'ignore')
119
apply_default_values_for_required_fields: Set defaults for required fields
120
force_optional_for_required_fields: Make all fields optional
121
class_name: Root class name for single-class generation
122
use_standard_collections: Use built-in collections instead of typing
123
use_schema_description: Use schema descriptions in docstrings
124
use_field_description: Use field descriptions in field definitions
125
use_default_kwarg: Use default= kwarg in field definitions
126
reuse_model: Reuse models with same structure
127
encoding: File encoding for input/output
128
enum_field_as_literal: Convert enums to Literal types
129
use_one_literal_as_default: Use single literal as default value
130
set_default_enum_member: Set first enum member as default
131
use_subclass_enum: Generate enum subclasses
132
strict_nullable: Strict nullable field handling
133
use_generic_container_types: Use generic types for containers
134
enable_faux_immutability: Enable immutable-like behavior
135
disable_appending_item_suffix: Don't append 'Item' suffix to names
136
strict_types: Enable strict typing for specified types
137
empty_enum_field_name: Name for empty enum fields
138
custom_class_name_generator: Function to generate class names
139
field_extra_keys: Extra keys to preserve in field metadata
140
field_include_all_keys: Include all keys in field metadata
141
field_extra_keys_without_x_prefix: Extra keys without x- prefix
142
openapi_scopes: Scopes to parse from OpenAPI spec
143
include_path_parameters: Include path parameters in models
144
graphql_scopes: Scopes to parse from GraphQL schema
145
wrap_string_literal: Wrap string literals in quotes
146
use_title_as_name: Use title field as model name
147
use_operation_id_as_name: Use operationId as model name
148
use_unique_items_as_set: Convert uniqueItems arrays to sets
149
http_headers: Headers for HTTP requests to remote schemas
150
http_ignore_tls: Ignore TLS verification for HTTPS requests
151
use_annotated: Use typing.Annotated for field annotations
152
use_non_positive_negative_number_constrained_types: Use constrained numeric types
153
original_field_name_delimiter: Delimiter for original field names
154
use_double_quotes: Use double quotes in generated code
155
use_union_operator: Use | union operator syntax (Python 3.10+)
156
collapse_root_models: Merge root models into single class
157
special_field_name_prefix: Prefix for special field names
158
remove_special_field_name_prefix: Remove special prefixes from field names
159
capitalise_enum_members: Capitalize enum member names
160
keep_model_order: Preserve model definition order
161
custom_file_header: Custom header for generated files
162
custom_file_header_path: Path to file containing custom header
163
custom_formatters: List of custom formatter class names
164
custom_formatters_kwargs: Arguments for custom formatters
165
use_pendulum: Use pendulum for datetime types
166
http_query_parameters: Query parameters for HTTP requests
167
treat_dot_as_module: Treat dots in names as module separators
168
use_exact_imports: Use exact imports instead of wildcards
169
union_mode: Union mode for Pydantic v2 (left_to_right, smart)
170
output_datetime_class: Datetime class type for output
171
keyword_only: Generate keyword-only fields
172
frozen_dataclasses: Generate frozen dataclasses
173
no_alias: Don't generate field aliases
174
formatters: Code formatters to apply (Black, isort, Ruff)
175
parent_scoped_naming: Use parent scope in model names
176
177
Raises:
178
Error: Base exception for generation errors
179
InvalidClassNameError: When generated class names are invalid
180
FileNotFoundError: When input file is not found
181
"""
182
```
183
184
### Basic Usage Examples
185
186
#### Generate from local file
187
```python
188
from datamodel_code_generator import generate, DataModelType
189
from pathlib import Path
190
191
generate(
192
input_=Path("schema.json"),
193
output=Path("models.py"),
194
output_model_type=DataModelType.PydanticV2BaseModel
195
)
196
```
197
198
#### Generate from URL
199
```python
200
from urllib.parse import urlparse
201
from datamodel_code_generator import generate
202
203
generate(
204
input_=urlparse("https://example.com/api/schema.yaml"),
205
output=Path("api_models.py"),
206
http_headers=[("Authorization", "Bearer token")]
207
)
208
```
209
210
#### Generate from string content
211
```python
212
from datamodel_code_generator import generate, InputFileType
213
from pathlib import Path
214
215
schema_json = '''
216
{
217
"type": "object",
218
"properties": {
219
"name": {"type": "string"},
220
"age": {"type": "integer", "minimum": 0}
221
},
222
"required": ["name"]
223
}
224
'''
225
226
generate(
227
input_=schema_json,
228
input_file_type=InputFileType.JsonSchema,
229
output=Path("person.py"),
230
field_constraints=True
231
)
232
```
233
234
#### Generate dataclasses with custom options
235
```python
236
from datamodel_code_generator import generate, DataModelType
237
from pathlib import Path
238
239
generate(
240
input_=Path("openapi.yaml"),
241
output=Path("dataclasses_models.py"),
242
output_model_type=DataModelType.DataclassesDataclass,
243
frozen_dataclasses=True,
244
use_schema_description=True,
245
snake_case_field=True
246
)
247
```
248
249
#### Generate with custom formatting
250
```python
251
from datamodel_code_generator.format import Formatter
252
253
generate(
254
input_=Path("schema.yaml"),
255
output=Path("formatted_models.py"),
256
formatters=[Formatter.BLACK, Formatter.ISORT, Formatter.RUFF_FORMAT],
257
use_double_quotes=True,
258
target_python_version=PythonVersion.PY_311
259
)
260
```
261
262
## Common Configuration Patterns
263
264
### Pydantic v2 with Modern Python Features
265
```python
266
generate(
267
input_=schema_path,
268
output=output_path,
269
output_model_type=DataModelType.PydanticV2BaseModel,
270
target_python_version=PythonVersion.PY_311,
271
use_union_operator=True,
272
use_annotated=True,
273
union_mode="smart"
274
)
275
```
276
277
### TypedDict for Type Hints Only
278
```python
279
generate(
280
input_=schema_path,
281
output=output_path,
282
output_model_type=DataModelType.TypingTypedDict,
283
use_standard_collections=True,
284
enum_field_as_literal=LiteralType.All
285
)
286
```
287
288
### OpenAPI with Path Parameters
289
```python
290
generate(
291
input_=openapi_path,
292
output=output_path,
293
input_file_type=InputFileType.OpenAPI,
294
openapi_scopes=[OpenAPIScope.Schemas, OpenAPIScope.Paths],
295
include_path_parameters=True,
296
use_operation_id_as_name=True
297
)
298
```