0
# JSON Schema Generation
1
2
JSON schema generation capabilities for creating OpenAPI-compatible schemas from pydantic models and types, enabling automatic API documentation and validation.
3
4
## Capabilities
5
6
### Schema Generation Functions
7
8
Functions for generating JSON schemas from models and types.
9
10
```python { .api }
11
def model_json_schema(
12
cls, by_alias=True, ref_template='#/$defs/{model}', schema_generator=None
13
):
14
"""
15
Generate JSON schema for a model class.
16
17
Args:
18
by_alias (bool): Use field aliases in schema
19
ref_template (str): Template for schema references
20
schema_generator: Custom schema generator class
21
22
Returns:
23
dict: JSON schema dictionary
24
"""
25
26
def models_json_schema(models, *, by_alias=True, title='Generated schema',
27
description=None, ref_template='#/$defs/{model}'):
28
"""
29
Generate JSON schema for multiple model classes.
30
31
Args:
32
models: Sequence of model classes or tuples of (model, mode)
33
by_alias (bool): Use field aliases in schema
34
title (str): Schema title
35
description (str): Schema description
36
ref_template (str): Template for schema references
37
38
Returns:
39
dict: Combined JSON schema dictionary
40
"""
41
```
42
43
### Schema Generator Class
44
45
Core class for customizing JSON schema generation behavior.
46
47
```python { .api }
48
class GenerateJsonSchema:
49
"""
50
JSON schema generator with customizable behavior.
51
52
Can be subclassed to customize schema generation for specific needs.
53
"""
54
55
def __init__(self, by_alias=True, ref_template='#/$defs/{model}'):
56
"""
57
Initialize schema generator.
58
59
Args:
60
by_alias (bool): Use field aliases in schema
61
ref_template (str): Template for schema references
62
"""
63
64
def generate_schema(self, schema):
65
"""
66
Generate JSON schema from core schema.
67
68
Args:
69
schema: Core schema to convert
70
71
Returns:
72
dict: JSON schema dictionary
73
"""
74
75
def generate_field_schema(self, schema, validation_alias, serialization_alias):
76
"""
77
Generate JSON schema for a field.
78
79
Args:
80
schema: Field core schema
81
validation_alias: Field validation alias
82
serialization_alias: Field serialization alias
83
84
Returns:
85
dict: Field JSON schema
86
"""
87
88
def generate_definitions(self, definitions):
89
"""
90
Generate schema definitions.
91
92
Args:
93
definitions: Dictionary of definitions
94
95
Returns:
96
dict: Generated definitions
97
"""
98
```
99
100
### Schema Annotations
101
102
Classes for customizing JSON schema generation with annotations.
103
104
```python { .api }
105
class WithJsonSchema:
106
"""
107
Annotation for providing custom JSON schema for a type.
108
109
Used with Annotated to override default schema generation.
110
"""
111
112
def __init__(self, json_schema, *, mode='validation'):
113
"""
114
Initialize with custom JSON schema.
115
116
Args:
117
json_schema: Custom JSON schema (dict or callable)
118
mode (str): When to apply ('validation', 'serialization', 'both')
119
"""
120
121
def SkipJsonSchema(inner_type):
122
"""
123
Skip JSON schema generation for a type.
124
125
Args:
126
inner_type: Type to skip schema generation for
127
128
Returns:
129
Annotated type that skips JSON schema generation
130
"""
131
```
132
133
### Schema Utilities
134
135
Utility functions and classes for JSON schema operations.
136
137
```python { .api }
138
class JsonSchemaValue:
139
"""
140
Represents a JSON schema value with mode information.
141
"""
142
143
def __init__(self, value, *, mode='both'):
144
"""
145
Initialize JSON schema value.
146
147
Args:
148
value: Schema value
149
mode (str): Application mode ('validation', 'serialization', 'both')
150
"""
151
152
def field_json_schema(field_info, *, by_alias=True, validation_alias=None,
153
serialization_alias=None, schema_generator=None):
154
"""
155
Generate JSON schema for a field.
156
157
Args:
158
field_info: Field information object
159
by_alias (bool): Use field aliases
160
validation_alias: Validation alias override
161
serialization_alias: Serialization alias override
162
schema_generator: Custom schema generator
163
164
Returns:
165
dict: Field JSON schema
166
"""
167
168
class PydanticJsonSchemaWarning(UserWarning):
169
"""
170
Warning raised during JSON schema generation.
171
"""
172
```
173
174
### Type Adapters Schema Generation
175
176
JSON schema generation for TypeAdapters.
177
178
```python { .api }
179
class TypeAdapter:
180
def json_schema(self, *, by_alias=True, ref_template='#/$defs/{model}'):
181
"""
182
Generate JSON schema for the adapted type.
183
184
Args:
185
by_alias (bool): Use field aliases in schema
186
ref_template (str): Template for schema references
187
188
Returns:
189
dict: JSON schema for the type
190
"""
191
```
192
193
## Usage Examples
194
195
### Basic Model Schema Generation
196
197
```python
198
from pydantic import BaseModel, Field
199
from typing import Optional, List
200
201
class User(BaseModel):
202
id: int
203
name: str = Field(..., min_length=1, max_length=100)
204
email: str = Field(..., pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
205
age: Optional[int] = Field(None, ge=0, le=150)
206
tags: List[str] = Field(default_factory=list)
207
208
# Generate JSON schema
209
schema = User.model_json_schema()
210
print(schema)
211
212
# Output includes:
213
# {
214
# "type": "object",
215
# "properties": {
216
# "id": {"type": "integer"},
217
# "name": {"type": "string", "minLength": 1, "maxLength": 100},
218
# "email": {"type": "string", "pattern": "^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$"},
219
# "age": {"anyOf": [{"type": "integer", "minimum": 0, "maximum": 150}, {"type": "null"}]},
220
# "tags": {"type": "array", "items": {"type": "string"}, "default": []}
221
# },
222
# "required": ["id", "name", "email"]
223
# }
224
```
225
226
### Multiple Models Schema
227
228
```python
229
from pydantic import BaseModel
230
231
class User(BaseModel):
232
name: str
233
email: str
234
235
class Post(BaseModel):
236
title: str
237
content: str
238
author: User
239
240
# Generate combined schema
241
from pydantic import models_json_schema
242
243
schema = models_json_schema(
244
[User, Post],
245
title="Blog API Schema",
246
description="Schema for blog users and posts"
247
)
248
249
print(schema)
250
# Includes both User and Post definitions with proper references
251
```
252
253
### Custom Schema Generation
254
255
```python
256
from pydantic import BaseModel, GenerateJsonSchema
257
258
class CustomSchemaGenerator(GenerateJsonSchema):
259
def generate_field_schema(self, schema, validation_alias, serialization_alias):
260
field_schema = super().generate_field_schema(schema, validation_alias, serialization_alias)
261
262
# Add custom properties
263
if schema.get('type') == 'string':
264
field_schema['x-custom-string'] = True
265
266
return field_schema
267
268
class User(BaseModel):
269
name: str
270
email: str
271
272
# Use custom generator
273
schema = User.model_json_schema(schema_generator=CustomSchemaGenerator)
274
print(schema)
275
# String fields will have 'x-custom-string': True
276
```
277
278
### Schema Annotations
279
280
```python
281
from pydantic import BaseModel, Field
282
from pydantic.json_schema import WithJsonSchema
283
from typing import Annotated
284
285
def custom_password_schema(schema, model_type):
286
"""Custom schema for password fields."""
287
schema.update({
288
'type': 'string',
289
'format': 'password',
290
'writeOnly': True,
291
'minLength': 8
292
})
293
return schema
294
295
class User(BaseModel):
296
username: str
297
password: Annotated[str, WithJsonSchema(custom_password_schema)]
298
299
class Config:
300
json_schema_extra = {
301
'examples': [
302
{
303
'username': 'johndoe',
304
'password': 'secretpassword'
305
}
306
]
307
}
308
309
schema = User.model_json_schema()
310
print(schema['properties']['password'])
311
# {'type': 'string', 'format': 'password', 'writeOnly': True, 'minLength': 8}
312
```
313
314
### TypeAdapter Schema Generation
315
316
```python
317
from pydantic import TypeAdapter
318
from typing import Dict, List, Optional
319
320
# Complex nested type
321
UserData = Dict[str, List[Optional[int]]]
322
323
adapter = TypeAdapter(UserData)
324
schema = adapter.json_schema()
325
326
print(schema)
327
# {
328
# "type": "object",
329
# "additionalProperties": {
330
# "type": "array",
331
# "items": {"anyOf": [{"type": "integer"}, {"type": "null"}]}
332
# }
333
# }
334
```
335
336
### OpenAPI Integration
337
338
```python
339
from pydantic import BaseModel, Field
340
from typing import List, Optional
341
342
class UserCreate(BaseModel):
343
"""Schema for creating a new user."""
344
345
name: str = Field(..., description="User's full name", example="John Doe")
346
email: str = Field(..., description="User's email address", example="john@example.com")
347
age: Optional[int] = Field(None, description="User's age", ge=0, le=150, example=30)
348
349
class UserResponse(BaseModel):
350
"""Schema for user response."""
351
352
id: int = Field(..., description="Unique user identifier", example=123)
353
name: str = Field(..., description="User's full name", example="John Doe")
354
email: str = Field(..., description="User's email address", example="john@example.com")
355
created_at: str = Field(..., description="Creation timestamp", example="2023-12-25T10:30:00Z")
356
357
# Generate schemas for OpenAPI
358
create_schema = UserCreate.model_json_schema()
359
response_schema = UserResponse.model_json_schema()
360
361
# These can be used directly in OpenAPI/FastAPI documentation
362
openapi_schemas = {
363
'UserCreate': create_schema,
364
'UserResponse': response_schema
365
}
366
```
367
368
### Schema Customization with Field Info
369
370
```python
371
from pydantic import BaseModel, Field
372
import json
373
374
class Product(BaseModel):
375
name: str = Field(
376
...,
377
title="Product Name",
378
description="The name of the product",
379
examples=["Laptop", "Phone", "Tablet"]
380
)
381
price: float = Field(
382
...,
383
title="Price",
384
description="Product price in USD",
385
gt=0,
386
examples=[999.99, 1299.00]
387
)
388
category: str = Field(
389
...,
390
title="Category",
391
description="Product category",
392
examples=["Electronics", "Clothing", "Books"]
393
)
394
395
schema = Product.model_json_schema()
396
print(json.dumps(schema, indent=2))
397
398
# Schema includes titles, descriptions, and examples for rich documentation
399
```