Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/json_schema.py: 17%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""!!! abstract "Usage Documentation"
2 [JSON Schema](../concepts/json_schema.md)
4The `json_schema` module contains classes and functions to allow the way [JSON Schema](https://json-schema.org/)
5is generated to be customized.
7In general you shouldn't need to use this module directly; instead, you can use
8[`BaseModel.model_json_schema`][pydantic.BaseModel.model_json_schema] and
9[`TypeAdapter.json_schema`][pydantic.TypeAdapter.json_schema].
10"""
12from __future__ import annotations as _annotations
14import collections.abc
15import dataclasses
16import inspect
17import math
18import os
19import re
20import warnings
21from collections import Counter, defaultdict
22from collections.abc import Callable, Hashable, Iterable, Sequence
23from copy import deepcopy
24from enum import Enum
25from re import Pattern
26from typing import (
27 TYPE_CHECKING,
28 Annotated,
29 Any,
30 Literal,
31 NewType,
32 TypeAlias,
33 TypeVar,
34 cast,
35 overload,
36)
38import pydantic_core
39from pydantic_core import MISSING, CoreSchema, PydanticOmit, core_schema, to_jsonable_python
40from pydantic_core.core_schema import ComputedField
41from typing_extensions import assert_never, deprecated, final
42from typing_inspection.introspection import get_literal_values
44from pydantic.warnings import PydanticDeprecatedSince26, PydanticDeprecatedSince29
46from ._internal import (
47 _config,
48 _core_metadata,
49 _core_utils,
50 _decorators,
51 _mock_val_ser,
52 _schema_generation_shared,
53 _typing_extra,
54)
55from .annotated_handlers import GetJsonSchemaHandler
56from .config import JsonDict, JsonValue
57from .errors import PydanticInvalidForJsonSchema, PydanticUserError
59if TYPE_CHECKING:
60 from . import ConfigDict
61 from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField
62 from ._internal._dataclasses import PydanticDataclass
63 from ._internal._schema_generation_shared import GetJsonSchemaFunction
64 from .main import BaseModel
67CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType]
68"""
69A type alias for defined schema types that represents a union of
70`core_schema.CoreSchemaType` and
71`core_schema.CoreSchemaFieldType`.
72"""
74JsonSchemaValue = dict[str, Any]
75"""
76A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.
77"""
79JsonSchemaMode = Literal['validation', 'serialization']
80"""
81A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'.
83For some types, the inputs to validation differ from the outputs of serialization. For example,
84computed fields will only be present when serializing, and should not be provided when
85validating. This flag provides a way to indicate whether you want the JSON schema required
86for validation inputs, or that will be matched by serialization outputs.
87"""
89_MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'}
92JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator']
93"""
94A type alias representing the kinds of warnings that can be emitted during JSON schema generation.
96See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
97for more details.
98"""
101class PydanticJsonSchemaWarning(UserWarning):
102 """This class is used to emit warnings produced during JSON schema generation.
103 See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
104 [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
105 methods for more details; these can be overridden to control warning behavior.
106 """
109NoDefault = object()
110"""A sentinel value used to indicate that no default value should be used when generating a JSON Schema
111for a core schema with a default value.
112"""
115# ##### JSON Schema Generation #####
116DEFAULT_REF_TEMPLATE = '#/$defs/{model}'
117"""The default format string used to generate reference names."""
119# There are three types of references relevant to building JSON schemas:
120# 1. core_schema "ref" values; these are not exposed as part of the JSON schema
121# * these might look like the fully qualified path of a model, its id, or something similar
122CoreRef = NewType('CoreRef', str)
123# 2. keys of the "definitions" object that will eventually go into the JSON schema
124# * by default, these look like "MyModel", though may change in the presence of collisions
125# * eventually, we may want to make it easier to modify the way these names are generated
126DefsRef = NewType('DefsRef', str)
127# 3. the values corresponding to the "$ref" key in the schema
128# * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"}
129JsonRef = NewType('JsonRef', str)
131CoreModeRef = tuple[CoreRef, JsonSchemaMode]
132JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable)
134_PRIMITIVE_JSON_SCHEMA_TYPES = ('string', 'boolean', 'null', 'integer', 'number')
137@dataclasses.dataclass(slots=True)
138class _DefinitionsRemapping:
139 defs_remapping: dict[DefsRef, DefsRef]
140 json_remapping: dict[JsonRef, JsonRef]
142 @staticmethod
143 def from_prioritized_choices(
144 prioritized_choices: dict[DefsRef, list[DefsRef]],
145 defs_to_json: dict[DefsRef, JsonRef],
146 definitions: dict[DefsRef, JsonSchemaValue],
147 ) -> _DefinitionsRemapping:
148 """
149 This function should produce a remapping that replaces complex DefsRef with the simpler ones from the
150 prioritized_choices such that applying the name remapping would result in an equivalent JSON schema.
151 """
152 # We need to iteratively simplify the definitions until we reach a fixed point.
153 # The reason for this is that outer definitions may reference inner definitions that get simplified
154 # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified
155 # the inner definitions.
156 copied_definitions = deepcopy(definitions)
157 definitions_schema = {'$defs': copied_definitions}
158 for _iter in range(100): # prevent an infinite loop in the case of a bug, 100 iterations should be enough
159 # For every possible remapped DefsRef, collect all schemas that DefsRef might be used for:
160 schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list)
161 for defs_ref in copied_definitions:
162 alternatives = prioritized_choices[defs_ref]
163 for alternative in alternatives:
164 schemas_for_alternatives[alternative].append(copied_definitions[defs_ref])
166 # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef
167 # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef.
168 for defs_ref in schemas_for_alternatives:
169 schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref])
171 # Build the remapping
172 defs_remapping: dict[DefsRef, DefsRef] = {}
173 json_remapping: dict[JsonRef, JsonRef] = {}
174 for original_defs_ref in definitions:
175 alternatives = prioritized_choices[original_defs_ref]
176 # Pick the first alternative that has only one schema, since that means there is no collision
177 remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1)
178 defs_remapping[original_defs_ref] = remapped_defs_ref
180 # Map all alternatives after the remapped one to the remapped one
181 # This ensures that intermediate simplifications are also remapped
182 remapped_index = alternatives.index(remapped_defs_ref)
183 for alt in alternatives[remapped_index:]:
184 json_remapping[defs_to_json[alt]] = defs_to_json[remapped_defs_ref]
185 remapping = _DefinitionsRemapping(defs_remapping, json_remapping)
186 new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions})
187 if definitions_schema == new_definitions_schema:
188 # We've reached the fixed point
189 return remapping
190 definitions_schema = new_definitions_schema
192 raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions')
194 def remap_defs_ref(self, ref: DefsRef) -> DefsRef:
195 return self.defs_remapping.get(ref, ref)
197 def remap_json_ref(self, ref: JsonRef) -> JsonRef:
198 return self.json_remapping.get(ref, ref)
200 def remap_json_schema(self, schema: Any) -> Any:
201 """
202 Recursively update the JSON schema replacing all $refs
203 """
204 if isinstance(schema, str):
205 # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings
206 return self.remap_json_ref(JsonRef(schema))
207 elif isinstance(schema, list):
208 return [self.remap_json_schema(item) for item in schema]
209 elif isinstance(schema, dict):
210 for key, value in schema.items():
211 if key == '$ref' and isinstance(value, str):
212 schema['$ref'] = self.remap_json_ref(JsonRef(value))
213 elif key == '$defs':
214 schema['$defs'] = {
215 self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
216 for key, value in schema['$defs'].items()
217 }
218 else:
219 schema[key] = self.remap_json_schema(value)
220 return schema
223class GenerateJsonSchema:
224 """!!! abstract "Usage Documentation"
225 [Customizing the JSON Schema Generation Process](../concepts/json_schema.md#customizing-the-json-schema-generation-process)
227 A class for generating JSON schemas.
229 This class generates JSON schemas based on configured parameters. The default schema dialect
230 is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema).
231 The class uses `by_alias` to configure how fields with
232 multiple names are handled and `ref_template` to format reference names.
234 Attributes:
235 schema_dialect: The JSON schema dialect used to generate the schema. See
236 [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4)
237 in the JSON Schema documentation for more information about dialects.
238 ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will
239 do nothing if its argument `kind` is in `ignored_warning_kinds`;
240 this value can be modified on subclasses to easily control which warnings are emitted.
241 by_alias: Whether to use field aliases when generating the schema.
242 ref_template: The format string used when generating reference names.
243 core_to_json_refs: A mapping of core refs to JSON refs.
244 core_to_defs_refs: A mapping of core refs to definition refs.
245 defs_to_core_refs: A mapping of definition refs to core refs.
246 json_to_defs_refs: A mapping of JSON refs to definition refs.
247 definitions: Definitions in the schema.
249 Args:
250 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
251 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
252 schemas). An explicit value takes precedence over the configuration.
253 ref_template: The format string to use when generating reference names.
254 union_format: The format to use when combining schemas from unions together. Can be one of:
256 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
257 keyword to combine schemas (the default).
258 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
259 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
260 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
261 `any_of`.
263 Raises:
264 JsonSchemaError: If the instance of the class is inadvertently reused after generating a schema.
265 """
267 schema_dialect = 'https://json-schema.org/draft/2020-12/schema'
269 # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`;
270 # this value can be modified on subclasses to easily control which warnings are emitted
271 ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'}
273 def __init__(
274 self,
275 by_alias: bool | None = None,
276 ref_template: str = DEFAULT_REF_TEMPLATE,
277 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
278 ) -> None:
279 # `None` means "not explicitly set": aliases are used, unless disabled by the config (e.g. `validate_by_alias`)
280 self._by_alias = by_alias
281 self.by_alias = by_alias is not False
282 self.ref_template = ref_template
283 self.union_format: Literal['any_of', 'primitive_type_array'] = union_format
285 self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {}
286 self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {}
287 self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {}
288 self.json_to_defs_refs: dict[JsonRef, DefsRef] = {}
290 self.definitions: dict[DefsRef, JsonSchemaValue] = {}
291 self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))
293 self._mode: JsonSchemaMode = 'validation'
295 # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
296 # alternatives, which are generally simpler, such as only including the class name.
297 # At the end of schema generation, we use these to produce a JSON schema with more human-readable
298 # definitions, which would also work better in a generated OpenAPI client, etc.
299 self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {}
300 self._collision_counter: dict[str, int] = defaultdict(int)
301 self._collision_index: dict[str, int] = {}
303 self._schema_type_to_method = self.build_schema_type_to_method()
305 # When we encounter definitions we need to try to build them immediately
306 # so that they are available schemas that reference them
307 # But it's possible that CoreSchema was never going to be used
308 # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
309 # the reference) so instead of failing altogether if we can't build a definition we
310 # store the error raised and re-throw it if we end up needing that def
311 self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {}
313 # This changes to True after generating a schema, to prevent issues caused by accidental reuse
314 # of a single instance of a schema generator
315 self._used = False
317 @property
318 def _config(self) -> _config.ConfigWrapper:
319 return self._config_wrapper_stack.tail
321 @property
322 def mode(self) -> JsonSchemaMode:
323 if self._config.json_schema_mode_override is not None:
324 return self._config.json_schema_mode_override
325 else:
326 return self._mode
328 def build_schema_type_to_method(
329 self,
330 ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
331 """Builds a dictionary mapping fields to methods for generating JSON schemas.
333 Returns:
334 A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method.
336 Raises:
337 TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type.
338 """
339 mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {}
340 core_schema_types: list[CoreSchemaOrFieldType] = list(get_literal_values(CoreSchemaOrFieldType))
341 for key in core_schema_types:
342 method_name = f'{key.replace("-", "_")}_schema'
343 try:
344 mapping[key] = getattr(self, method_name)
345 except AttributeError as e: # pragma: no cover
346 if os.getenv('PYDANTIC_PRIVATE_ALLOW_UNHANDLED_SCHEMA_TYPES'):
347 continue
348 raise TypeError(
349 f'No method for generating JsonSchema for core_schema.type={key!r} '
350 f'(expected: {type(self).__name__}.{method_name})'
351 ) from e
352 return mapping
354 def generate_definitions(
355 self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
356 ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
357 """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a
358 mapping that links the input keys to the definition references.
360 Args:
361 inputs: A sequence of tuples, where:
363 - The first element is a JSON schema key type.
364 - The second element is the JSON mode: either 'validation' or 'serialization'.
365 - The third element is a core schema.
367 Returns:
368 A tuple where:
370 - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
371 whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
372 JsonRef references to definitions that are defined in the second returned element.)
373 - The second element is a dictionary whose keys are definition references for the JSON schemas
374 from the first returned element, and whose values are the actual JSON schema definitions.
376 Raises:
377 PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema.
378 """
379 if self._used:
380 raise PydanticUserError(
381 'This JSON schema generator has already been used to generate a JSON schema. '
382 f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
383 code='json-schema-already-used',
384 )
386 for _, mode, schema in inputs:
387 self._mode = mode
388 self.generate_inner(schema)
390 definitions_remapping = self._build_definitions_remapping()
392 json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}
393 for key, mode, schema in inputs:
394 self._mode = mode
395 json_schema = self.generate_inner(schema)
396 json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema)
398 json_schema = {'$defs': self.definitions}
399 json_schema = definitions_remapping.remap_json_schema(json_schema)
400 self._used = True
401 return json_schemas_map, self.sort(json_schema['$defs']) # type: ignore
403 def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue:
404 """Generates a JSON schema for a specified schema in a specified mode.
406 Args:
407 schema: A Pydantic model.
408 mode: The mode in which to generate the schema. Defaults to 'validation'.
410 Returns:
411 A JSON schema representing the specified schema.
413 Raises:
414 PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema.
415 """
416 self._mode = mode
417 if self._used:
418 raise PydanticUserError(
419 'This JSON schema generator has already been used to generate a JSON schema. '
420 f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
421 code='json-schema-already-used',
422 )
424 json_schema: JsonSchemaValue = self.generate_inner(schema)
425 json_ref_counts = self.get_json_ref_counts(json_schema)
427 ref = cast(JsonRef, json_schema.get('$ref'))
428 while ref is not None: # may need to unpack multiple levels
429 ref_json_schema = self.get_schema_from_definitions(ref)
430 if json_ref_counts[ref] == 1 and ref_json_schema is not None and len(json_schema) == 1:
431 # "Unpack" the ref since this is the only reference and there are no sibling keys
432 json_schema = ref_json_schema.copy() # copy to prevent recursive dict reference
433 json_ref_counts[ref] -= 1
434 ref = cast(JsonRef, json_schema.get('$ref'))
435 ref = None
437 self._garbage_collect_definitions(json_schema)
438 definitions_remapping = self._build_definitions_remapping()
440 if self.definitions:
441 json_schema['$defs'] = self.definitions
443 json_schema = definitions_remapping.remap_json_schema(json_schema)
445 # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
446 # this method and adding the following line after a call to super().generate(schema):
447 # json_schema['$schema'] = self.schema_dialect
449 self._used = True
450 return self.sort(json_schema)
452 def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: # noqa: C901
453 """Generates a JSON schema for a given core schema.
455 Args:
456 schema: The given core schema.
458 Returns:
459 The generated JSON schema.
461 TODO: the nested function definitions here seem like bad practice, I'd like to unpack these
462 in a future PR. It'd be great if we could shorten the call stack a bit for JSON schema generation,
463 and I think there's potential for that here.
464 """
465 # If a schema with the same CoreRef has been handled, just return a reference to it
466 # Note that this assumes that it will _never_ be the case that the same CoreRef is used
467 # on types that should have different JSON schemas
468 if 'ref' in schema:
469 core_ref = CoreRef(schema['ref']) # type: ignore[typeddict-item]
470 core_mode_ref = (core_ref, self.mode)
471 if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions:
472 return {'$ref': self.core_to_json_refs[core_mode_ref]}
474 def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue:
475 if 'ref' in core_schema:
476 core_ref = CoreRef(core_schema['ref']) # type: ignore[typeddict-item]
477 defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
478 json_ref = JsonRef(ref_json_schema['$ref'])
479 # Replace the schema if it's not a reference to itself
480 # What we want to avoid is having the def be just a ref to itself
481 # which is what would happen if we blindly assigned any
482 if json_schema.get('$ref', None) != json_ref:
483 self.definitions[defs_ref] = json_schema
484 self._core_defs_invalid_for_json_schema.pop(defs_ref, None)
485 json_schema = ref_json_schema
486 return json_schema
488 def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue:
489 """Generate a JSON schema based on the input schema.
491 Args:
492 schema_or_field: The core schema to generate a JSON schema from.
494 Returns:
495 The generated JSON schema.
497 Raises:
498 TypeError: If an unexpected schema type is encountered.
499 """
500 # Generate the core-schema-type-specific bits of the schema generation:
501 json_schema: JsonSchemaValue | None = None
502 if self.mode == 'serialization' and 'serialization' in schema_or_field:
503 # In this case, we skip the JSON Schema generation of the schema
504 # and use the `'serialization'` schema instead (canonical example:
505 # `Annotated[int, PlainSerializer(str)]`).
506 ser_schema = schema_or_field['serialization'] # type: ignore
507 json_schema = self.ser_schema(ser_schema)
509 # It might be that the 'serialization'` is skipped depending on `when_used`.
510 # This is only relevant for `nullable` schemas though, so we special case here.
511 if (
512 json_schema is not None
513 and ser_schema.get('when_used') in ('unless-none', 'json-unless-none')
514 and schema_or_field['type'] == 'nullable'
515 ):
516 json_schema = self.get_union_of_schemas([{'type': 'null'}, json_schema])
517 if json_schema is None:
518 if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field):
519 generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']]
520 json_schema = generate_for_schema_type(schema_or_field)
521 else:
522 raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
523 return json_schema
525 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func)
527 metadata = cast(_core_metadata.CoreMetadata, schema.get('metadata', {}))
529 # TODO: I dislike that we have to wrap these basic dict updates in callables, is there any way around this?
531 if js_updates := metadata.get('pydantic_js_updates'):
533 def js_updates_handler_func(
534 schema_or_field: CoreSchemaOrField,
535 current_handler: GetJsonSchemaHandler = current_handler,
536 ) -> JsonSchemaValue:
537 json_schema = {**current_handler(schema_or_field), **js_updates}
538 return json_schema
540 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_updates_handler_func)
542 if js_extra := metadata.get('pydantic_js_extra'):
544 def js_extra_handler_func(
545 schema_or_field: CoreSchemaOrField,
546 current_handler: GetJsonSchemaHandler = current_handler,
547 ) -> JsonSchemaValue:
548 json_schema = current_handler(schema_or_field)
549 if isinstance(js_extra, dict):
550 json_schema.update(to_jsonable_python(js_extra))
551 elif callable(js_extra):
552 # similar to typing issue in _update_class_schema when we're working with callable js extra
553 js_extra(json_schema) # type: ignore
554 return json_schema
556 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_extra_handler_func)
558 for js_modify_function in metadata.get('pydantic_js_functions', ()):
560 def new_handler_func(
561 schema_or_field: CoreSchemaOrField,
562 current_handler: GetJsonSchemaHandler = current_handler,
563 js_modify_function: GetJsonSchemaFunction = js_modify_function,
564 ) -> JsonSchemaValue:
565 json_schema = js_modify_function(schema_or_field, current_handler)
566 if _core_utils.is_core_schema(schema_or_field):
567 json_schema = populate_defs(schema_or_field, json_schema)
568 original_schema = current_handler.resolve_ref_schema(json_schema)
569 ref = json_schema.pop('$ref', None)
570 if ref and json_schema:
571 original_schema.update(json_schema)
572 return original_schema
574 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
576 for js_modify_function in metadata.get('pydantic_js_annotation_functions', ()):
578 def new_handler_func(
579 schema_or_field: CoreSchemaOrField,
580 current_handler: GetJsonSchemaHandler = current_handler,
581 js_modify_function: GetJsonSchemaFunction = js_modify_function,
582 ) -> JsonSchemaValue:
583 return js_modify_function(schema_or_field, current_handler)
585 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
587 json_schema = current_handler(schema)
588 if _core_utils.is_core_schema(schema):
589 json_schema = populate_defs(schema, json_schema)
590 return json_schema
592 def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue:
593 """Override this method to customize the sorting of the JSON schema (e.g., don't sort at all, sort all keys unconditionally, etc.)
595 By default, alphabetically sort the keys in the JSON schema, skipping the 'properties' and 'default' keys to preserve field definition order.
596 This sort is recursive, so it will sort all nested dictionaries as well.
597 """
598 sorted_dict: dict[str, JsonSchemaValue] = {}
599 keys = value.keys()
600 if parent_key not in ('properties', 'default'):
601 keys = sorted(keys)
602 for key in keys:
603 sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
604 return sorted_dict
606 def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any:
607 """Recursively sort a JSON schema value."""
608 if isinstance(value, dict):
609 sorted_dict: dict[str, JsonSchemaValue] = {}
610 keys = value.keys()
611 if parent_key not in ('properties', 'default'):
612 keys = sorted(keys)
613 for key in keys:
614 sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
615 return sorted_dict
616 elif isinstance(value, list):
617 sorted_list: list[JsonSchemaValue] = [self._sort_recursive(item, parent_key) for item in value]
618 return sorted_list
619 else:
620 return value
622 # ### Schema generation methods
624 def invalid_schema(self, schema: core_schema.InvalidSchema) -> JsonSchemaValue:
625 """Placeholder - should never be called."""
627 raise RuntimeError('Cannot generate schema for invalid_schema. This is a bug! Please report it.')
629 def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue:
630 """Generates a JSON schema that matches any value.
632 Args:
633 schema: The core schema.
635 Returns:
636 The generated JSON schema.
637 """
638 return {}
640 def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue:
641 """Generates a JSON schema that matches `None`.
643 Args:
644 schema: The core schema.
646 Returns:
647 The generated JSON schema.
648 """
649 return {'type': 'null'}
651 def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue:
652 """Generates a JSON schema that matches a bool value.
654 Args:
655 schema: The core schema.
657 Returns:
658 The generated JSON schema.
659 """
660 return {'type': 'boolean'}
662 def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue:
663 """Generates a JSON schema that matches an int value.
665 Args:
666 schema: The core schema.
668 Returns:
669 The generated JSON schema.
670 """
671 json_schema: dict[str, Any] = {'type': 'integer'}
672 self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
673 json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
674 return json_schema
676 def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue:
677 """Generates a JSON schema that matches a float value.
679 Args:
680 schema: The core schema.
682 Returns:
683 The generated JSON schema.
684 """
685 json_schema: dict[str, Any] = {'type': 'number'}
686 self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
687 json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
688 return json_schema
690 def fraction_schema(self, schema: core_schema.FractionSchema) -> JsonSchemaValue:
691 """Generates a JSON schema that matches a fraction value.
693 Args:
694 schema: The core schema.
696 Returns:
697 The generated JSON schema.
699 """
700 json_schema: JsonSchemaValue = {'type': 'string', 'format': 'fraction'}
701 if self.mode == 'validation':
702 le = schema.get('le')
703 ge = schema.get('ge')
704 lt = schema.get('lt')
705 gt = schema.get('gt')
706 json_schema = {
707 'anyOf': [
708 self.float_schema(
709 core_schema.float_schema(
710 le=None if le is None else float(le),
711 ge=None if ge is None else float(ge),
712 lt=None if lt is None else float(lt),
713 gt=None if gt is None else float(gt),
714 )
715 ),
716 json_schema,
717 ],
718 }
719 return json_schema
721 def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
722 """Generates a JSON schema that matches a decimal value.
724 Args:
725 schema: The core schema.
727 Returns:
728 The generated JSON schema.
729 """
730 str_schema = core_schema.str_schema()
731 pattern = self.get_decimal_pattern(schema)
732 if pattern is not None:
733 str_schema['pattern'] = pattern
734 json_schema = self.str_schema(str_schema)
735 if self.mode == 'validation':
736 multiple_of = schema.get('multiple_of')
737 le = schema.get('le')
738 ge = schema.get('ge')
739 lt = schema.get('lt')
740 gt = schema.get('gt')
741 json_schema = {
742 'anyOf': [
743 self.float_schema(
744 core_schema.float_schema(
745 allow_inf_nan=schema.get('allow_inf_nan'),
746 multiple_of=None if multiple_of is None else float(multiple_of),
747 le=None if le is None else float(le),
748 ge=None if ge is None else float(ge),
749 lt=None if lt is None else float(lt),
750 gt=None if gt is None else float(gt),
751 )
752 ),
753 json_schema,
754 ],
755 }
756 return json_schema
758 def get_decimal_pattern(self, schema: core_schema.DecimalSchema) -> str | None:
759 """Get the regular expression pattern to apply to the string representation of a decimal.
761 By default, no pattern is applied (`None` is returned). Subclasses can override this method
762 to return a custom pattern, or [`build_decimal_pattern()`][pydantic.json_schema.GenerateJsonSchema.build_decimal_pattern]
763 can be used to get a pattern reflecting the `max_digits` and `decimal_places` constraints:
765 ```python
766 from pydantic.json_schema import GenerateJsonSchema
768 class MyGenerateJsonSchema(GenerateJsonSchema):
769 def get_decimal_pattern(self, schema):
770 return self.build_decimal_pattern(schema)
771 ```
773 Args:
774 schema: The core schema.
776 Returns:
777 The regular expression pattern, or `None` if no pattern should be applied.
778 """
779 return None
781 def build_decimal_pattern(self, schema: core_schema.DecimalSchema) -> str:
782 """Build a regular expression pattern for the string representation of a decimal.
784 The pattern takes into account the `max_digits` and `decimal_places` constraints, and the current
785 mode:
787 - In `'validation'` mode, the pattern accepts the string syntax understood by the [`Decimal`][decimal.Decimal]
788 constructor. The `max_digits` and `decimal_places` constraints are only reflected for strings
789 *without* an exponent: strings using an exponent are accepted as long as they are syntactically valid,
790 as the constraints can't be expressed with a regular expression in this case.
791 - In `'serialization'` mode, the pattern exactly describes the strings produced by pydantic
792 (i.e. by `str(decimal)`) for decimals satisfying the constraints,
793 including the ones using scientific notation (e.g. `'1E-7'`, `'1.5E+3'`).
795 In both modes, trailing zeros in the decimal part are not counted (e.g. `'1.10'` is accepted with
796 `decimal_places=1`), consistent with the validation behavior. If `allow_inf_nan` is enabled (on the
797 core schema or in the configuration), the string representations of infinity and NaN are also accepted.
799 Args:
800 schema: The core schema.
802 Returns:
803 The regular expression pattern.
804 """
805 max_digits = schema.get('max_digits')
806 decimal_places = schema.get('decimal_places')
807 allow_inf_nan = schema.get('allow_inf_nan')
808 if allow_inf_nan is None:
809 allow_inf_nan = self._config.config_dict.get('allow_inf_nan', False)
810 if self.mode == 'validation':
811 return _decimal_validation_pattern(max_digits, decimal_places, allow_inf_nan)
812 else:
813 return _decimal_serialization_pattern(max_digits, decimal_places, allow_inf_nan)
815 def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue:
816 """Generates a JSON schema that matches a string value.
818 Args:
819 schema: The core schema.
821 Returns:
822 The generated JSON schema.
823 """
824 json_schema: JsonSchemaValue = {'type': 'string'}
825 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
826 if 'minLength' not in json_schema and self._config.str_min_length:
827 json_schema['minLength'] = self._config.str_min_length
828 if 'maxLength' not in json_schema and self._config.str_max_length is not None:
829 json_schema['maxLength'] = self._config.str_max_length
830 if isinstance(json_schema.get('pattern'), Pattern):
831 # TODO: should we add regex flags to the pattern?
832 json_schema['pattern'] = json_schema.get('pattern').pattern # type: ignore
833 return json_schema
835 def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:
836 """Generates a JSON schema that matches a bytes value.
838 Args:
839 schema: The core schema.
841 Returns:
842 The generated JSON schema.
843 """
844 json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'}
845 self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
846 return json_schema
848 def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue:
849 """Generates a JSON schema that matches a date value.
851 Args:
852 schema: The core schema.
854 Returns:
855 The generated JSON schema.
856 """
857 return self._common_temporal_schema('date', self._config.ser_json_temporal)
859 def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:
860 """Generates a JSON schema that matches a time value.
862 Args:
863 schema: The core schema.
865 Returns:
866 The generated JSON schema.
867 """
868 return self._common_temporal_schema('time', self._config.ser_json_temporal)
870 def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:
871 """Generates a JSON schema that matches a datetime value.
873 Args:
874 schema: The core schema.
876 Returns:
877 The generated JSON schema.
878 """
879 return self._common_temporal_schema('date-time', self._config.ser_json_temporal)
881 def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:
882 """Generates a JSON schema that matches a timedelta value.
884 Args:
885 schema: The core schema.
887 Returns:
888 The generated JSON schema.
889 """
890 if 'ser_json_temporal' in self._config.config_dict:
891 temporal_format = self._config.ser_json_temporal
892 else:
893 # `ser_json_temporal` supersedes `ser_json_timedelta`, which only applies when the former isn't
894 # explicitly set.
895 temporal_format = 'seconds' if self._config.ser_json_timedelta == 'float' else 'iso8601'
896 return self._common_temporal_schema('duration', temporal_format)
898 def _common_temporal_schema(
899 self, format: str, temporal_format: Literal['iso8601', 'seconds', 'milliseconds']
900 ) -> JsonSchemaValue:
901 if self.mode == 'serialization' and temporal_format != 'iso8601':
902 # Both `'seconds'` and `'milliseconds'` serialize to a number:
903 return {'type': 'number'}
904 return {'type': 'string', 'format': format}
906 def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
907 """Generates a JSON schema that matches a literal value.
909 Args:
910 schema: The core schema.
912 Returns:
913 The generated JSON schema.
914 """
915 expected = [to_jsonable_python(v.value if isinstance(v, Enum) else v) for v in schema['expected']]
917 result: dict[str, Any] = {}
918 if len(expected) == 1:
919 result['const'] = expected[0]
920 else:
921 result['enum'] = expected
923 types = {type(e) for e in expected}
924 if types == {str}:
925 result['type'] = 'string'
926 elif types == {int}:
927 result['type'] = 'integer'
928 elif types == {float}:
929 result['type'] = 'number'
930 elif types == {bool}:
931 result['type'] = 'boolean'
932 elif types == {list}:
933 result['type'] = 'array'
934 elif types == {type(None)}:
935 result['type'] = 'null'
936 return result
938 def missing_sentinel_schema(self, schema: core_schema.MissingSentinelSchema) -> JsonSchemaValue:
939 """Generates a JSON schema that matches a schema that allows the `MISSING` sentinel value.
941 Args:
942 schema: The core schema.
944 Returns:
945 The generated JSON schema.
946 """
947 inner_schema = schema.get('schema')
948 if inner_schema is None:
949 raise PydanticOmit
950 return self.generate_inner(inner_schema)
952 def ellipsis_schema(self, schema: core_schema.EllipsisSchema) -> JsonSchemaValue:
953 """Handles JSON schema generation for a core schema that checks if a value is the [`Ellipsis`][] literal.
955 Unless overridden in a subclass, this raises an error.
957 Args:
958 schema: The core schema.
960 Returns:
961 The generated JSON schema.
962 """
963 return self.handle_invalid_for_json_schema(schema, 'core_schema.EllipsisSchema')
965 def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue:
966 """Generates a JSON schema that matches an Enum value.
968 Args:
969 schema: The core schema.
971 Returns:
972 The generated JSON schema.
973 """
974 enum_type = schema['cls']
975 description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
976 if (
977 description == 'An enumeration.'
978 ): # This is the default value provided by enum.EnumMeta.__new__; don't use it
979 description = None
980 result: dict[str, Any] = {'title': enum_type.__name__, 'description': description}
981 result = {k: v for k, v in result.items() if v is not None}
983 expected = [to_jsonable_python(v.value) for v in schema['members']]
985 result['enum'] = expected
987 types = {type(e) for e in expected}
988 if isinstance(enum_type, str) or types == {str}:
989 result['type'] = 'string'
990 elif isinstance(enum_type, int) or types == {int}:
991 result['type'] = 'integer'
992 elif isinstance(enum_type, float) or types == {float}:
993 result['type'] = 'number'
994 elif types == {bool}:
995 result['type'] = 'boolean'
996 elif types == {list}:
997 result['type'] = 'array'
999 return result
1001 def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue:
1002 """Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
1004 Unless overridden in a subclass, this raises an error.
1006 Args:
1007 schema: The core schema.
1009 Returns:
1010 The generated JSON schema.
1011 """
1012 return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})')
1014 def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue:
1015 """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
1017 For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
1019 Args:
1020 schema: The core schema.
1022 Returns:
1023 The generated JSON schema.
1024 """
1025 # Note: This is for compatibility with V1; you can override if you want different behavior.
1026 return {}
1028 def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue:
1029 """Generates a JSON schema that matches a callable value.
1031 Unless overridden in a subclass, this raises an error.
1033 Args:
1034 schema: The core schema.
1036 Returns:
1037 The generated JSON schema.
1038 """
1039 return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema')
1041 def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue:
1042 """Returns a schema that matches a list schema.
1044 Args:
1045 schema: The core schema.
1047 Returns:
1048 The generated JSON schema.
1049 """
1050 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
1051 json_schema = {'type': 'array', 'items': items_schema}
1052 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
1053 return json_schema
1055 def deque_schema(self, schema: core_schema.DequeSchema) -> JsonSchemaValue:
1056 """Returns a schema that matches a deque schema.
1058 Args:
1059 schema: The core schema.
1061 Returns:
1062 The generated JSON schema.
1063 """
1064 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
1065 json_schema = {'type': 'array', 'items': items_schema}
1066 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
1067 return json_schema
1069 @deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None)
1070 @final
1071 def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
1072 """Replaced by `tuple_schema`."""
1073 warnings.warn(
1074 '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.',
1075 PydanticDeprecatedSince26,
1076 stacklevel=2,
1077 )
1078 return self.tuple_schema(schema)
1080 @deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None)
1081 @final
1082 def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
1083 """Replaced by `tuple_schema`."""
1084 warnings.warn(
1085 '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.',
1086 PydanticDeprecatedSince26,
1087 stacklevel=2,
1088 )
1089 return self.tuple_schema(schema)
1091 def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
1092 """Generates a JSON schema that matches a tuple schema e.g. `tuple[int,
1093 str, bool]` or `tuple[int, ...]`.
1095 Args:
1096 schema: The core schema.
1098 Returns:
1099 The generated JSON schema.
1100 """
1101 json_schema: JsonSchemaValue = {'type': 'array'}
1102 if 'variadic_item_index' in schema:
1103 variadic_item_index = schema['variadic_item_index']
1104 if variadic_item_index > 0:
1105 json_schema['minItems'] = variadic_item_index
1106 json_schema['prefixItems'] = [
1107 self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
1108 ]
1109 if variadic_item_index + 1 == len(schema['items_schema']):
1110 # if the variadic item is the last item, then represent it faithfully
1111 json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index])
1112 else:
1113 # otherwise, 'items' represents the schema for the variadic
1114 # item plus the suffix, so just allow anything for simplicity
1115 # for now
1116 json_schema['items'] = True
1117 else:
1118 prefixItems = [self.generate_inner(item) for item in schema['items_schema']]
1119 if prefixItems:
1120 json_schema['prefixItems'] = prefixItems
1121 json_schema['minItems'] = len(prefixItems)
1122 json_schema['maxItems'] = len(prefixItems)
1123 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
1124 return json_schema
1126 def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue:
1127 """Generates a JSON schema that matches a set schema.
1129 Args:
1130 schema: The core schema.
1132 Returns:
1133 The generated JSON schema.
1134 """
1135 return self._common_set_schema(schema)
1137 def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue:
1138 """Generates a JSON schema that matches a frozenset schema.
1140 Args:
1141 schema: The core schema.
1143 Returns:
1144 The generated JSON schema.
1145 """
1146 return self._common_set_schema(schema)
1148 def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue:
1149 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
1150 json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema}
1151 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
1152 return json_schema
1154 def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue:
1155 """Returns a JSON schema that represents the provided GeneratorSchema.
1157 Args:
1158 schema: The schema.
1160 Returns:
1161 The generated JSON schema.
1162 """
1163 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
1164 json_schema = {'type': 'array', 'items': items_schema}
1165 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
1166 return json_schema
1168 def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue:
1169 """Generates a JSON schema that matches a dict schema.
1171 Args:
1172 schema: The core schema.
1174 Returns:
1175 The generated JSON schema.
1176 """
1177 return self._common_dict_schema(schema)
1179 def frozendict_schema(self, schema: core_schema.FrozenDictSchema) -> JsonSchemaValue:
1180 """Generates a JSON schema that matches a frozendict schema.
1182 Args:
1183 schema: The core schema.
1185 Returns:
1186 The generated JSON schema.
1187 """
1188 return self._common_dict_schema(schema)
1190 def ordered_dict_schema(self, schema: core_schema.OrderedDictSchema) -> JsonSchemaValue:
1191 """Generates a JSON schema that matches an `OrderedDict` schema.
1193 Args:
1194 schema: The core schema.
1196 Returns:
1197 The generated JSON schema.
1198 """
1199 return self._common_dict_schema(schema)
1201 def counter_schema(self, schema: core_schema.CounterSchema) -> JsonSchemaValue:
1202 """Generates a JSON schema that matches a `Counter` schema.
1204 Args:
1205 schema: The core schema.
1207 Returns:
1208 The generated JSON schema.
1209 """
1210 return self._common_dict_schema(schema)
1212 def _common_dict_schema(
1213 self,
1214 schema: core_schema.DictSchema
1215 | core_schema.FrozenDictSchema
1216 | core_schema.OrderedDictSchema
1217 | core_schema.CounterSchema,
1218 ) -> JsonSchemaValue:
1219 json_schema: JsonSchemaValue = {'type': 'object'}
1221 keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {}
1222 if '$ref' not in keys_schema:
1223 keys_pattern = keys_schema.pop('pattern', None)
1224 # Don't give a title to patternProperties/propertyNames:
1225 keys_schema.pop('title', None)
1226 else:
1227 # Here, we assume that if the keys schema is a definition reference,
1228 # it can't be a simple string core schema (and thus no pattern can exist).
1229 # However, this is only in practice (in theory, a definition reference core
1230 # schema could be generated for a simple string schema).
1231 # Note that we avoid calling `self.resolve_ref_schema`, as it might not exist yet.
1232 keys_pattern = None
1234 values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {}
1235 # don't give a title to additionalProperties:
1236 values_schema.pop('title', None)
1238 if values_schema or keys_pattern is not None:
1239 if keys_pattern is None:
1240 json_schema['additionalProperties'] = values_schema
1241 else:
1242 json_schema['patternProperties'] = {keys_pattern: values_schema}
1243 else: # for `dict[str, Any]`, we allow any key and any value, since `str` is the default key type
1244 json_schema['additionalProperties'] = True
1246 if (
1247 # The len check indicates that constraints are probably present:
1248 (keys_schema.get('type') == 'string' and len(keys_schema) > 1)
1249 # If this is a definition reference schema, it most likely has constraints:
1250 or '$ref' in keys_schema
1251 ):
1252 keys_schema.pop('type', None)
1253 json_schema['propertyNames'] = keys_schema
1255 self.update_with_validations(json_schema, schema, self.ValidationsMapping.object)
1256 return json_schema
1258 def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue:
1259 """Generates a JSON schema that matches a function-before schema.
1261 Args:
1262 schema: The core schema.
1264 Returns:
1265 The generated JSON schema.
1266 """
1267 if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
1268 return self.generate_inner(input_schema)
1270 return self.generate_inner(schema['schema'])
1272 def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue:
1273 """Generates a JSON schema that matches a function-after schema.
1275 Args:
1276 schema: The core schema.
1278 Returns:
1279 The generated JSON schema.
1280 """
1281 return self.generate_inner(schema['schema'])
1283 def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue:
1284 """Generates a JSON schema that matches a function-plain schema.
1286 Args:
1287 schema: The core schema.
1289 Returns:
1290 The generated JSON schema.
1291 """
1292 if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
1293 return self.generate_inner(input_schema)
1295 return self.handle_invalid_for_json_schema(
1296 schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})'
1297 )
1299 def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue:
1300 """Generates a JSON schema that matches a function-wrap schema.
1302 Args:
1303 schema: The core schema.
1305 Returns:
1306 The generated JSON schema.
1307 """
1308 if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
1309 return self.generate_inner(input_schema)
1311 return self.generate_inner(schema['schema'])
1313 def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
1314 """Generates a JSON schema that matches a schema with a default value.
1316 Args:
1317 schema: The core schema.
1319 Returns:
1320 The generated JSON schema.
1321 """
1322 json_schema = self.generate_inner(schema['schema'])
1324 default = self.get_default_value(schema)
1325 if default is NoDefault or default is MISSING:
1326 return json_schema
1328 # we reflect the application of custom plain, no-info serializers to defaults for
1329 # JSON Schemas viewed in serialization mode:
1330 # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
1331 if self.mode == 'serialization':
1332 # `_get_ser_schema_for_default_value()` is used to unpack potentially nested validator schemas:
1333 ser_schema = _get_ser_schema_for_default_value(schema['schema'])
1334 if (
1335 ser_schema is not None
1336 and (ser_func := ser_schema.get('function'))
1337 and not (default is None and ser_schema.get('when_used') in ('unless-none', 'json-unless-none'))
1338 ):
1339 try:
1340 default = ser_func(default) # type: ignore
1341 except Exception:
1342 # It might be that the provided default needs to be validated (read: parsed) first
1343 # (assuming `validate_default` is enabled). However, we can't perform
1344 # such validation during JSON Schema generation so we don't support
1345 # this pattern for now.
1346 # (One example is when using `foo: ByteSize = '1MB'`, which validates and
1347 # serializes as an int. In this case, `ser_func` is `int` and `int('1MB')` fails).
1348 self.emit_warning(
1349 'non-serializable-default',
1350 f'Unable to serialize value {default!r} with the plain serializer; excluding default from JSON schema',
1351 )
1352 return json_schema
1354 # Sort set/frozenset defaults to ensure deterministic JSON schema generation
1355 # We only sort if len > 1 because sets of size 0 or 1 are already deterministic
1356 if isinstance(default, collections.abc.Set) and len(default) > 1:
1357 try:
1358 default = sorted(default)
1359 except TypeError: # pragma: no cover
1360 # If items aren't comparable (e.g. mixed types), we can't sort them.
1361 pass
1363 try:
1364 encoded_default = self.encode_default(default)
1365 except pydantic_core.PydanticSerializationError:
1366 self.emit_warning(
1367 'non-serializable-default',
1368 f'Default value {default} is not JSON serializable; excluding default from JSON schema',
1369 )
1370 # Return the inner schema, as though there was no default
1371 return json_schema
1373 json_schema['default'] = encoded_default
1374 return json_schema
1376 def get_default_value(self, schema: core_schema.WithDefaultSchema) -> Any:
1377 """Get the default value to be used when generating a JSON Schema for a core schema with a default.
1379 The default implementation is to use the statically defined default value. This method can be overridden
1380 if you want to make use of the default factory.
1382 Args:
1383 schema: The `'with-default'` core schema.
1385 Returns:
1386 The default value to use, or [`NoDefault`][pydantic.json_schema.NoDefault] if no default
1387 value is available.
1388 """
1389 return schema.get('default', NoDefault)
1391 def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue:
1392 """Generates a JSON schema that matches a schema that allows null values.
1394 Args:
1395 schema: The core schema.
1397 Returns:
1398 The generated JSON schema.
1399 """
1400 null_schema = {'type': 'null'}
1401 inner_json_schema = self.generate_inner(schema['schema'])
1403 if inner_json_schema == null_schema:
1404 return null_schema
1405 else:
1406 return self.get_union_of_schemas([inner_json_schema, null_schema])
1408 def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue:
1409 """Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
1411 Args:
1412 schema: The core schema.
1414 Returns:
1415 The generated JSON schema.
1416 """
1417 generated: list[JsonSchemaValue] = []
1419 for choice in core_schema.iter_union_choices(schema):
1420 try:
1421 generated.append(self.generate_inner(choice))
1422 except PydanticOmit: # noqa: PERF203
1423 continue
1424 except PydanticInvalidForJsonSchema as exc:
1425 self.emit_warning('skipped-choice', exc.message)
1426 if len(generated) == 1:
1427 return generated[0]
1428 return self.get_union_of_schemas(generated)
1430 def get_union_of_schemas(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
1431 """Returns the JSON Schema representation for the union of the provided JSON Schemas.
1433 The result depends on the configured `'union_format'`.
1435 Args:
1436 schemas: The list of JSON Schemas to be included in the union.
1438 Returns:
1439 The JSON Schema representing the union of schemas.
1440 """
1441 if self.union_format == 'primitive_type_array':
1442 types: list[str] = []
1443 for schema in schemas:
1444 schema_types: list[str] | str | None = schema.get('type')
1445 if schema_types is None:
1446 # No type, meaning it can be a ref or an empty schema.
1447 break
1448 if not isinstance(schema_types, list):
1449 schema_types = [schema_types]
1450 if not all(t in _PRIMITIVE_JSON_SCHEMA_TYPES for t in schema_types):
1451 break
1452 if len(schema) != 1:
1453 # We only want to include types that don't have any constraints. For instance,
1454 # if `schemas = [{'type': 'string', 'maxLength': 3}, {'type': 'string', 'minLength': 5}]`,
1455 # we don't want to produce `{'type': 'string', 'maxLength': 3, 'minLength': 5}`.
1456 # Same if we have some metadata (e.g. `title`) on a specific union member, we want to preserve it.
1457 break
1459 types.extend(schema_types)
1460 else:
1461 # If we got there, all the schemas where valid to be used with the `'primitive_type_array` format
1462 return {'type': list(dict.fromkeys(types))}
1464 return self.get_flattened_anyof(schemas)
1466 def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue:
1467 """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where
1468 the schemas are tagged with a discriminator field that indicates which schema should be used to validate
1469 the value.
1471 Args:
1472 schema: The core schema.
1474 Returns:
1475 The generated JSON schema.
1476 """
1477 generated: dict[str, JsonSchemaValue] = {}
1478 for k, v in schema['choices'].items():
1479 if isinstance(k, Enum):
1480 k = k.value
1481 elif isinstance(k, bool):
1482 # Use the JSON representation so that the discriminator mapping
1483 # can be matched against the serialized payload value
1484 k = 'true' if k else 'false'
1485 elif k is None:
1486 k = 'null'
1487 try:
1488 # Use str(k) since keys must be strings for json; while not technically correct,
1489 # it's the closest that can be represented in valid JSON
1490 generated[str(k)] = self.generate_inner(v).copy()
1491 except PydanticOmit:
1492 continue
1493 except PydanticInvalidForJsonSchema as exc:
1494 self.emit_warning('skipped-choice', exc.message)
1496 one_of_choices = _deduplicate_schemas(generated.values())
1497 json_schema: JsonSchemaValue = {'oneOf': one_of_choices}
1499 # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
1500 openapi_discriminator = self._extract_discriminator(schema, one_of_choices)
1501 if openapi_discriminator is not None:
1502 json_schema['discriminator'] = {
1503 'propertyName': openapi_discriminator,
1504 'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
1505 }
1507 return json_schema
1509 def _extract_discriminator(
1510 self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict]
1511 ) -> str | None:
1512 """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final
1513 schema."""
1514 openapi_discriminator: str | None = None
1516 if isinstance(schema['discriminator'], str):
1517 return schema['discriminator']
1519 if isinstance(schema['discriminator'], list):
1520 # If the discriminator is a single item list containing a string, that is equivalent to the string case
1521 if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str):
1522 return schema['discriminator'][0]
1523 # When an alias is used that is different from the field name, the discriminator will be a list of single
1524 # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is
1525 # more than one possible attribute, and looks for whether a single alias choice is present as a documented
1526 # property on all choices. If so, that property will be used as the OpenAPI discriminator.
1527 for alias_path in schema['discriminator']:
1528 if not isinstance(alias_path, list):
1529 break # this means that the discriminator is not a list of alias paths
1530 if len(alias_path) != 1:
1531 continue # this means that the "alias" does not represent a single field
1532 alias = alias_path[0]
1533 if not isinstance(alias, str):
1534 continue # this means that the "alias" does not represent a field
1535 alias_is_present_on_all_choices = True
1536 for choice in one_of_choices:
1537 try:
1538 choice = self.resolve_ref_schema(choice)
1539 except RuntimeError as exc:
1540 # TODO: fixme - this is a workaround for the fact that we can't always resolve refs
1541 # for tagged union choices at this point in the schema gen process, we might need to do
1542 # another pass at the end like we do for core schemas
1543 self.emit_warning('skipped-discriminator', str(exc))
1544 choice = {}
1545 properties = choice.get('properties', {})
1546 if not isinstance(properties, dict) or alias not in properties:
1547 alias_is_present_on_all_choices = False
1548 break
1549 if alias_is_present_on_all_choices:
1550 openapi_discriminator = alias
1551 break
1552 return openapi_discriminator
1554 def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue:
1555 """Generates a JSON schema that matches a core_schema.ChainSchema.
1557 When generating a schema for validation, we return the validation JSON schema for the first step in the chain.
1558 For serialization, we return the serialization JSON schema for the last step in the chain.
1560 Args:
1561 schema: The core schema.
1563 Returns:
1564 The generated JSON schema.
1565 """
1566 step_index = 0 if self.mode == 'validation' else -1 # use first step for validation, last for serialization
1567 return self.generate_inner(schema['steps'][step_index])
1569 def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue:
1570 """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the
1571 strict schema.
1573 Args:
1574 schema: The core schema.
1576 Returns:
1577 The generated JSON schema.
1578 """
1579 # TODO: Need to read the default value off of model config or whatever
1580 use_strict = schema.get('strict', False) # TODO: replace this default False
1581 # If your JSON schema fails to generate it is probably
1582 # because one of the following two branches failed.
1583 if use_strict:
1584 return self.generate_inner(schema['strict_schema'])
1585 else:
1586 return self.generate_inner(schema['lax_schema'])
1588 def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue:
1589 """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the
1590 Python schema.
1592 The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override
1593 this method.
1595 Args:
1596 schema: The core schema.
1598 Returns:
1599 The generated JSON schema.
1600 """
1601 return self.generate_inner(schema['json_schema'])
1603 def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue:
1604 """Generates a JSON schema that matches a schema that defines a typed dict.
1606 Args:
1607 schema: The core schema.
1609 Returns:
1610 The generated JSON schema.
1611 """
1612 total = schema.get('total', True)
1613 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
1614 (name, self.field_is_required(field, total), field)
1615 for name, field in schema['fields'].items()
1616 if self.field_is_present(field)
1617 ]
1618 if self.mode == 'serialization':
1619 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
1620 cls = schema.get('cls')
1621 config = _get_typed_dict_config(cls)
1622 with self._config_wrapper_stack.push(config):
1623 json_schema = self._named_required_fields_schema(named_required_fields)
1625 # There's some duplication between `extra_behavior` and
1626 # the config's `extra`/core config's `extra_fields_behavior`.
1627 # However, it is common to manually create TypedDictSchemas,
1628 # where you don't necessarily have a class.
1629 # At runtime, `extra_behavior` takes priority over the config
1630 # for validation, so follow the same for the JSON Schema:
1631 if 'extras_schema' in schema and schema['extras_schema'] != core_schema.any_schema():
1632 allow_additional_props = self.generate_inner(schema['extras_schema'])
1633 else:
1634 allow_additional_props = True
1636 if schema.get('extra_behavior') == 'forbid':
1637 json_schema['additionalProperties'] = False
1638 elif schema.get('extra_behavior') == 'allow':
1639 json_schema['additionalProperties'] = allow_additional_props
1641 if cls is not None:
1642 # `_update_class_schema()` will not override
1643 # `additionalProperties` if already present:
1644 self._update_class_schema(json_schema, cls, config or {})
1645 elif 'additionalProperties' not in json_schema:
1646 extra = schema.get('config', {}).get('extra_fields_behavior')
1647 if extra == 'forbid':
1648 json_schema['additionalProperties'] = False
1649 elif extra == 'allow':
1650 json_schema['additionalProperties'] = allow_additional_props
1652 return json_schema
1654 @staticmethod
1655 def _name_required_computed_fields(
1656 computed_fields: list[ComputedField],
1657 ) -> list[tuple[str, bool, core_schema.ComputedField]]:
1658 return [
1659 (field['property_name'], field.get('serialization_exclude_if') is None, field) for field in computed_fields
1660 ]
1662 def _named_required_fields_schema(
1663 self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]]
1664 ) -> JsonSchemaValue:
1665 properties: dict[str, JsonSchemaValue] = {}
1666 required_fields: list[str] = []
1667 for name, required, field in named_required_fields:
1668 if self.by_alias:
1669 name = self._get_alias_name(field, name)
1670 try:
1671 field_json_schema = self.generate_inner(field).copy()
1672 except PydanticOmit:
1673 continue
1674 if 'title' not in field_json_schema and self.field_title_should_be_set(field):
1675 title = self.get_title_from_name(name)
1676 field_json_schema['title'] = title
1677 field_json_schema = self.handle_ref_overrides(field_json_schema)
1678 properties[name] = field_json_schema
1679 if required:
1680 required_fields.append(name)
1682 json_schema = {'type': 'object', 'properties': properties}
1683 if required_fields:
1684 json_schema['required'] = required_fields
1685 return json_schema
1687 def _get_alias_name(self, field: CoreSchemaField, name: str) -> str:
1688 if field['type'] == 'computed-field':
1689 alias: Any = field.get('alias', name)
1690 elif self.mode == 'validation':
1691 use_alias = self._config.validate_by_alias if self._by_alias is None else self._by_alias
1692 alias = field.get('validation_alias', name) if use_alias else name
1693 else:
1694 alias = field.get('serialization_alias', name)
1695 if isinstance(alias, str):
1696 name = alias
1697 elif isinstance(alias, list):
1698 alias = cast('list[str] | str', alias)
1699 for path in alias:
1700 if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str):
1701 # Use the first valid single-item string path; the code that constructs the alias array
1702 # should ensure the first such item is what belongs in the JSON schema
1703 name = path[0]
1704 break
1705 else:
1706 assert_never(alias)
1707 return name
1709 def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue:
1710 """Generates a JSON schema that matches a schema that defines a typed dict field.
1712 Args:
1713 schema: The core schema.
1715 Returns:
1716 The generated JSON schema.
1717 """
1718 return self.generate_inner(schema['schema'])
1720 def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue:
1721 """Generates a JSON schema that matches a schema that defines a dataclass field.
1723 Args:
1724 schema: The core schema.
1726 Returns:
1727 The generated JSON schema.
1728 """
1729 return self.generate_inner(schema['schema'])
1731 def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue:
1732 """Generates a JSON schema that matches a schema that defines a model field.
1734 Args:
1735 schema: The core schema.
1737 Returns:
1738 The generated JSON schema.
1739 """
1740 return self.generate_inner(schema['schema'])
1742 def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue:
1743 """Generates a JSON schema that matches a schema that defines a computed field.
1745 Args:
1746 schema: The core schema.
1748 Returns:
1749 The generated JSON schema.
1750 """
1751 return self.generate_inner(schema['return_schema'])
1753 def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
1754 """Generates a JSON schema that matches a schema that defines a model.
1756 Args:
1757 schema: The core schema.
1759 Returns:
1760 The generated JSON schema.
1761 """
1762 # We do not use schema['model'].model_json_schema() here
1763 # because it could lead to inconsistent refs handling, etc.
1764 cls = cast('type[BaseModel]', schema['cls'])
1765 config = cls.model_config
1767 with self._config_wrapper_stack.push(config):
1768 json_schema = self.generate_inner(schema['schema'])
1770 self._update_class_schema(json_schema, cls, config)
1772 return json_schema
1774 def _update_class_schema(self, json_schema: JsonSchemaValue, cls: type[Any], config: ConfigDict) -> None:
1775 """Update json_schema with the following, extracted from `config` and `cls`:
1777 * title
1778 * description
1779 * additional properties
1780 * json_schema_extra
1781 * deprecated
1783 Done in place, hence there's no return value as the original json_schema is mutated.
1784 No ref resolving is involved here, as that's not appropriate for simple updates.
1785 """
1786 from ._internal._dataclasses import is_stdlib_dataclass
1787 from .main import BaseModel
1789 if (config_title := config.get('title')) is not None:
1790 json_schema.setdefault('title', config_title)
1791 elif model_title_generator := config.get('model_title_generator'):
1792 title = model_title_generator(cls)
1793 if not isinstance(title, str):
1794 raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')
1795 json_schema.setdefault('title', title)
1796 if 'title' not in json_schema:
1797 json_schema['title'] = cls.__name__
1799 # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default
1800 if cls is BaseModel:
1801 docstring = None
1802 elif is_stdlib_dataclass(cls): # For Pydantic dataclasses, we already handle this at class creation
1803 # The `dataclass` module generates a `__doc__` based on the `inspect.signature()`
1804 # result, which we don't want to use as a description. Such `__doc__` startswith
1805 # `cls.__name__(`, which could lead to mistakenly discarding it if for some reason
1806 # an explicitly set class docstring follows the same pattern, but this is unlikely
1807 # to happen.
1808 doc = cls.__doc__
1809 docstring = None if doc is None or doc.startswith(f'{cls.__name__}(') else doc
1810 else:
1811 docstring = cls.__doc__
1813 if docstring:
1814 json_schema.setdefault('description', inspect.cleandoc(docstring))
1816 extra = config.get('extra')
1817 if 'additionalProperties' not in json_schema: # This check is particularly important for `typed_dict_schema()`
1818 if extra == 'allow':
1819 json_schema['additionalProperties'] = True
1820 elif extra == 'forbid':
1821 json_schema['additionalProperties'] = False
1823 json_schema_extra = config.get('json_schema_extra')
1824 if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:
1825 root_json_schema_extra = cls.model_fields['root'].json_schema_extra
1826 if json_schema_extra and root_json_schema_extra:
1827 raise ValueError(
1828 '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
1829 ' field must not be set simultaneously'
1830 )
1831 if root_json_schema_extra:
1832 json_schema_extra = root_json_schema_extra
1834 if isinstance(json_schema_extra, (staticmethod, classmethod)):
1835 # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable
1836 json_schema_extra = json_schema_extra.__get__(cls)
1838 if isinstance(json_schema_extra, dict):
1839 json_schema.update(json_schema_extra)
1840 elif callable(json_schema_extra):
1841 if len(_typing_extra.signature_no_eval(json_schema_extra).parameters) > 1:
1842 json_schema_extra = cast(Callable[[JsonDict, type[Any]], None], json_schema_extra)
1843 json_schema_extra(json_schema, cls)
1844 else:
1845 json_schema_extra = cast(Callable[[JsonDict], None], json_schema_extra)
1846 json_schema_extra(json_schema)
1847 elif json_schema_extra is not None:
1848 raise ValueError(
1849 f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None"
1850 )
1852 if hasattr(cls, '__deprecated__'):
1853 json_schema['deprecated'] = True
1855 def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
1856 """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
1858 Args:
1859 json_schema: The schema to resolve.
1861 Returns:
1862 The resolved schema.
1864 Raises:
1865 RuntimeError: If the schema reference can't be found in definitions.
1866 """
1867 while '$ref' in json_schema:
1868 ref = json_schema['$ref']
1869 schema_to_update = self.get_schema_from_definitions(JsonRef(ref))
1870 if schema_to_update is None:
1871 raise RuntimeError(f'Cannot update undefined schema for $ref={ref}')
1872 json_schema = schema_to_update
1873 return json_schema
1875 def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue:
1876 """Generates a JSON schema that matches a schema that defines a model's fields.
1878 Args:
1879 schema: The core schema.
1881 Returns:
1882 The generated JSON schema.
1883 """
1884 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
1885 (name, self.field_is_required(field, total=True), field)
1886 for name, field in schema['fields'].items()
1887 if self.field_is_present(field)
1888 ]
1889 if self.mode == 'serialization':
1890 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
1891 json_schema = self._named_required_fields_schema(named_required_fields)
1892 extras_schema = schema.get('extras_schema', None)
1893 if extras_schema is not None:
1894 schema_to_update = self.resolve_ref_schema(json_schema)
1895 schema_to_update['additionalProperties'] = self.generate_inner(extras_schema)
1896 return json_schema
1898 def field_is_present(self, field: CoreSchemaField) -> bool:
1899 """Whether the field should be included in the generated JSON schema.
1901 Args:
1902 field: The schema for the field itself.
1904 Returns:
1905 `True` if the field should be included in the generated JSON schema, `False` otherwise.
1906 """
1907 if self.mode == 'serialization':
1908 # If you still want to include the field in the generated JSON schema,
1909 # override this method and return True
1910 return not field.get('serialization_exclude')
1911 elif self.mode == 'validation':
1912 return True
1913 else:
1914 assert_never(self.mode)
1916 def field_is_required(
1917 self,
1918 field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
1919 total: bool,
1920 ) -> bool:
1921 """Whether the field should be marked as required in the generated JSON schema.
1922 (Note that this is irrelevant if the field is not present in the JSON schema.).
1924 Args:
1925 field: The schema for the field itself.
1926 total: Only applies to `TypedDictField`s.
1927 Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't
1928 explicitly specify `required=False` are required.
1930 Returns:
1931 `True` if the field should be marked as required in the generated JSON schema, `False` otherwise.
1932 """
1933 if field['type'] == 'typed-dict-field':
1934 required = field.get('required', total)
1935 else:
1936 required = field['schema']['type'] != 'default'
1938 if self.mode == 'serialization':
1939 has_exclude_if = field.get('serialization_exclude_if') is not None
1940 if self._config.json_schema_serialization_defaults_required:
1941 return not has_exclude_if
1942 else:
1943 return required and not has_exclude_if
1944 else:
1945 return required
1947 def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue:
1948 """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
1950 Args:
1951 schema: The core schema.
1953 Returns:
1954 The generated JSON schema.
1955 """
1956 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
1957 (field['name'], self.field_is_required(field, total=True), field)
1958 for field in schema['fields']
1959 if self.field_is_present(field)
1960 ]
1961 if self.mode == 'serialization':
1962 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
1963 return self._named_required_fields_schema(named_required_fields)
1965 def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
1966 """Generates a JSON schema that matches a schema that defines a dataclass.
1968 Args:
1969 schema: The core schema.
1971 Returns:
1972 The generated JSON schema.
1973 """
1975 cls = schema['cls']
1976 # If (stdlib) dataclass doesn't have config, the parent's config is used (as during core schema generation):
1977 config = cast('ConfigDict | None', getattr(cls, '__pydantic_config__', None))
1979 with self._config_wrapper_stack.push(config):
1980 json_schema = self.generate_inner(schema['schema']).copy()
1982 # Only the parent's `extra` config value is relevant to the class schema. It is propagated
1983 # to the core config (and used for validation), so we reuse it:
1984 class_config = config or {}
1985 if 'extra' not in class_config and (extra := schema.get('config', {}).get('extra_fields_behavior')) is not None:
1986 class_config = cast('ConfigDict', {**class_config, 'extra': extra})
1988 self._update_class_schema(json_schema, cls, class_config)
1990 return json_schema
1992 def named_tuple_field_schema(self, schema: core_schema.NamedTupleField) -> JsonSchemaValue:
1993 """Generates a JSON schema that matches a schema that defines a named tuple field.
1995 Args:
1996 schema: The core schema.
1998 Returns:
1999 The generated JSON schema.
2000 """
2001 return self.generate_inner(schema['schema'])
2003 def named_tuple_schema(self, schema: core_schema.NamedTupleSchema) -> JsonSchemaValue:
2004 """Generates a JSON schema that matches a schema that defines a named tuple.
2006 Args:
2007 schema: The core schema.
2009 Returns:
2010 The generated JSON schema.
2011 """
2012 prefix_items: list[JsonSchemaValue] = []
2013 min_items = 0
2015 for field in schema['fields']:
2016 name = field['name']
2017 if self.by_alias:
2018 alias = field.get('validation_alias')
2019 if isinstance(alias, str):
2020 name = alias
2022 field_schema = self.generate_inner(field['schema']).copy()
2023 if 'title' not in field_schema and self.field_title_should_be_set(field['schema']):
2024 field_schema['title'] = self.get_title_from_name(name)
2025 prefix_items.append(field_schema)
2027 if field['schema']['type'] != 'default':
2028 # This assumes that if the field has a default value,
2029 # the inner schema must be of type WithDefaultSchema.
2030 min_items += 1
2032 json_schema: JsonSchemaValue = {'type': 'array'}
2033 if prefix_items:
2034 json_schema['prefixItems'] = prefix_items
2035 if min_items:
2036 json_schema['minItems'] = min_items
2037 json_schema['maxItems'] = len(prefix_items)
2039 return json_schema
2041 def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:
2042 """Generates a JSON schema that matches a schema that defines a function's arguments.
2044 Args:
2045 schema: The core schema.
2047 Returns:
2048 The generated JSON schema.
2049 """
2050 prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments')
2052 arguments = schema['arguments_schema']
2053 kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only']
2054 kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}]
2055 p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only']
2056 var_args_schema = schema.get('var_args_schema')
2057 var_kwargs_schema = schema.get('var_kwargs_schema')
2059 if prefer_positional:
2060 positional_possible = not kw_only_arguments and not var_kwargs_schema
2061 if positional_possible:
2062 return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
2064 keyword_possible = not p_only_arguments and not var_args_schema
2065 if keyword_possible:
2066 return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema)
2068 if not prefer_positional:
2069 positional_possible = not kw_only_arguments and not var_kwargs_schema
2070 if positional_possible:
2071 return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
2073 raise PydanticInvalidForJsonSchema(
2074 'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
2075 )
2077 def kw_arguments_schema(
2078 self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None
2079 ) -> JsonSchemaValue:
2080 """Generates a JSON schema that matches a schema that defines a function's keyword arguments.
2082 Args:
2083 arguments: The core schema.
2085 Returns:
2086 The generated JSON schema.
2087 """
2088 properties: dict[str, JsonSchemaValue] = {}
2089 required: list[str] = []
2090 for argument in arguments:
2091 name = self.get_argument_name(argument)
2092 argument_schema = self.generate_inner(argument['schema']).copy()
2093 if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
2094 argument_schema['title'] = self.get_title_from_name(name)
2095 properties[name] = argument_schema
2097 if argument['schema']['type'] != 'default':
2098 # This assumes that if the argument has a default value,
2099 # the inner schema must be of type WithDefaultSchema.
2100 # I believe this is true, but I am not 100% sure
2101 required.append(name)
2103 json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
2104 if required:
2105 json_schema['required'] = required
2107 if var_kwargs_schema:
2108 additional_properties_schema = self.generate_inner(var_kwargs_schema)
2109 if additional_properties_schema:
2110 json_schema['additionalProperties'] = additional_properties_schema
2111 else:
2112 json_schema['additionalProperties'] = False
2113 return json_schema
2115 def p_arguments_schema(
2116 self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
2117 ) -> JsonSchemaValue:
2118 """Generates a JSON schema that matches a schema that defines a function's positional arguments.
2120 Args:
2121 arguments: The core schema.
2123 Returns:
2124 The generated JSON schema.
2125 """
2126 prefix_items: list[JsonSchemaValue] = []
2127 min_items = 0
2129 for argument in arguments:
2130 name = self.get_argument_name(argument)
2132 argument_schema = self.generate_inner(argument['schema']).copy()
2133 if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
2134 argument_schema['title'] = self.get_title_from_name(name)
2135 prefix_items.append(argument_schema)
2137 if argument['schema']['type'] != 'default':
2138 # This assumes that if the argument has a default value,
2139 # the inner schema must be of type WithDefaultSchema.
2140 # I believe this is true, but I am not 100% sure
2141 min_items += 1
2143 json_schema: JsonSchemaValue = {'type': 'array'}
2144 if prefix_items:
2145 json_schema['prefixItems'] = prefix_items
2146 if min_items:
2147 json_schema['minItems'] = min_items
2149 if var_args_schema:
2150 items_schema = self.generate_inner(var_args_schema)
2151 if items_schema:
2152 json_schema['items'] = items_schema
2153 else:
2154 json_schema['maxItems'] = len(prefix_items)
2156 return json_schema
2158 def get_argument_name(self, argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) -> str:
2159 """Retrieves the name of an argument.
2161 Args:
2162 argument: The core schema.
2164 Returns:
2165 The name of the argument.
2166 """
2167 name = argument['name']
2168 if self.by_alias:
2169 alias = argument.get('alias')
2170 if isinstance(alias, str):
2171 name = alias
2172 else:
2173 pass # might want to do something else?
2174 return name
2176 def arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue:
2177 """Generates a JSON schema that matches a schema that defines a function's arguments.
2179 Args:
2180 schema: The core schema.
2182 Returns:
2183 The generated JSON schema.
2184 """
2185 arguments = schema['arguments_schema']
2186 properties: dict[str, JsonSchemaValue] = {}
2187 required: list[str] = []
2188 for argument in arguments:
2189 mode = argument.get('mode', 'positional_or_keyword')
2190 name = self.get_argument_name(argument)
2191 argument_schema = self.generate_inner(argument['schema']).copy()
2192 if mode == 'var_args':
2193 argument_schema = {'type': 'array', 'items': argument_schema}
2194 elif mode == 'var_kwargs_uniform':
2195 argument_schema = {'type': 'object', 'additionalProperties': argument_schema}
2197 argument_schema.setdefault('title', self.get_title_from_name(name))
2198 properties[name] = argument_schema
2200 if (
2201 (mode == 'var_kwargs_unpacked_typed_dict' and 'required' in argument_schema)
2202 or mode not in {'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'}
2203 and argument['schema']['type'] != 'default'
2204 ):
2205 # This assumes that if the argument has a default value,
2206 # the inner schema must be of type WithDefaultSchema.
2207 # I believe this is true, but I am not 100% sure
2208 required.append(name)
2210 json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
2211 if required:
2212 json_schema['required'] = required
2213 return json_schema
2215 def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:
2216 """Generates a JSON schema that matches a schema that defines a function call.
2218 Args:
2219 schema: The core schema.
2221 Returns:
2222 The generated JSON schema.
2223 """
2224 return self.generate_inner(schema['arguments_schema'])
2226 def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue:
2227 """Generates a JSON schema that matches a schema that defines a custom error.
2229 Args:
2230 schema: The core schema.
2232 Returns:
2233 The generated JSON schema.
2234 """
2235 return self.generate_inner(schema['schema'])
2237 def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue:
2238 """Generates a JSON schema that matches a schema that defines a JSON object.
2240 Args:
2241 schema: The core schema.
2243 Returns:
2244 The generated JSON schema.
2245 """
2246 content_core_schema = schema.get('schema') or core_schema.any_schema()
2247 content_json_schema = self.generate_inner(content_core_schema)
2248 if self.mode == 'validation':
2249 return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema}
2250 else:
2251 # self.mode == 'serialization'
2252 return content_json_schema
2254 def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue:
2255 """Generates a JSON schema that matches a schema that defines a URL.
2257 Args:
2258 schema: The core schema.
2260 Returns:
2261 The generated JSON schema.
2262 """
2263 json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1}
2264 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
2265 return json_schema
2267 def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue:
2268 """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
2270 Args:
2271 schema: The core schema.
2273 Returns:
2274 The generated JSON schema.
2275 """
2276 # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
2277 json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1}
2278 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
2279 return json_schema
2281 def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue:
2282 """Generates a JSON schema that matches a UUID.
2284 Args:
2285 schema: The core schema.
2287 Returns:
2288 The generated JSON schema.
2289 """
2290 return {'type': 'string', 'format': 'uuid'}
2292 def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue:
2293 """Generates a JSON schema that matches a schema that defines a JSON object with definitions.
2295 Args:
2296 schema: The core schema.
2298 Returns:
2299 The generated JSON schema.
2300 """
2301 for definition in schema['definitions']:
2302 try:
2303 self.generate_inner(definition)
2304 except PydanticInvalidForJsonSchema as e: # noqa: PERF203
2305 core_ref: CoreRef = CoreRef(definition['ref']) # type: ignore
2306 self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
2307 continue
2308 return self.generate_inner(schema['schema'])
2310 def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:
2311 """Generates a JSON schema that matches a schema that references a definition.
2313 Args:
2314 schema: The core schema.
2316 Returns:
2317 The generated JSON schema.
2318 """
2319 core_ref = CoreRef(schema['schema_ref'])
2320 _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
2321 return ref_json_schema
2323 def ser_schema(
2324 self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
2325 ) -> JsonSchemaValue | None:
2326 """Generates a JSON schema that matches a schema that defines a serialized object.
2328 Args:
2329 schema: The core schema.
2331 Returns:
2332 The generated JSON schema.
2333 """
2334 match schema:
2335 case {'type': 'function-plain' | 'function-wrap'}:
2336 # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
2337 return_schema = schema.get('return_schema')
2338 if return_schema is not None:
2339 return self.generate_inner(return_schema)
2340 case {'type': 'format' | 'to-string'}:
2341 # FormatSerSchema or ToStringSerSchema
2342 return self.str_schema(core_schema.str_schema())
2343 case {'type': 'model'}:
2344 # ModelSerSchema
2345 return self.generate_inner(schema['schema'])
2346 return None
2348 def complex_schema(self, schema: core_schema.ComplexSchema) -> JsonSchemaValue:
2349 """Generates a JSON schema that matches a complex number.
2351 JSON has no standard way to represent complex numbers. Complex number is not a numeric
2352 type. Here we represent complex number as strings following the rule defined by Python.
2353 For instance, '1+2j' is an accepted complex string. Details can be found in
2354 [Python's `complex` documentation][complex].
2356 Args:
2357 schema: The core schema.
2359 Returns:
2360 The generated JSON schema.
2361 """
2362 return {'type': 'string'}
2364 # ### Utility methods
2366 def get_title_from_name(self, name: str) -> str:
2367 """Retrieves a title from a name.
2369 Args:
2370 name: The name to retrieve a title from.
2372 Returns:
2373 The title.
2374 """
2375 return name.title().replace('_', ' ').strip()
2377 def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
2378 """Returns true if a field with the given schema should have a title set based on the field name.
2380 Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title
2381 (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
2383 Args:
2384 schema: The schema to check.
2386 Returns:
2387 `True` if the field should have a title set, `False` otherwise.
2388 """
2389 if _core_utils.is_core_schema_field(schema):
2390 if schema['type'] == 'computed-field':
2391 field_schema = schema['return_schema']
2392 else:
2393 field_schema = schema['schema']
2394 return self.field_title_should_be_set(field_schema)
2396 elif _core_utils.is_core_schema(schema):
2397 if schema.get('ref'): # things with refs, such as models and enums, should not have titles set
2398 return False
2399 if schema['type'] in {'default', 'nullable', 'definitions'}:
2400 return self.field_title_should_be_set(schema['schema']) # type: ignore[typeddict-item]
2401 if schema['type'] == 'missing-sentinel' and (inner_schema := schema.get('schema')) is not None:
2402 return self.field_title_should_be_set(inner_schema)
2403 if _core_utils.is_function_with_inner_schema(schema):
2404 return self.field_title_should_be_set(schema['schema'])
2405 if schema['type'] == 'definition-ref':
2406 # Referenced schemas should not have titles set for the same reason
2407 # schemas with refs should not
2408 return False
2409 return True # anything else should have title set
2411 else:
2412 raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}') # pragma: no cover
2414 def normalize_name(self, name: str) -> str:
2415 """Normalizes a name to be used as a key in a dictionary.
2417 Args:
2418 name: The name to normalize.
2420 Returns:
2421 The normalized name.
2422 """
2423 return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__')
2425 def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
2426 """Override this method to change the way that definitions keys are generated from a core reference.
2428 Args:
2429 core_mode_ref: The core reference.
2431 Returns:
2432 The definitions key.
2433 """
2434 # Split the core ref into "components"; generic origins and arguments are each separate components
2435 core_ref, mode = core_mode_ref
2436 components = re.split(r'([\][,])', core_ref)
2437 # Remove IDs from each component
2438 components = [x.rsplit(':', 1)[0] for x in components]
2439 core_ref_no_id = ''.join(components)
2440 # Remove everything before the last period from each "component"
2441 components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
2442 short_ref = ''.join(components)
2444 mode_title = _MODE_TITLE_MAPPING[mode]
2446 # It is important that the generated defs_ref values be such that at least one choice will not
2447 # be generated for any other core_ref. Currently, this should be the case because we include
2448 # the id of the source type in the core_ref
2449 name = DefsRef(self.normalize_name(short_ref))
2450 name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}')
2451 module_qualname = DefsRef(self.normalize_name(core_ref_no_id))
2452 module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}')
2453 module_qualname_id = DefsRef(self.normalize_name(core_ref))
2454 occurrence_index = self._collision_index.get(module_qualname_id)
2455 if occurrence_index is None:
2456 self._collision_counter[module_qualname] += 1
2457 occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname]
2459 module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}')
2460 module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}')
2462 self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [
2463 name,
2464 name_mode,
2465 module_qualname,
2466 module_qualname_mode,
2467 module_qualname_occurrence,
2468 module_qualname_occurrence_mode,
2469 ]
2471 return module_qualname_occurrence_mode
2473 def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]:
2474 """This method wraps the get_defs_ref method with some cache-lookup/population logic,
2475 and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
2477 Args:
2478 core_ref: The core reference to get the definitions reference for.
2480 Returns:
2481 A tuple of the definitions reference and the JSON schema that will refer to it.
2482 """
2483 core_mode_ref = (core_ref, self.mode)
2484 maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref)
2485 if maybe_defs_ref is not None:
2486 json_ref = self.core_to_json_refs[core_mode_ref]
2487 return maybe_defs_ref, {'$ref': json_ref}
2489 defs_ref = self.get_defs_ref(core_mode_ref)
2491 # populate the ref translation mappings
2492 self.core_to_defs_refs[core_mode_ref] = defs_ref
2493 self.defs_to_core_refs[defs_ref] = core_mode_ref
2495 json_ref = JsonRef(self.ref_template.format(model=defs_ref))
2496 self.core_to_json_refs[core_mode_ref] = json_ref
2497 self.json_to_defs_refs[json_ref] = defs_ref
2498 ref_json_schema = {'$ref': json_ref}
2499 return defs_ref, ref_json_schema
2501 def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
2502 """Remove any sibling keys that are redundant with the referenced schema.
2504 Args:
2505 json_schema: The schema to remove redundant sibling keys from.
2507 Returns:
2508 The schema with redundant sibling keys removed.
2509 """
2510 if '$ref' in json_schema:
2511 # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
2512 json_schema = json_schema.copy()
2514 referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
2515 if referenced_json_schema is None:
2516 # This can happen when building schemas for models with not-yet-defined references.
2517 # It may be a good idea to do a recursive pass at the end of the generation to remove
2518 # any redundant override keys.
2519 return json_schema
2520 for k, v in list(json_schema.items()):
2521 if k == '$ref':
2522 continue
2523 if k in referenced_json_schema and referenced_json_schema[k] == v:
2524 del json_schema[k] # redundant key
2526 return json_schema
2528 def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None:
2529 try:
2530 def_ref = self.json_to_defs_refs[json_ref]
2531 if def_ref in self._core_defs_invalid_for_json_schema:
2532 raise self._core_defs_invalid_for_json_schema[def_ref]
2533 return self.definitions.get(def_ref, None)
2534 except KeyError:
2535 if json_ref.startswith(('http://', 'https://')):
2536 return None
2537 raise
2539 def encode_default(self, dft: Any) -> Any:
2540 """Encode a default value to a JSON-serializable value.
2542 This is used to encode default values for fields in the generated JSON schema.
2544 Args:
2545 dft: The default value to encode.
2547 Returns:
2548 The encoded default value.
2549 """
2550 from .type_adapter import TypeAdapter, _type_has_config
2552 config = self._config.config_dict
2553 if self.mode == 'validation' and ('ser_json_temporal' in config or 'ser_json_timedelta' in config):
2554 # Temporal serialization formats aren't applied to validation JSON Schemas (see `_common_temporal_schema()`),
2555 # so they shouldn't be applied to the default either:
2556 config = cast(
2557 'ConfigDict',
2558 {k: v for k, v in config.items() if k not in ('ser_json_temporal', 'ser_json_timedelta')},
2559 )
2560 try:
2561 # Types with their own config (e.g. models) can't be used with a config, so we serialize "as Any",
2562 # which will serialize using their own serializer.
2563 return TypeAdapter(Any if _type_has_config(type(dft)) else type(dft), config=config).dump_python(
2564 dft, by_alias=self.by_alias, mode='json'
2565 )
2566 except Exception as e:
2567 raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}') from e
2569 def update_with_validations(
2570 self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
2571 ) -> None:
2572 """Update the json_schema with the corresponding validations specified in the core_schema,
2573 using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
2575 Args:
2576 json_schema: The JSON schema to update.
2577 core_schema: The core schema to get the validations from.
2578 mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
2579 """
2580 for core_key, json_schema_key in mapping.items():
2581 if core_key in core_schema:
2582 json_schema[json_schema_key] = core_schema[core_key]
2584 class ValidationsMapping:
2585 """This class just contains mappings from core_schema attribute names to the corresponding
2586 JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in
2587 principle override this class in a subclass of GenerateJsonSchema (by inheriting from
2588 GenerateJsonSchema.ValidationsMapping) to change these mappings.
2589 """
2591 numeric = {
2592 'multiple_of': 'multipleOf',
2593 'le': 'maximum',
2594 'ge': 'minimum',
2595 'lt': 'exclusiveMaximum',
2596 'gt': 'exclusiveMinimum',
2597 }
2598 bytes = {
2599 'min_length': 'minLength',
2600 'max_length': 'maxLength',
2601 }
2602 string = {
2603 'min_length': 'minLength',
2604 'max_length': 'maxLength',
2605 'pattern': 'pattern',
2606 }
2607 array = {
2608 'min_length': 'minItems',
2609 'max_length': 'maxItems',
2610 }
2611 object = {
2612 'min_length': 'minProperties',
2613 'max_length': 'maxProperties',
2614 }
2616 def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
2617 members = []
2618 for schema in schemas:
2619 if len(schema) == 1 and 'anyOf' in schema:
2620 members.extend(schema['anyOf'])
2621 else:
2622 members.append(schema)
2623 members = _deduplicate_schemas(members)
2624 if len(members) == 1:
2625 return members[0]
2626 return {'anyOf': members}
2628 def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]:
2629 """Get all values corresponding to the key '$ref' anywhere in the json_schema."""
2630 json_refs: dict[JsonRef, int] = Counter()
2632 def _add_json_refs(schema: Any) -> None:
2633 if isinstance(schema, dict):
2634 if '$ref' in schema:
2635 json_ref = JsonRef(schema['$ref'])
2636 if not isinstance(json_ref, str):
2637 return # in this case, '$ref' might have been the name of a property
2638 already_visited = json_ref in json_refs
2639 json_refs[json_ref] += 1
2640 if already_visited:
2641 return # prevent recursion on a definition that was already visited
2642 try:
2643 defs_ref = self.json_to_defs_refs[json_ref]
2644 if defs_ref in self._core_defs_invalid_for_json_schema:
2645 raise self._core_defs_invalid_for_json_schema[defs_ref]
2646 _add_json_refs(self.definitions[defs_ref])
2647 except KeyError:
2648 if not json_ref.startswith(('http://', 'https://')):
2649 raise
2651 for k, v in schema.items():
2652 if k == 'examples' and isinstance(v, list):
2653 # Skip examples that may contain arbitrary values and references
2654 # (see the comment in `_get_all_json_refs` for more details).
2655 continue
2656 _add_json_refs(v)
2657 elif isinstance(schema, list):
2658 for v in schema:
2659 _add_json_refs(v)
2661 _add_json_refs(json_schema)
2662 return json_refs
2664 def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue:
2665 raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
2667 def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None:
2668 """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method."""
2669 message = self.render_warning_message(kind, detail)
2670 if message is not None:
2671 warnings.warn(message, PydanticJsonSchemaWarning)
2673 def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None:
2674 """This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
2676 You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema
2677 to modify what warnings are generated. If you want more control, you can override this method;
2678 just return None in situations where you don't want warnings to be emitted.
2680 Args:
2681 kind: The kind of warning to render. It can be one of the following:
2683 - 'skipped-choice': A choice field was skipped because it had no valid choices.
2684 - 'non-serializable-default': A default value was skipped because it was not JSON-serializable.
2685 detail: A string with additional details about the warning.
2687 Returns:
2688 The formatted warning message, or `None` if no warning should be emitted.
2689 """
2690 if kind in self.ignored_warning_kinds:
2691 return None
2692 return f'{detail} [{kind}]'
2694 def _build_definitions_remapping(self) -> _DefinitionsRemapping:
2695 defs_to_json: dict[DefsRef, JsonRef] = {}
2696 for defs_refs in self._prioritized_defsref_choices.values():
2697 for defs_ref in defs_refs:
2698 json_ref = JsonRef(self.ref_template.format(model=defs_ref))
2699 defs_to_json[defs_ref] = json_ref
2701 return _DefinitionsRemapping.from_prioritized_choices(
2702 self._prioritized_defsref_choices, defs_to_json, self.definitions
2703 )
2705 def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None:
2706 visited_defs_refs: set[DefsRef] = set()
2707 unvisited_json_refs = _get_all_json_refs(schema)
2708 while unvisited_json_refs:
2709 next_json_ref = unvisited_json_refs.pop()
2710 try:
2711 next_defs_ref = self.json_to_defs_refs[next_json_ref]
2712 if next_defs_ref in visited_defs_refs:
2713 continue
2714 visited_defs_refs.add(next_defs_ref)
2715 unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref]))
2716 except KeyError:
2717 if not next_json_ref.startswith(('http://', 'https://')):
2718 raise
2720 self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs}
2723# ##### Start JSON Schema Generation Functions #####
2726def model_json_schema(
2727 cls: type[BaseModel] | type[PydanticDataclass],
2728 by_alias: bool | None = None,
2729 ref_template: str = DEFAULT_REF_TEMPLATE,
2730 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
2731 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
2732 mode: JsonSchemaMode = 'validation',
2733) -> dict[str, Any]:
2734 """Utility function to generate a JSON Schema for a model.
2736 Args:
2737 cls: The model class to generate a JSON Schema for.
2738 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
2739 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
2740 schemas). An explicit value takes precedence over the configuration.
2741 ref_template: The template to use for generating JSON Schema references.
2742 union_format: The format to use when combining schemas from unions together. Can be one of:
2744 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
2745 keyword to combine schemas (the default).
2746 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
2747 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
2748 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
2749 `any_of`.
2750 schema_generator: The class to use for generating the JSON Schema.
2751 mode: The mode to use for generating the JSON Schema. It can be one of the following:
2753 - 'validation': Generate a JSON Schema for validating data.
2754 - 'serialization': Generate a JSON Schema for serializing data.
2756 Returns:
2757 The generated JSON Schema.
2758 """
2759 from .main import BaseModel
2761 schema_generator_instance = schema_generator(
2762 by_alias=by_alias, ref_template=ref_template, union_format=union_format
2763 )
2765 if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
2766 cls.__pydantic_core_schema__.rebuild()
2768 if cls is BaseModel:
2769 raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')
2771 assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
2772 return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)
2775def models_json_schema(
2776 models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
2777 *,
2778 by_alias: bool | None = None,
2779 title: str | None = None,
2780 description: str | None = None,
2781 ref_template: str = DEFAULT_REF_TEMPLATE,
2782 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
2783 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
2784) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
2785 """Utility function to generate a JSON Schema for multiple models.
2787 Args:
2788 models: A sequence of tuples of the form (model, mode).
2789 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
2790 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
2791 schemas). An explicit value takes precedence over the configuration.
2792 title: The title of the generated JSON Schema.
2793 description: The description of the generated JSON Schema.
2794 ref_template: The reference template to use for generating JSON Schema references.
2795 union_format: The format to use when combining schemas from unions together. Can be one of:
2797 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
2798 keyword to combine schemas (the default).
2799 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
2800 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
2801 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
2802 `any_of`.
2803 schema_generator: The schema generator to use for generating the JSON Schema.
2805 Returns:
2806 A tuple where:
2807 - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
2808 whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
2809 JsonRef references to definitions that are defined in the second returned element.)
2810 - The second element is a JSON schema containing all definitions referenced in the first returned
2811 element, along with the optional title and description keys.
2812 """
2813 for cls, _ in models:
2814 if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
2815 cls.__pydantic_core_schema__.rebuild()
2817 instance = schema_generator(by_alias=by_alias, ref_template=ref_template, union_format=union_format)
2818 inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [
2819 (m, mode, m.__pydantic_core_schema__) for m, mode in models
2820 ]
2821 json_schemas_map, definitions = instance.generate_definitions(inputs)
2823 json_schema: dict[str, Any] = {}
2824 if definitions:
2825 json_schema['$defs'] = definitions
2826 if title:
2827 json_schema['title'] = title
2828 if description:
2829 json_schema['description'] = description
2831 return json_schemas_map, json_schema
2834# ##### End JSON Schema Generation Functions #####
2837# Decimal JSON Schema pattern utilities.
2838# Note: while we could use `\d` to represent digits (`Decimal` objects allow Unicode decimal digits), we use [0-9] instead:
2839# - to reduce complexity (`\d` expands to a large set, and with `max_digits`/`decimal_places` constraints set, it can blow
2840# the compile limit on some engines).
2841# - [0-9] is a portable pattern (e.g. `\d` is equivalent to `[0-9]` in ECMA (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape#d)
2842# while it allows any Unicode decimal digit in Python.
2845def _repeat(atom: str, min_count: int, max_count: int) -> str:
2846 """Build a regex repetition of `atom` between `min_count` and `max_count` times (inclusive), using the shortest quantifier."""
2847 if min_count > max_count or max_count == 0:
2848 return ''
2849 if min_count == max_count:
2850 return atom if min_count == 1 else f'{atom}{{{min_count}}}'
2851 if (min_count, max_count) == (0, 1):
2852 return f'{atom}?'
2853 return f'{atom}{{{min_count},{max_count}}}'
2856def _int_range_pattern(max_value: int) -> str:
2857 """Build a regex matching the integers between 1 and `max_value` (inclusive), without leading zeros."""
2858 digits = str(max_value)
2859 length = len(digits)
2860 alts: list[str] = [f'[1-9]{_repeat("[0-9]", k - 1, k - 1)}' for k in range(1, length)]
2861 for i, char in enumerate(digits):
2862 d = int(char)
2863 low = 1 if i == 0 else 0
2864 high = d if i == length - 1 else d - 1
2865 if high >= low:
2866 char_class = str(low) if low == high else f'[{low}-{high}]'
2867 alts.append(f'{digits[:i]}{char_class}{_repeat("[0-9]", length - i - 1, length - i - 1)}')
2868 return alts[0] if len(alts) == 1 else f'(?:{"|".join(alts)})'
2871def _decimal_validation_pattern(max_digits: int | None, decimal_places: int | None, allow_inf_nan: bool) -> str:
2872 """Build the decimal pattern for the `'validation'` mode."""
2874 number = r'(?:[0-9]+\.?[0-9]*|\.[0-9]+)' # e.g. 1, 1., .5
2875 exponent = r'[eE][+-]?[0-9]+' # e.g. e5, E5, e-7
2876 # e.g. Infinity, inf, NaN, sNaN, NaN123 (case-insensitive). Spelled out explicitly, as inline flags
2877 # aren't supported by all regular expression engines:
2878 non_finite = r'|[iI][nN][fF](?:[iI][nN][iI][tT][yY])?|[sS]?[nN][aA][nN][0-9]*' if allow_inf_nan else ''
2879 if max_digits is None and decimal_places is None:
2880 return rf'^[+-]?(?:{number}(?:{exponent})?{non_finite})$'
2882 alts: list[str] = []
2883 if max_digits is not None and decimal_places is not None:
2884 # If `decimal_places > max_digits`, no whole digits are allowed and `max_digits` bounds the decimal places:
2885 whole = max(0, max_digits - decimal_places)
2886 places = min(max_digits, decimal_places)
2887 int_part = f'0*{_repeat("[0-9]", 1, whole)}' if whole else '0+'
2888 opt_int_part = f'0*{_repeat("[0-9]", 0, whole)}'
2889 opt_frac_part = rf'\.{_repeat("[0-9]", 0, places)}0*'
2890 frac_part = rf'\.{_repeat("[0-9]", 1, places)}0*' if places else r'\.0+'
2891 alts += [f'{int_part}(?:{opt_frac_part})?', f'{opt_int_part}{frac_part}']
2892 elif max_digits is not None:
2893 # The whole part and decimal part must have at most `max_digits` digits in total,
2894 # so we enumerate the possible widths of the whole part:
2895 int_part = f'0*{_repeat("[0-9]", 1, max_digits)}' if max_digits else '0+'
2896 alts.append(rf'{int_part}(?:\.0*)?')
2897 alts += [
2898 rf'0*{_repeat("[0-9]", whole, whole)}\.{_repeat("[0-9]", 1, max_digits - whole)}0*'
2899 for whole in range(max_digits)
2900 ] or [r'0*\.0+']
2901 else:
2902 assert decimal_places is not None
2903 opt_frac_part = rf'\.{_repeat("[0-9]", 0, decimal_places)}0*'
2904 frac_part = rf'\.{_repeat("[0-9]", 1, decimal_places)}0*' if decimal_places else r'\.0+'
2905 alts += [f'[0-9]+(?:{opt_frac_part})?', f'[0-9]*{frac_part}']
2907 alts.append(f'{number}{exponent}')
2908 return rf'^[+-]?(?:{"|".join(alts)}{non_finite})$'
2911def _decimal_serialization_pattern(max_digits: int | None, decimal_places: int | None, allow_inf_nan: bool) -> str:
2912 """Build the decimal pattern for the `'serialization'` mode.
2914 Decimals are serialized using `str()`, producing either:
2916 - The plain notation (`'123.45'`), when the exponent is lower than or equal to 0 and the adjusted
2917 exponent is greater than or equal to -6.
2918 - The scientific notation otherwise (`'1E+3'`, `'1.5E-7'`, `'0E-10'`), with a single digit before
2919 the optional decimal point and an always signed exponent.
2921 Trailing zeros of the decimal part are preserved by `str()`, but aren't counted by the validation logic.
2922 """
2924 def frac_part(places: int) -> str:
2925 return rf'\.{_repeat("[0-9]", 1, places)}0*' if places else r'\.0+'
2927 alts: list[str] = []
2929 # Plain notation:
2930 if max_digits is not None and decimal_places is not None:
2931 whole = max(0, max_digits - decimal_places)
2932 places = min(max_digits, decimal_places)
2933 int_part = f'(?:0|[1-9]{_repeat("[0-9]", 0, whole - 1)})' if whole else '0'
2934 alts.append(f'{int_part}(?:{frac_part(places)})?')
2935 elif max_digits is not None:
2936 # The whole part and decimal part must have at most `max_digits` digits in total,
2937 # so we enumerate the possible widths of the whole part:
2938 alts.append(rf'0(?:\.{_repeat("[0-9]", 1, max_digits)}0*)?')
2939 alts += [
2940 f'[1-9]{_repeat("[0-9]", whole - 1, whole - 1)}(?:{frac_part(max_digits - whole)})?'
2941 for whole in range(1, max_digits + 1)
2942 ]
2943 elif decimal_places is not None:
2944 alts.append(f'(?:0|[1-9][0-9]*)(?:{frac_part(decimal_places)})?')
2945 else:
2946 alts.append(r'(?:0|[1-9][0-9]*)(?:\.[0-9]+)?')
2948 # Zero with an exponent (e.g. `'0E-10'`), which normalizes to zero and thus satisfies any constraint:
2949 alts.append(r'0E[+-][1-9][0-9]*')
2951 # Scientific notation with a positive exponent `k` (e.g. `'1.5E+3'`): the value has `k + 1` whole digits
2952 # and no decimal places:
2953 if max_digits is None:
2954 alts.append(r'[1-9](?:\.[0-9]+)?E\+[1-9][0-9]*')
2955 else:
2956 max_exponent = max_digits - (decimal_places or 0) - 1
2957 if max_exponent >= 1:
2958 alts.append(rf'[1-9](?:\.[0-9]+)?E\+{_int_range_pattern(max_exponent)}')
2960 # Scientific notation with a negative exponent `k` (`k >= 7`, e.g. `'1.5E-7'`): the value has no whole digits,
2961 # and `k` + (the number of significant decimal digits of the coefficient) decimal places:
2962 if max_digits is None and decimal_places is None:
2963 alts.append(r'[1-9](?:\.[0-9]+)?E-[1-9][0-9]*')
2964 else:
2965 max_places = min(c for c in (max_digits, decimal_places) if c is not None)
2966 alts += [f'[1-9](?:{frac_part(max_places - k)})?E-{k}' for k in range(7, max_places + 1)]
2968 if allow_inf_nan:
2969 # `str()` produces `'Infinity'`, `'NaN'` and `'sNaN'` (with an optional payload):
2970 alts += ['Infinity', 's?NaN[0-9]*']
2972 return rf'^-?(?:{"|".join(alts)})$'
2975def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]:
2976 return list({_make_json_hashable(schema): schema for schema in schemas}.values())
2979_HashableJsonValue: TypeAlias = (
2980 int | float | str | bool | None | tuple['_HashableJsonValue', ...] | tuple[tuple[str, '_HashableJsonValue'], ...]
2981)
2984def _make_json_hashable(value: JsonValue) -> _HashableJsonValue:
2985 if isinstance(value, dict):
2986 return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items()))
2987 elif isinstance(value, list):
2988 return tuple(_make_json_hashable(v) for v in value)
2989 else:
2990 return value
2993@dataclasses.dataclass(slots=True)
2994class WithJsonSchema:
2995 """!!! abstract "Usage Documentation"
2996 [`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
2998 An annotation used to override the JSON Schema for a type.
3000 This is useful when you want to set a JSON Schema for a type that don't produce any JSON Schemas by default
3001 (e.g. [`Callable`][collections.abc.Callable]).
3003 If `mode` is set this will only apply to that schema generation mode, allowing you to set different JSON Schemas for validation and serialization.
3005 !!! note
3006 If the `WithJsonSchema` annotation is coupled with the [`Field()`][pydantic.Field] function, the behavior overriding will vary depending on the location:
3008 * If the [`Annotated`][typing.Annotated] metadata is specified at the "top-level" field, `Field()` metadata arguments
3009 (excluding [constraints](../concepts/fields.md#field-constraints)) such as `title` and `description` will be applied on
3010 top of the `WithJsonSchema`, no matter the order:
3012 ```python
3013 from typing import Annotated
3015 from pydantic import BaseModel, Field, WithJsonSchema
3017 class Model(BaseModel):
3018 field: Annotated[
3019 int,
3020 Field(title='My Field'),
3021 WithJsonSchema({'type': 'integer', 'extra': 'data'}),
3022 ]
3024 Model.model_json_schema()['properties']['field']
3025 #> {'type': 'integer', 'extra': 'data', 'title': 'My Field'}
3026 ```
3028 * If the [`Annotated`][typing.Annotated] metadata is specified on a specific inner type, `WithJsonSchema` will unconditionally
3029 override the JSON Schema:
3031 ```python
3032 from typing import Annotated
3034 from pydantic import BaseModel, Field, WithJsonSchema
3036 class Model(BaseModel):
3037 field: list[
3038 Annotated[
3039 int,
3040 Field(title='My Field'),
3041 WithJsonSchema({'type': 'integer', 'extra': 'data'}),
3042 ]
3043 ]
3045 Model.model_json_schema()['properties']['field']
3046 #> {'items': {'extra': 'data', 'type': 'integer'}, 'title': 'Field', 'type': 'array'}
3047 ```
3049 See also the documentation about [the annotated pattern](../concepts/fields.md#the-annotated-pattern).
3050 """
3052 json_schema: JsonSchemaValue | None
3053 mode: Literal['validation', 'serialization'] | None = None
3055 def __get_pydantic_json_schema__(
3056 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
3057 ) -> JsonSchemaValue:
3058 if self.mode is not None and self.mode != handler.mode:
3059 return handler(core_schema)
3060 if self.json_schema is None:
3061 # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema
3062 raise PydanticOmit
3063 else:
3064 return self.json_schema.copy()
3066 def __hash__(self) -> int:
3067 return hash(self.mode)
3070class Examples:
3071 """Add examples to a JSON schema.
3073 If the JSON Schema already contains examples, the provided examples
3074 will be appended.
3076 If `mode` is set this will only apply to that schema generation mode,
3077 allowing you to add different examples for validation and serialization.
3078 """
3080 @overload
3081 @deprecated('Using a dict for `examples` is deprecated since v2.9 and will be removed in v3.0. Use a list instead.')
3082 def __init__(
3083 self, examples: dict[str, Any], mode: Literal['validation', 'serialization'] | None = None
3084 ) -> None: ...
3086 @overload
3087 def __init__(self, examples: list[Any], mode: Literal['validation', 'serialization'] | None = None) -> None: ...
3089 def __init__(
3090 self, examples: dict[str, Any] | list[Any], mode: Literal['validation', 'serialization'] | None = None
3091 ) -> None:
3092 if isinstance(examples, dict):
3093 warnings.warn(
3094 'Using a dict for `examples` is deprecated, use a list instead.',
3095 PydanticDeprecatedSince29,
3096 stacklevel=2,
3097 )
3098 self.examples = examples
3099 self.mode = mode
3101 def __get_pydantic_json_schema__(
3102 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
3103 ) -> JsonSchemaValue:
3104 mode = self.mode or handler.mode
3105 json_schema = handler(core_schema)
3106 if mode != handler.mode:
3107 return json_schema
3108 examples = json_schema.get('examples')
3109 if examples is None:
3110 json_schema['examples'] = to_jsonable_python(self.examples)
3111 if isinstance(examples, dict):
3112 if isinstance(self.examples, list):
3113 warnings.warn(
3114 'Updating existing JSON Schema examples of type dict with examples of type list. '
3115 'Only the existing examples values will be retained. Note that dict support for '
3116 'examples is deprecated and will be removed in v3.0.',
3117 UserWarning,
3118 )
3119 json_schema['examples'] = to_jsonable_python(
3120 [ex for value in examples.values() for ex in value] + self.examples
3121 )
3122 else:
3123 json_schema['examples'] = to_jsonable_python({**examples, **self.examples})
3124 if isinstance(examples, list):
3125 if isinstance(self.examples, list):
3126 json_schema['examples'] = to_jsonable_python(examples + self.examples)
3127 elif isinstance(self.examples, dict):
3128 warnings.warn(
3129 'Updating existing JSON Schema examples of type list with examples of type dict. '
3130 'Only the examples values will be retained. Note that dict support for '
3131 'examples is deprecated and will be removed in v3.0.',
3132 UserWarning,
3133 )
3134 json_schema['examples'] = to_jsonable_python(
3135 examples + [ex for value in self.examples.values() for ex in value]
3136 )
3138 return json_schema
3140 def __hash__(self) -> int:
3141 return hash(self.mode)
3144def _get_all_json_refs(item: Any) -> set[JsonRef]:
3145 """Get all the definitions references from a JSON schema."""
3146 refs: set[JsonRef] = set()
3147 stack = [item]
3149 while stack:
3150 current = stack.pop()
3151 if isinstance(current, dict):
3152 for key, value in current.items():
3153 if key == 'examples' and isinstance(value, list):
3154 # Skip examples that may contain arbitrary values and references
3155 # (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
3156 # of type list is necessary to avoid skipping valid portions of the schema,
3157 # for instance when "examples" is used as a property key. A more robust solution
3158 # could be found, but would require more advanced JSON Schema parsing logic.
3159 continue
3160 if key == '$ref' and isinstance(value, str):
3161 refs.add(JsonRef(value))
3162 elif isinstance(value, dict):
3163 stack.append(value)
3164 elif isinstance(value, list):
3165 stack.extend(value)
3166 elif isinstance(current, list):
3167 stack.extend(current)
3169 return refs
3172AnyType = TypeVar('AnyType')
3174if TYPE_CHECKING:
3175 SkipJsonSchema = Annotated[AnyType, ...]
3176else:
3178 @dataclasses.dataclass(slots=True)
3179 class SkipJsonSchema:
3180 """!!! abstract "Usage Documentation"
3181 [`SkipJsonSchema` Annotation](../concepts/json_schema.md#skipjsonschema-annotation)
3183 Add this as an annotation on a field to skip generating a JSON schema for that field.
3185 Example:
3186 ```python
3187 from pprint import pprint
3189 from pydantic import BaseModel
3190 from pydantic.json_schema import SkipJsonSchema
3192 class Model(BaseModel):
3193 a: int | None = None # (1)!
3194 b: int | SkipJsonSchema[None] = None # (2)!
3195 c: SkipJsonSchema[int | None] = None # (3)!
3197 pprint(Model.model_json_schema())
3198 '''
3199 {
3200 'properties': {
3201 'a': {
3202 'anyOf': [
3203 {'type': 'integer'},
3204 {'type': 'null'}
3205 ],
3206 'default': None,
3207 'title': 'A'
3208 },
3209 'b': {
3210 'default': None,
3211 'title': 'B',
3212 'type': 'integer'
3213 }
3214 },
3215 'title': 'Model',
3216 'type': 'object'
3217 }
3218 '''
3219 ```
3221 1. The integer and null types are both included in the schema for `a`.
3222 2. The integer type is the only type included in the schema for `b`.
3223 3. The entirety of the `c` field is omitted from the schema.
3224 """
3226 def __class_getitem__(cls, item: AnyType) -> AnyType:
3227 return Annotated[item, cls()]
3229 def __get_pydantic_json_schema__(
3230 self, core_schema: CoreSchema, handler: GetJsonSchemaHandler
3231 ) -> JsonSchemaValue:
3232 raise PydanticOmit
3234 def __hash__(self) -> int:
3235 return hash(type(self))
3238def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict | None:
3239 # If typed dictionary doesn't have config, the parent's config is used (as during core schema generation),
3240 # hence a default of `None`:
3241 if cls is not None:
3242 try:
3243 return _decorators.get_attribute_from_bases(cls, '__pydantic_config__')
3244 except AttributeError:
3245 pass
3246 return None
3249def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:
3250 """Get a `'function-plain'` serialization schema that can be used to serialize a default value.
3252 This takes into account having the serialization schema nested under validation schema(s).
3253 """
3254 if (
3255 (ser_schema := schema.get('serialization'))
3256 and ser_schema['type'] == 'function-plain'
3257 and not ser_schema.get('info_arg')
3258 ):
3259 return cast('core_schema.PlainSerializerFunctionSerSchema', ser_schema)
3260 if _core_utils.is_function_with_inner_schema(schema):
3261 return _get_ser_schema_for_default_value(schema['schema'])