Coverage for pydantic / json_schema.py: 92.06%
1299 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-21 11:56 +0000
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 1jlmeabnqrifgskophcd
14import collections.abc 1jlmeabnqrifgskophcd
15import dataclasses 1jlmeabnqrifgskophcd
16import inspect 1jlmeabnqrifgskophcd
17import math 1jlmeabnqrifgskophcd
18import os 1jlmeabnqrifgskophcd
19import re 1jlmeabnqrifgskophcd
20import warnings 1jlmeabnqrifgskophcd
21from collections import Counter, defaultdict 1jlmeabnqrifgskophcd
22from collections.abc import Callable, Hashable, Iterable, Sequence 1jlmeabnqrifgskophcd
23from copy import deepcopy 1jlmeabnqrifgskophcd
24from enum import Enum 1jlmeabnqrifgskophcd
25from re import Pattern 1jlmeabnqrifgskophcd
26from typing import ( 1jlmeabnqrifgskophcd
27 TYPE_CHECKING,
28 Annotated,
29 Any,
30 Literal,
31 NewType,
32 TypeAlias,
33 TypeVar,
34 assert_never,
35 cast,
36)
38import pydantic_core 1jlmeabnqrifgskophcd
39from pydantic_core import MISSING, CoreSchema, PydanticOmit, core_schema, to_jsonable_python 1jlmeabnqrifgskophcd
40from pydantic_core.core_schema import ComputedField 1jlmeabnqrifgskophcd
41from typing_inspection.introspection import get_literal_values 1jlmeabnqrifgskophcd
43from ._internal import ( 1jlmeabnqrifgskophcd
44 _config,
45 _core_metadata,
46 _core_utils,
47 _decorators,
48 _mock_val_ser,
49 _schema_generation_shared,
50 _typing_extra,
51)
52from .annotated_handlers import GetJsonSchemaHandler 1jlmeabnqrifgskophcd
53from .config import JsonDict, JsonValue 1jlmeabnqrifgskophcd
54from .errors import PydanticInvalidForJsonSchema, PydanticUserError 1jlmeabnqrifgskophcd
56if TYPE_CHECKING: 1jlmeabnqrifgskophcd
57 from . import ConfigDict
58 from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField
59 from ._internal._dataclasses import PydanticDataclass
60 from ._internal._schema_generation_shared import GetJsonSchemaFunction
61 from .main import BaseModel
64CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType] 1jlmeabnqrifgskophcd
65""" 1jlmeabnqrifgskophcd
66A type alias for defined schema types that represents a union of
67`core_schema.CoreSchemaType` and
68`core_schema.CoreSchemaFieldType`.
69"""
71JsonSchemaValue = dict[str, Any] 1jlmeabnqrifgskophcd
72""" 1jlmeabnqrifgskophcd
73A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.
74"""
76JsonSchemaMode = Literal['validation', 'serialization'] 1jlmeabnqrifgskophcd
77""" 1jlmeabnqrifgskophcd
78A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'.
80For some types, the inputs to validation differ from the outputs of serialization. For example,
81computed fields will only be present when serializing, and should not be provided when
82validating. This flag provides a way to indicate whether you want the JSON schema required
83for validation inputs, or that will be matched by serialization outputs.
84"""
86_MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'} 1jlmeabnqrifgskophcd
89JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator'] 1jlmeabnqrifgskophcd
90""" 1jlmeabnqrifgskophcd
91A type alias representing the kinds of warnings that can be emitted during JSON schema generation.
93See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
94for more details.
95"""
98class PydanticJsonSchemaWarning(UserWarning): 1jlmeabnqrifgskophcd
99 """This class is used to emit warnings produced during JSON schema generation.
100 See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
101 [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
102 methods for more details; these can be overridden to control warning behavior.
103 """
106NoDefault = object() 1jlmeabnqrifgskophcd
107"""A sentinel value used to indicate that no default value should be used when generating a JSON Schema 1jlmeabnqrifgskophcd
108for a core schema with a default value.
109"""
112# ##### JSON Schema Generation #####
113DEFAULT_REF_TEMPLATE = '#/$defs/{model}' 1jlmeabnqrifgskophcd
114"""The default format string used to generate reference names.""" 1jlmeabnqrifgskophcd
116# There are three types of references relevant to building JSON schemas:
117# 1. core_schema "ref" values; these are not exposed as part of the JSON schema
118# * these might look like the fully qualified path of a model, its id, or something similar
119CoreRef = NewType('CoreRef', str) 1jlmeabnqrifgskophcd
120# 2. keys of the "definitions" object that will eventually go into the JSON schema
121# * by default, these look like "MyModel", though may change in the presence of collisions
122# * eventually, we may want to make it easier to modify the way these names are generated
123DefsRef = NewType('DefsRef', str) 1jlmeabnqrifgskophcd
124# 3. the values corresponding to the "$ref" key in the schema
125# * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"}
126JsonRef = NewType('JsonRef', str) 1jlmeabnqrifgskophcd
128CoreModeRef = tuple[CoreRef, JsonSchemaMode] 1jlmeabnqrifgskophcd
129JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable) 1jlmeabnqrifgskophcd
131_PRIMITIVE_JSON_SCHEMA_TYPES = ('string', 'boolean', 'null', 'integer', 'number') 1jlmeabnqrifgskophcd
134@dataclasses.dataclass(slots=True) 1jlmeabnqrifgskophcd
135class _DefinitionsRemapping: 1jlmeabnqrifgskophcd
136 defs_remapping: dict[DefsRef, DefsRef] 1jlmeabnqrifgskophcd
137 json_remapping: dict[JsonRef, JsonRef] 1jlmeabnqrifgskophcd
139 @staticmethod 1jlmeabnqrifgskophcd
140 def from_prioritized_choices( 1jlmeabnqrifgskophcd
141 prioritized_choices: dict[DefsRef, list[DefsRef]],
142 defs_to_json: dict[DefsRef, JsonRef],
143 definitions: dict[DefsRef, JsonSchemaValue],
144 ) -> _DefinitionsRemapping:
145 """
146 This function should produce a remapping that replaces complex DefsRef with the simpler ones from the
147 prioritized_choices such that applying the name remapping would result in an equivalent JSON schema.
148 """
149 # We need to iteratively simplify the definitions until we reach a fixed point.
150 # The reason for this is that outer definitions may reference inner definitions that get simplified
151 # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified
152 # the inner definitions.
153 copied_definitions = deepcopy(definitions) 1jlmeabnqrifgkophcd
154 definitions_schema = {'$defs': copied_definitions} 1jlmeabnqrifgkophcd
155 for _iter in range(100): # prevent an infinite loop in the case of a bug, 100 iterations should be enough 155 ↛ 190line 155 didn't jump to line 190 because the loop on line 155 didn't complete1jlmeabnqrifgkophcd
156 # For every possible remapped DefsRef, collect all schemas that DefsRef might be used for:
157 schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list) 1jlmeabnqrifgkophcd
158 for defs_ref in copied_definitions: 1jlmeabnqrifgkophcd
159 alternatives = prioritized_choices[defs_ref] 1jlmeabnqrifgkophcd
160 for alternative in alternatives: 1jlmeabnqrifgkophcd
161 schemas_for_alternatives[alternative].append(copied_definitions[defs_ref]) 1jlmeabnqrifgkophcd
163 # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef
164 # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef.
165 for defs_ref in schemas_for_alternatives: 1jlmeabnqrifgkophcd
166 if len(schemas_for_alternatives[defs_ref]) > 1: 1jlmeabnqrifgkophcd
167 schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref]) 1jlmeabnqrifgkophcd
169 # Build the remapping
170 defs_remapping: dict[DefsRef, DefsRef] = {} 1jlmeabnqrifgkophcd
171 json_remapping: dict[JsonRef, JsonRef] = {} 1jlmeabnqrifgkophcd
172 for original_defs_ref in definitions: 1jlmeabnqrifgkophcd
173 alternatives = prioritized_choices[original_defs_ref] 1jlmeabnqrifgkophcd
174 # Pick the first alternative that has only one schema, since that means there is no collision
175 remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1) 1jlmeabnqrifgkophcd
176 defs_remapping[original_defs_ref] = remapped_defs_ref 1jlmeabnqrifgkophcd
178 # Map all alternatives after the remapped one to the remapped one
179 # This ensures that intermediate simplifications are also remapped
180 remapped_index = alternatives.index(remapped_defs_ref) 1jlmeabnqrifgkophcd
181 for alt in alternatives[remapped_index:]: 1jlmeabnqrifgkophcd
182 json_remapping[defs_to_json[alt]] = defs_to_json[remapped_defs_ref] 1jlmeabnqrifgkophcd
183 remapping = _DefinitionsRemapping(defs_remapping, json_remapping) 1jlmeabnqrifgkophcd
184 new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions}) 1jlmeabnqrifgkophcd
185 if definitions_schema == new_definitions_schema: 1jlmeabnqrifgkophcd
186 # We've reached the fixed point
187 return remapping 1jlmeabnqrifgkophcd
188 definitions_schema = new_definitions_schema 1jlmeabnqrifgkophcd
190 raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions')
192 def remap_defs_ref(self, ref: DefsRef) -> DefsRef: 1jlmeabnqrifgskophcd
193 return self.defs_remapping.get(ref, ref) 1jlmeabnqrifgkophcd
195 def remap_json_ref(self, ref: JsonRef) -> JsonRef: 1jlmeabnqrifgskophcd
196 return self.json_remapping.get(ref, ref) 1jlmeabnqrifgkophcd
198 def remap_json_schema(self, schema: Any) -> Any: 1jlmeabnqrifgskophcd
199 """
200 Recursively update the JSON schema replacing all $refs
201 """
202 if isinstance(schema, str): 1jlmeabnqrifgkophcd
203 # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings
204 return self.remap_json_ref(JsonRef(schema)) 1jlmeabnqrifgkophcd
205 elif isinstance(schema, list): 1jlmeabnqrifgkophcd
206 return [self.remap_json_schema(item) for item in schema] 1jlmeabnqrifgkophcd
207 elif isinstance(schema, dict): 1jlmeabnqrifgkophcd
208 for key, value in schema.items(): 1jlmeabnqrifgkophcd
209 if key == '$ref' and isinstance(value, str): 1jlmeabnqrifgkophcd
210 schema['$ref'] = self.remap_json_ref(JsonRef(value)) 1jlmeabnqrifgkophcd
211 elif key == '$defs': 1jlmeabnqrifgkophcd
212 schema['$defs'] = { 1jlmeabnqrifgkophcd
213 self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
214 for key, value in schema['$defs'].items()
215 }
216 else:
217 schema[key] = self.remap_json_schema(value) 1jlmeabnqrifgkophcd
218 return schema 1jlmeabnqrifgkophcd
221class GenerateJsonSchema: 1jlmeabnqrifgskophcd
222 """!!! abstract "Usage Documentation"
223 [Customizing the JSON Schema Generation Process](../concepts/json_schema.md#customizing-the-json-schema-generation-process)
225 A class for generating JSON schemas.
227 This class generates JSON schemas based on configured parameters. The default schema dialect
228 is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema).
229 The class uses `by_alias` to configure how fields with
230 multiple names are handled and `ref_template` to format reference names.
232 Attributes:
233 schema_dialect: The JSON schema dialect used to generate the schema. See
234 [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4)
235 in the JSON Schema documentation for more information about dialects.
236 ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will
237 do nothing if its argument `kind` is in `ignored_warning_kinds`;
238 this value can be modified on subclasses to easily control which warnings are emitted.
239 by_alias: Whether to use field aliases when generating the schema.
240 ref_template: The format string used when generating reference names.
241 core_to_json_refs: A mapping of core refs to JSON refs.
242 core_to_defs_refs: A mapping of core refs to definition refs.
243 defs_to_core_refs: A mapping of definition refs to core refs.
244 json_to_defs_refs: A mapping of JSON refs to definition refs.
245 definitions: Definitions in the schema.
247 Args:
248 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
249 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
250 schemas). An explicit value takes precedence over the configuration.
251 ref_template: The format string to use when generating reference names.
252 union_format: The format to use when combining schemas from unions together. Can be one of:
254 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
255 keyword to combine schemas (the default).
256 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
257 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
258 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
259 `any_of`.
261 Raises:
262 JsonSchemaError: If the instance of the class is inadvertently reused after generating a schema.
263 """
265 schema_dialect = 'https://json-schema.org/draft/2020-12/schema' 1jlmeabnqrifgskophcd
267 # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`;
268 # this value can be modified on subclasses to easily control which warnings are emitted
269 ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'} 1jlmeabnqrifgskophcd
271 def __init__( 1jlmeabnqrifgskophcd
272 self,
273 by_alias: bool | None = None,
274 ref_template: str = DEFAULT_REF_TEMPLATE,
275 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
276 ) -> None:
277 # `None` means "not explicitly set": aliases are used, unless disabled by the config (e.g. `validate_by_alias`)
278 self._by_alias = by_alias 1jlmeabnqrifgkophcd
279 self.by_alias = by_alias is not False 1jlmeabnqrifgkophcd
280 self.ref_template = ref_template 1jlmeabnqrifgkophcd
281 self.union_format: Literal['any_of', 'primitive_type_array'] = union_format 1jlmeabnqrifgkophcd
283 self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {} 1jlmeabnqrifgkophcd
284 self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {} 1jlmeabnqrifgkophcd
285 self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {} 1jlmeabnqrifgkophcd
286 self.json_to_defs_refs: dict[JsonRef, DefsRef] = {} 1jlmeabnqrifgkophcd
288 self.definitions: dict[DefsRef, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
289 self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({})) 1jlmeabnqrifgkophcd
291 self._mode: JsonSchemaMode = 'validation' 1jlmeabnqrifgkophcd
293 # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
294 # alternatives, which are generally simpler, such as only including the class name.
295 # At the end of schema generation, we use these to produce a JSON schema with more human-readable
296 # definitions, which would also work better in a generated OpenAPI client, etc.
297 self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {} 1jlmeabnqrifgkophcd
298 self._collision_counter: dict[str, int] = defaultdict(int) 1jlmeabnqrifgkophcd
299 self._collision_index: dict[str, int] = {} 1jlmeabnqrifgkophcd
301 self._schema_type_to_method = self.build_schema_type_to_method() 1jlmeabnqrifgkophcd
303 # When we encounter definitions we need to try to build them immediately
304 # so that they are available schemas that reference them
305 # But it's possible that CoreSchema was never going to be used
306 # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
307 # the reference) so instead of failing altogether if we can't build a definition we
308 # store the error raised and re-throw it if we end up needing that def
309 self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {} 1jlmeabnqrifgkophcd
311 # This changes to True after generating a schema, to prevent issues caused by accidental reuse
312 # of a single instance of a schema generator
313 self._used = False 1jlmeabnqrifgkophcd
315 @property 1jlmeabnqrifgskophcd
316 def _config(self) -> _config.ConfigWrapper: 1jlmeabnqrifgskophcd
317 return self._config_wrapper_stack.tail 1jlmeabnqrifgkophcd
319 @property 1jlmeabnqrifgskophcd
320 def mode(self) -> JsonSchemaMode: 1jlmeabnqrifgskophcd
321 if self._config.json_schema_mode_override is not None: 1jlmeabnqrifgkophcd
322 return self._config.json_schema_mode_override 1jlmeabnqrifgkophcd
323 else:
324 return self._mode 1jlmeabnqrifgkophcd
326 def build_schema_type_to_method( 1jlmeabnqrifgskophcd
327 self,
328 ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
329 """Builds a dictionary mapping fields to methods for generating JSON schemas.
331 Returns:
332 A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method.
334 Raises:
335 TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type.
336 """
337 mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {} 1jlmeabnqrifgkophcd
338 core_schema_types: list[CoreSchemaOrFieldType] = list(get_literal_values(CoreSchemaOrFieldType)) 1jlmeabnqrifgkophcd
339 for key in core_schema_types: 1jlmeabnqrifgkophcd
340 method_name = f'{key.replace("-", "_")}_schema' 1jlmeabnqrifgkophcd
341 try: 1jlmeabnqrifgkophcd
342 mapping[key] = getattr(self, method_name) 1jlmeabnqrifgkophcd
343 except AttributeError as e: # pragma: no cover
344 if os.getenv('PYDANTIC_PRIVATE_ALLOW_UNHANDLED_SCHEMA_TYPES'):
345 continue
346 raise TypeError(
347 f'No method for generating JsonSchema for core_schema.type={key!r} '
348 f'(expected: {type(self).__name__}.{method_name})'
349 ) from e
350 return mapping 1jlmeabnqrifgkophcd
352 def generate_definitions( 1jlmeabnqrifgskophcd
353 self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
354 ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
355 """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a
356 mapping that links the input keys to the definition references.
358 Args:
359 inputs: A sequence of tuples, where:
361 - The first element is a JSON schema key type.
362 - The second element is the JSON mode: either 'validation' or 'serialization'.
363 - The third element is a core schema.
365 Returns:
366 A tuple where:
368 - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
369 whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
370 JsonRef references to definitions that are defined in the second returned element.)
371 - The second element is a dictionary whose keys are definition references for the JSON schemas
372 from the first returned element, and whose values are the actual JSON schema definitions.
374 Raises:
375 PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema.
376 """
377 if self._used: 1jlmeabnqrifgkophcd
378 raise PydanticUserError( 1jlmeabnqrifgkophcd
379 'This JSON schema generator has already been used to generate a JSON schema. '
380 f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
381 code='json-schema-already-used',
382 )
384 for _, mode, schema in inputs: 1jlmeabnqrifgkophcd
385 self._mode = mode 1jlmeabnqrifgkophcd
386 self.generate_inner(schema) 1jlmeabnqrifgkophcd
388 definitions_remapping = self._build_definitions_remapping() 1jlmeabnqrifgkophcd
390 json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {} 1jlmeabnqrifgkophcd
391 for key, mode, schema in inputs: 1jlmeabnqrifgkophcd
392 self._mode = mode 1jlmeabnqrifgkophcd
393 json_schema = self.generate_inner(schema) 1jlmeabnqrifgkophcd
394 json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema) 1jlmeabnqrifgkophcd
396 json_schema = {'$defs': self.definitions} 1jlmeabnqrifgkophcd
397 json_schema = definitions_remapping.remap_json_schema(json_schema) 1jlmeabnqrifgkophcd
398 self._used = True 1jlmeabnqrifgkophcd
399 return json_schemas_map, self.sort(json_schema['$defs']) # type: ignore 1jlmeabnqrifgkophcd
401 def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue: 1jlmeabnqrifgskophcd
402 """Generates a JSON schema for a specified schema in a specified mode.
404 Args:
405 schema: A Pydantic model.
406 mode: The mode in which to generate the schema. Defaults to 'validation'.
408 Returns:
409 A JSON schema representing the specified schema.
411 Raises:
412 PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema.
413 """
414 self._mode = mode 1jlmeabnqrifgkophcd
415 if self._used: 1jlmeabnqrifgkophcd
416 raise PydanticUserError( 1jlmeabnqrifgkophcd
417 'This JSON schema generator has already been used to generate a JSON schema. '
418 f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
419 code='json-schema-already-used',
420 )
422 json_schema: JsonSchemaValue = self.generate_inner(schema) 1jlmeabnqrifgkophcd
423 json_ref_counts = self.get_json_ref_counts(json_schema) 1jlmeabnqrifgkophcd
425 ref = cast(JsonRef, json_schema.get('$ref')) 1jlmeabnqrifgkophcd
426 while ref is not None: # may need to unpack multiple levels 1jlmeabnqrifgkophcd
427 ref_json_schema = self.get_schema_from_definitions(ref) 1jlmeabnqrifgkophcd
428 if json_ref_counts[ref] == 1 and ref_json_schema is not None and len(json_schema) == 1: 1jlmeabnqrifgkophcd
429 # "Unpack" the ref since this is the only reference and there are no sibling keys
430 json_schema = ref_json_schema.copy() # copy to prevent recursive dict reference 1jlmeabnqrifgkophcd
431 json_ref_counts[ref] -= 1 1jlmeabnqrifgkophcd
432 ref = cast(JsonRef, json_schema.get('$ref')) 1jlmeabnqrifgkophcd
433 ref = None 1jlmeabnqrifgkophcd
435 self._garbage_collect_definitions(json_schema) 1jlmeabnqrifgkophcd
436 definitions_remapping = self._build_definitions_remapping() 1jlmeabnqrifgkophcd
438 if self.definitions: 1jlmeabnqrifgkophcd
439 json_schema['$defs'] = self.definitions 1jlmeabnqrifgkophcd
441 json_schema = definitions_remapping.remap_json_schema(json_schema) 1jlmeabnqrifgkophcd
443 # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
444 # this method and adding the following line after a call to super().generate(schema):
445 # json_schema['$schema'] = self.schema_dialect
447 self._used = True 1jlmeabnqrifgkophcd
448 return self.sort(json_schema) 1jlmeabnqrifgkophcd
450 def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
451 """Generates a JSON schema for a given core schema.
453 Args:
454 schema: The given core schema.
456 Returns:
457 The generated JSON schema.
458 """
459 if schema['type'] in ('model', 'dataclass', 'typed-dict'): 1jlmeabnqrifgkophcd
460 # The class config (and in particular `json_schema_mode_override`) must be pushed *before*
461 # the definitions cache lookup, so that the JSON Schema is cached under the mode it was generated with:
462 with self._config_wrapper_stack.push(_get_class_config(schema)): # pyright: ignore[reportArgumentType] 1jlmeabnqrifgkophcd
463 return self._generate_inner(schema) 1jlmeabnqrifgkophcd
464 return self._generate_inner(schema) 1jlmeabnqrifgkophcd
466 def _generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: # noqa: C901 1jlmeabnqrifgskophcd
467 """TODO: the nested function definitions here seem like bad practice, I'd like to unpack these
468 in a future PR. It'd be great if we could shorten the call stack a bit for JSON schema generation,
469 and I think there's potential for that here.
470 """
471 # If a schema with the same CoreRef has been handled, just return a reference to it
472 # Note that this assumes that it will _never_ be the case that the same CoreRef is used
473 # on types that should have different JSON schemas
474 if 'ref' in schema: 1jlmeabnqrifgkophcd
475 core_ref = CoreRef(schema['ref']) # type: ignore[typeddict-item] 1jlmeabnqrifgkophcd
476 core_mode_ref = (core_ref, self.mode) 1jlmeabnqrifgkophcd
477 if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions: 1jlmeabnqrifgkophcd
478 return {'$ref': self.core_to_json_refs[core_mode_ref]} 1jlmeabnqrifgkophcd
480 def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue: 1jlmeabnqrifgkophcd
481 if 'ref' in core_schema: 1jlmeabnqrifgkophcd
482 core_ref = CoreRef(core_schema['ref']) # type: ignore[typeddict-item] 1jlmeabnqrifgkophcd
483 defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref) 1jlmeabnqrifgkophcd
484 json_ref = JsonRef(ref_json_schema['$ref']) 1jlmeabnqrifgkophcd
485 # Replace the schema if it's not a reference to itself
486 # What we want to avoid is having the def be just a ref to itself
487 # which is what would happen if we blindly assigned any
488 if json_schema.get('$ref', None) != json_ref: 488 ↛ 491line 488 didn't jump to line 491 because the condition on line 488 was always true1jlmeabnqrifgkophcd
489 self.definitions[defs_ref] = json_schema 1jlmeabnqrifgkophcd
490 self._core_defs_invalid_for_json_schema.pop(defs_ref, None) 1jlmeabnqrifgkophcd
491 json_schema = ref_json_schema 1jlmeabnqrifgkophcd
492 return json_schema 1jlmeabnqrifgkophcd
494 def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue: 1jlmeabnqrifgkophcd
495 """Generate a JSON schema based on the input schema.
497 Args:
498 schema_or_field: The core schema to generate a JSON schema from.
500 Returns:
501 The generated JSON schema.
503 Raises:
504 TypeError: If an unexpected schema type is encountered.
505 """
506 # Generate the core-schema-type-specific bits of the schema generation:
507 json_schema: JsonSchemaValue | None = None 1jlmeabnqrifgkophcd
508 if self.mode == 'serialization' and 'serialization' in schema_or_field: 1jlmeabnqrifgkophcd
509 # In this case, we skip the JSON Schema generation of the schema
510 # and use the `'serialization'` schema instead (canonical example:
511 # `Annotated[int, PlainSerializer(str)]`).
512 ser_schema = schema_or_field['serialization'] # type: ignore 1jlmeabnqrifgkophcd
513 json_schema = self.ser_schema(ser_schema) 1jlmeabnqrifgkophcd
515 # It might be that the 'serialization'` is skipped depending on `when_used`.
516 # This is only relevant for `nullable` schemas though (possibly wrapped, e.g. when
517 # using a field serializer on a field with a default value), so we special case here.
518 if ( 1eabifghcd
519 json_schema is not None
520 and ser_schema.get('when_used') in ('unless-none', 'json-unless-none')
521 and _is_nullable_schema(schema_or_field)
522 ):
523 json_schema = self.get_union_of_schemas([{'type': 'null'}, json_schema]) 1jlmeabnqrifgkophcd
524 if json_schema is None: 1jlmeabnqrifgkophcd
525 if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field): 525 ↛ 529line 525 didn't jump to line 529 because the condition on line 525 was always true1jlmeabnqrifgkophcd
526 generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']] 1jlmeabnqrifgkophcd
527 json_schema = generate_for_schema_type(schema_or_field) 1jlmeabnqrifgkophcd
528 else:
529 raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
530 return json_schema 1jlmeabnqrifgkophcd
532 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func) 1jlmeabnqrifgkophcd
534 metadata = cast(_core_metadata.CoreMetadata, schema.get('metadata', {})) 1jlmeabnqrifgkophcd
536 # TODO: I dislike that we have to wrap these basic dict updates in callables, is there any way around this?
538 if js_updates := metadata.get('pydantic_js_updates'): 1jlmeabnqrifgkophcd
540 def js_updates_handler_func( 1jlmeabnqrifgkophcd
541 schema_or_field: CoreSchemaOrField,
542 current_handler: GetJsonSchemaHandler = current_handler,
543 ) -> JsonSchemaValue:
544 json_schema = {**current_handler(schema_or_field), **js_updates} 1jlmeabnqrifgkophcd
545 return json_schema 1jlmeabnqrifgkophcd
547 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_updates_handler_func) 1jlmeabnqrifgkophcd
549 if js_extra := metadata.get('pydantic_js_extra'): 1jlmeabnqrifgkophcd
551 def js_extra_handler_func( 1jlmeabnqrifgkophcd
552 schema_or_field: CoreSchemaOrField,
553 current_handler: GetJsonSchemaHandler = current_handler,
554 ) -> JsonSchemaValue:
555 json_schema = current_handler(schema_or_field) 1jlmeabnqrifgkophcd
556 if isinstance(js_extra, dict): 1jlmeabnqrifgkophcd
557 json_schema.update(to_jsonable_python(js_extra)) 1jlmeabnqrifgkophcd
558 elif callable(js_extra): 558 ↛ 561line 558 didn't jump to line 561 because the condition on line 558 was always true1jlmeabnqrifgkophcd
559 # similar to typing issue in _update_class_schema when we're working with callable js extra
560 js_extra(json_schema) # type: ignore 1jlmeabnqrifgkophcd
561 return json_schema 1jlmeabnqrifgkophcd
563 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_extra_handler_func) 1jlmeabnqrifgkophcd
565 for js_modify_function in metadata.get('pydantic_js_functions', ()): 1jlmeabnqrifgkophcd
567 def new_handler_func( 1jlmeabnqrifgkophcd
568 schema_or_field: CoreSchemaOrField,
569 current_handler: GetJsonSchemaHandler = current_handler,
570 js_modify_function: GetJsonSchemaFunction = js_modify_function,
571 ) -> JsonSchemaValue:
572 json_schema = js_modify_function(schema_or_field, current_handler) 1jlmeabnqrifgkophcd
573 if _core_utils.is_core_schema(schema_or_field): 573 ↛ 575line 573 didn't jump to line 575 because the condition on line 573 was always true1jlmeabnqrifgkophcd
574 json_schema = populate_defs(schema_or_field, json_schema) 1jlmeabnqrifgkophcd
575 original_schema = current_handler.resolve_ref_schema(json_schema) 1jlmeabnqrifgkophcd
576 ref = json_schema.pop('$ref', None) 1jlmeabnqrifgkophcd
577 if ref and json_schema: 577 ↛ 578line 577 didn't jump to line 578 because the condition on line 577 was never true1jlmeabnqrifgkophcd
578 original_schema.update(json_schema)
579 return original_schema 1jlmeabnqrifgkophcd
581 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func) 1jlmeabnqrifgkophcd
583 for js_modify_function in metadata.get('pydantic_js_annotation_functions', ()): 1jlmeabnqrifgkophcd
585 def new_handler_func( 1jlmeabnqrifgkophcd
586 schema_or_field: CoreSchemaOrField,
587 current_handler: GetJsonSchemaHandler = current_handler,
588 js_modify_function: GetJsonSchemaFunction = js_modify_function,
589 ) -> JsonSchemaValue:
590 return js_modify_function(schema_or_field, current_handler) 1jlmeabnqrifgkophcd
592 current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func) 1jlmeabnqrifgkophcd
594 json_schema = current_handler(schema) 1jlmeabnqrifgkophcd
595 if _core_utils.is_core_schema(schema): 1jlmeabnqrifgkophcd
596 json_schema = populate_defs(schema, json_schema) 1jlmeabnqrifgkophcd
597 return json_schema 1jlmeabnqrifgkophcd
599 def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
600 """Override this method to customize the sorting of the JSON schema (e.g., don't sort at all, sort all keys unconditionally, etc.)
602 By default, alphabetically sort the keys in the JSON schema, skipping the 'properties' and 'default' keys to preserve field definition order.
603 This sort is recursive, so it will sort all nested dictionaries as well.
604 """
605 sorted_dict: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
606 keys = value.keys() 1jlmeabnqrifgkophcd
607 if parent_key not in ('properties', 'default'): 607 ↛ 609line 607 didn't jump to line 609 because the condition on line 607 was always true1jlmeabnqrifgkophcd
608 keys = sorted(keys) 1jlmeabnqrifgkophcd
609 for key in keys: 1jlmeabnqrifgkophcd
610 sorted_dict[key] = self._sort_recursive(value[key], parent_key=key) 1jlmeabnqrifgkophcd
611 return sorted_dict 1jlmeabnqrifgkophcd
613 def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any: 1jlmeabnqrifgskophcd
614 """Recursively sort a JSON schema value."""
615 if isinstance(value, dict): 1jlmeabnqrifgkophcd
616 sorted_dict: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
617 keys = value.keys() 1jlmeabnqrifgkophcd
618 if parent_key not in ('properties', 'default'): 1jlmeabnqrifgkophcd
619 keys = sorted(keys) 1jlmeabnqrifgkophcd
620 for key in keys: 1jlmeabnqrifgkophcd
621 sorted_dict[key] = self._sort_recursive(value[key], parent_key=key) 1jlmeabnqrifgkophcd
622 return sorted_dict 1jlmeabnqrifgkophcd
623 elif isinstance(value, list): 1jlmeabnqrifgkophcd
624 sorted_list: list[JsonSchemaValue] = [self._sort_recursive(item, parent_key) for item in value] 1jlmeabnqrifgkophcd
625 return sorted_list 1jlmeabnqrifgkophcd
626 else:
627 return value 1jlmeabnqrifgkophcd
629 # ### Schema generation methods
631 def invalid_schema(self, schema: core_schema.InvalidSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
632 """Placeholder - should never be called."""
634 raise RuntimeError('Cannot generate schema for invalid_schema. This is a bug! Please report it.')
636 def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
637 """Generates a JSON schema that matches any value.
639 Args:
640 schema: The core schema.
642 Returns:
643 The generated JSON schema.
644 """
645 return {} 1jlmeabnqrifgkophcd
647 def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
648 """Generates a JSON schema that matches `None`.
650 Args:
651 schema: The core schema.
653 Returns:
654 The generated JSON schema.
655 """
656 return {'type': 'null'} 1jlmeabnqrifgkophcd
658 def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
659 """Generates a JSON schema that matches a bool value.
661 Args:
662 schema: The core schema.
664 Returns:
665 The generated JSON schema.
666 """
667 return {'type': 'boolean'} 1jlmeabnqrifgkophcd
669 def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
670 """Generates a JSON schema that matches an int value.
672 Args:
673 schema: The core schema.
675 Returns:
676 The generated JSON schema.
677 """
678 json_schema: dict[str, Any] = {'type': 'integer'} 1jlmeabnqrifgkophcd
679 self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric) 1jlmeabnqrifgkophcd
680 json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}} 1jlmeabnqrifgkophcd
681 return json_schema 1jlmeabnqrifgkophcd
683 def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
684 """Generates a JSON schema that matches a float value.
686 Args:
687 schema: The core schema.
689 Returns:
690 The generated JSON schema.
691 """
692 json_schema: dict[str, Any] = {'type': 'number'} 1jlmeabnqrifgkophcd
693 self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric) 1jlmeabnqrifgkophcd
694 json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}} 1jlmeabnqrifgkophcd
695 return json_schema 1jlmeabnqrifgkophcd
697 def fraction_schema(self, schema: core_schema.FractionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
698 """Generates a JSON schema that matches a fraction value.
700 Args:
701 schema: The core schema.
703 Returns:
704 The generated JSON schema.
706 """
707 json_schema: JsonSchemaValue = {'type': 'string', 'format': 'fraction'} 1jlmeabnqrifgkophcd
708 if self.mode == 'validation': 1jlmeabnqrifgkophcd
709 le = schema.get('le') 1jlmeabnqrifgkophcd
710 ge = schema.get('ge') 1jlmeabnqrifgkophcd
711 lt = schema.get('lt') 1jlmeabnqrifgkophcd
712 gt = schema.get('gt') 1jlmeabnqrifgkophcd
713 json_schema = { 1jlmeabnqrifgkophcd
714 'anyOf': [
715 self.float_schema(
716 core_schema.float_schema(
717 le=None if le is None else float(le),
718 ge=None if ge is None else float(ge),
719 lt=None if lt is None else float(lt),
720 gt=None if gt is None else float(gt),
721 )
722 ),
723 json_schema,
724 ],
725 }
726 return json_schema 1jlmeabnqrifgkophcd
728 def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
729 """Generates a JSON schema that matches a decimal value.
731 Args:
732 schema: The core schema.
734 Returns:
735 The generated JSON schema.
736 """
737 json_schema: JsonSchemaValue = {'type': 'string'} 1jlmeabnqrifgkophcd
738 pattern = self.get_decimal_pattern(schema) 1jlmeabnqrifgkophcd
739 if pattern is not None: 1jlmeabnqrifgkophcd
740 json_schema['pattern'] = pattern 1jlmeabnqrifgkophcd
741 if self.mode == 'validation': 1jlmeabnqrifgkophcd
742 multiple_of = schema.get('multiple_of') 1jlmeabnqrifgkophcd
743 le = schema.get('le') 1jlmeabnqrifgkophcd
744 ge = schema.get('ge') 1jlmeabnqrifgkophcd
745 lt = schema.get('lt') 1jlmeabnqrifgkophcd
746 gt = schema.get('gt') 1jlmeabnqrifgkophcd
747 json_schema = { 1jlmeabnqrifgkophcd
748 'anyOf': [
749 self.float_schema(
750 core_schema.float_schema(
751 allow_inf_nan=schema.get('allow_inf_nan'),
752 multiple_of=None if multiple_of is None else float(multiple_of),
753 le=None if le is None else float(le),
754 ge=None if ge is None else float(ge),
755 lt=None if lt is None else float(lt),
756 gt=None if gt is None else float(gt),
757 )
758 ),
759 json_schema,
760 ],
761 }
762 return json_schema 1jlmeabnqrifgkophcd
764 def get_decimal_pattern(self, schema: core_schema.DecimalSchema) -> str | None: 1jlmeabnqrifgskophcd
765 """Get the regular expression pattern to apply to the string representation of a decimal.
767 By default, no pattern is applied (`None` is returned). Subclasses can override this method
768 to return a custom pattern, or [`build_decimal_pattern()`][pydantic.json_schema.GenerateJsonSchema.build_decimal_pattern]
769 can be used to get a pattern reflecting the `max_digits` and `decimal_places` constraints:
771 ```python
772 from pydantic.json_schema import GenerateJsonSchema
774 class MyGenerateJsonSchema(GenerateJsonSchema):
775 def get_decimal_pattern(self, schema):
776 return self.build_decimal_pattern(schema)
777 ```
779 Args:
780 schema: The core schema.
782 Returns:
783 The regular expression pattern, or `None` if no pattern should be applied.
784 """
785 return None 1jlmeabnqrifgkophcd
787 def build_decimal_pattern(self, schema: core_schema.DecimalSchema) -> str: 1jlmeabnqrifgskophcd
788 """Build a regular expression pattern for the string representation of a decimal.
790 The pattern takes into account the `max_digits` and `decimal_places` constraints, and the current
791 mode:
793 - In `'validation'` mode, the pattern accepts the string syntax understood by the [`Decimal`][decimal.Decimal]
794 constructor. The `max_digits` and `decimal_places` constraints are only reflected for strings
795 *without* an exponent: strings using an exponent are accepted as long as they are syntactically valid,
796 as the constraints can't be expressed with a regular expression in this case.
797 - In `'serialization'` mode, the pattern exactly describes the strings produced by pydantic
798 (i.e. by `str(decimal)`) for decimals satisfying the constraints,
799 including the ones using scientific notation (e.g. `'1E-7'`, `'1.5E+3'`).
801 In both modes, trailing zeros in the decimal part are not counted (e.g. `'1.10'` is accepted with
802 `decimal_places=1`), consistent with the validation behavior. If `allow_inf_nan` is enabled (on the
803 core schema or in the configuration), the string representations of infinity and NaN are also accepted.
805 Args:
806 schema: The core schema.
808 Returns:
809 The regular expression pattern.
810 """
811 max_digits = schema.get('max_digits') 1jlmeabnqrifgkophcd
812 decimal_places = schema.get('decimal_places') 1jlmeabnqrifgkophcd
813 allow_inf_nan = schema.get('allow_inf_nan') 1jlmeabnqrifgkophcd
814 if allow_inf_nan is None: 1jlmeabnqrifgkophcd
815 allow_inf_nan = self._config.config_dict.get('allow_inf_nan', False) 1jlmeabnqrifgkophcd
816 if self.mode == 'validation': 1jlmeabnqrifgkophcd
817 return _decimal_validation_pattern(max_digits, decimal_places, allow_inf_nan) 1jlmeabnqrifgkophcd
818 else:
819 return _decimal_serialization_pattern(max_digits, decimal_places, allow_inf_nan) 1jlmeabnqrifgkophcd
821 def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
822 """Generates a JSON schema that matches a string value.
824 Args:
825 schema: The core schema.
827 Returns:
828 The generated JSON schema.
829 """
830 json_schema: JsonSchemaValue = {'type': 'string'} 1jlmeabnqrifgkophcd
831 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) 1jlmeabnqrifgkophcd
832 if 'minLength' not in json_schema and self._config.str_min_length: 1jlmeabnqrifgkophcd
833 json_schema['minLength'] = self._config.str_min_length 1jlmeabnqrifgkophcd
834 if 'maxLength' not in json_schema and self._config.str_max_length is not None: 1jlmeabnqrifgkophcd
835 json_schema['maxLength'] = self._config.str_max_length 1jlmeabnqrifgkophcd
836 if isinstance(json_schema.get('pattern'), Pattern): 1jlmeabnqrifgkophcd
837 # TODO: should we add regex flags to the pattern?
838 json_schema['pattern'] = json_schema.get('pattern').pattern # type: ignore 1jlmeabnqrifgkophcd
839 return json_schema 1jlmeabnqrifgkophcd
841 def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
842 """Generates a JSON schema that matches a bytes value.
844 Args:
845 schema: The core schema.
847 Returns:
848 The generated JSON schema.
849 """
850 json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'} 1jlmeabnqrifgkophcd
851 self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes) 1jlmeabnqrifgkophcd
852 return json_schema 1jlmeabnqrifgkophcd
854 def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
855 """Generates a JSON schema that matches a date value.
857 Args:
858 schema: The core schema.
860 Returns:
861 The generated JSON schema.
862 """
863 return self._common_temporal_schema('date', self._config.ser_json_temporal) 1jlmeabnqrifgkophcd
865 def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
866 """Generates a JSON schema that matches a time value.
868 Args:
869 schema: The core schema.
871 Returns:
872 The generated JSON schema.
873 """
874 return self._common_temporal_schema('time', self._config.ser_json_temporal) 1jlmeabnqrifgkophcd
876 def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
877 """Generates a JSON schema that matches a datetime value.
879 Args:
880 schema: The core schema.
882 Returns:
883 The generated JSON schema.
884 """
885 return self._common_temporal_schema('date-time', self._config.ser_json_temporal) 1jlmeabnqrifgkophcd
887 def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
888 """Generates a JSON schema that matches a timedelta value.
890 Args:
891 schema: The core schema.
893 Returns:
894 The generated JSON schema.
895 """
896 if 'ser_json_temporal' in self._config.config_dict: 1jlmeabnqrifgkophcd
897 temporal_format = self._config.ser_json_temporal 1jlmeabnqrifgkophcd
898 else:
899 # `ser_json_temporal` supersedes `ser_json_timedelta`, which only applies when the former isn't
900 # explicitly set.
901 temporal_format = 'seconds' if self._config.ser_json_timedelta == 'float' else 'iso8601' 1jlmeabnqrifgkophcd
902 return self._common_temporal_schema('duration', temporal_format) 1jlmeabnqrifgkophcd
904 def _common_temporal_schema( 1jlmeabnqrifgskophcd
905 self, format: str, temporal_format: Literal['iso8601', 'seconds', 'milliseconds']
906 ) -> JsonSchemaValue:
907 if self.mode == 'serialization' and temporal_format != 'iso8601': 1jlmeabnqrifgkophcd
908 # Both `'seconds'` and `'milliseconds'` serialize to a number:
909 return {'type': 'number'} 1jlmeabnqrifgkophcd
910 return {'type': 'string', 'format': format} 1jlmeabnqrifgkophcd
912 def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
913 """Generates a JSON schema that matches a literal value.
915 Args:
916 schema: The core schema.
918 Returns:
919 The generated JSON schema.
920 """
921 expected = [to_jsonable_python(v.value if isinstance(v, Enum) else v) for v in schema['expected']] 1jlmeabnqrifgkophcd
923 result: dict[str, Any] = {} 1jlmeabnqrifgkophcd
924 if len(expected) == 1: 1jlmeabnqrifgkophcd
925 result['const'] = expected[0] 1jlmeabnqrifgkophcd
926 else:
927 result['enum'] = expected 1jlmeabnqrifgkophcd
929 types = {type(e) for e in expected} 1jlmeabnqrifgkophcd
930 if types == {str}: 1jlmeabnqrifgkophcd
931 result['type'] = 'string' 1jlmeabnqrifgkophcd
932 elif types == {int}: 1jlmeabnqrifgkophcd
933 result['type'] = 'integer' 1jlmeabnqrifgkophcd
934 elif types == {float}: 1jlmeabnqrifgkophcd
935 result['type'] = 'number' 1jlmeabnqrifgkophcd
936 elif types == {bool}: 1jlmeabnqrifgkophcd
937 result['type'] = 'boolean' 1jlmeabnqrifgkophcd
938 elif types == {list}: 1jlmeabnqrifgkophcd
939 result['type'] = 'array' 1jlmeabnqrifgkophcd
940 elif types == {type(None)}: 1jlmeabnqrifgkophcd
941 result['type'] = 'null' 1jlmeabnqrifgkophcd
942 return result 1jlmeabnqrifgkophcd
944 def missing_sentinel_schema(self, schema: core_schema.MissingSentinelSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
945 """Generates a JSON schema that matches a schema that allows the `MISSING` sentinel value.
947 Args:
948 schema: The core schema.
950 Returns:
951 The generated JSON schema.
952 """
953 inner_schema = schema.get('schema') 1jlmeabnqrifgkophcd
954 if inner_schema is None: 1jlmeabnqrifgkophcd
955 raise PydanticOmit 1jlmeabnqrifgkophcd
956 return self.generate_inner(inner_schema) 1jlmeabnqrifgkophcd
958 def ellipsis_schema(self, schema: core_schema.EllipsisSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
959 """Handles JSON schema generation for a core schema that checks if a value is the [`Ellipsis`][] literal.
961 Unless overridden in a subclass, this raises an error.
963 Args:
964 schema: The core schema.
966 Returns:
967 The generated JSON schema.
968 """
969 return self.handle_invalid_for_json_schema(schema, 'core_schema.EllipsisSchema') 1jlmeabnqrifgkophcd
971 def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
972 """Generates a JSON schema that matches an Enum value.
974 Args:
975 schema: The core schema.
977 Returns:
978 The generated JSON schema.
979 """
980 enum_type = schema['cls'] 1jlmeabnqrifgkophcd
981 description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__) 1jlmeabnqrifgkophcd
982 if ( 982 ↛ 985line 982 didn't jump to line 985 because the condition on line 982 was never true1eabifghcd
983 description == 'An enumeration.'
984 ): # This is the default value provided by enum.EnumMeta.__new__; don't use it
985 description = None
986 result: dict[str, Any] = {'title': enum_type.__name__, 'description': description} 1jlmeabnqrifgkophcd
987 result = {k: v for k, v in result.items() if v is not None} 1jlmeabnqrifgkophcd
989 expected = [to_jsonable_python(v.value) for v in schema['members']] 1jlmeabnqrifgkophcd
991 result['enum'] = expected 1jlmeabnqrifgkophcd
993 types = {type(e) for e in expected} 1jlmeabnqrifgkophcd
994 if isinstance(enum_type, str) or types == {str}: 1jlmeabnqrifgkophcd
995 result['type'] = 'string' 1jlmeabnqrifgkophcd
996 elif isinstance(enum_type, int) or types == {int}: 1jlmeabnqrifgkophcd
997 result['type'] = 'integer' 1jlmeabnqrifgkophcd
998 elif isinstance(enum_type, float) or types == {float}: 1jlmeabnqrifgkophcd
999 result['type'] = 'number' 1jlmeabnqrifgkophcd
1000 elif types == {bool}: 1000 ↛ 1001line 1000 didn't jump to line 1001 because the condition on line 1000 was never true1jlmeabnqrifgkophcd
1001 result['type'] = 'boolean'
1002 elif types == {list}: 1jlmeabnqrifgkophcd
1003 result['type'] = 'array' 1jlmeabnqrifgkophcd
1005 return result 1jlmeabnqrifgkophcd
1007 def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1008 """Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
1010 Unless overridden in a subclass, this raises an error.
1012 Args:
1013 schema: The core schema.
1015 Returns:
1016 The generated JSON schema.
1017 """
1018 return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})') 1jlmeabnqrifgkophcd
1020 def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1021 """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
1023 For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
1025 Args:
1026 schema: The core schema.
1028 Returns:
1029 The generated JSON schema.
1030 """
1031 # Note: This is for compatibility with V1; you can override if you want different behavior.
1032 return {} 1jlmeabnqrifgkophcd
1034 def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1035 """Generates a JSON schema that matches a callable value.
1037 Unless overridden in a subclass, this raises an error.
1039 Args:
1040 schema: The core schema.
1042 Returns:
1043 The generated JSON schema.
1044 """
1045 return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema') 1jlmeabnqrifgkophcd
1047 def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1048 """Returns a schema that matches a list schema.
1050 Args:
1051 schema: The core schema.
1053 Returns:
1054 The generated JSON schema.
1055 """
1056 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) 1jlmeabnqrifgkophcd
1057 json_schema = {'type': 'array', 'items': items_schema} 1jlmeabnqrifgkophcd
1058 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) 1jlmeabnqrifgkophcd
1059 return json_schema 1jlmeabnqrifgkophcd
1061 def deque_schema(self, schema: core_schema.DequeSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1062 """Returns a schema that matches a deque schema.
1064 Args:
1065 schema: The core schema.
1067 Returns:
1068 The generated JSON schema.
1069 """
1070 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) 1jlmeabnqrifgkophcd
1071 json_schema = {'type': 'array', 'items': items_schema} 1jlmeabnqrifgkophcd
1072 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) 1jlmeabnqrifgkophcd
1073 return json_schema 1jlmeabnqrifgkophcd
1075 def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1076 """Generates a JSON schema that matches a tuple schema e.g. `tuple[int,
1077 str, bool]` or `tuple[int, ...]`.
1079 Args:
1080 schema: The core schema.
1082 Returns:
1083 The generated JSON schema.
1084 """
1085 json_schema: JsonSchemaValue = {'type': 'array'} 1jlmeabnqrifgkophcd
1086 if 'variadic_item_index' in schema: 1jlmeabnqrifgkophcd
1087 variadic_item_index = schema['variadic_item_index'] 1jlmeabnqrifgkophcd
1088 if variadic_item_index > 0: 1jlmeabnqrifgkophcd
1089 json_schema['minItems'] = variadic_item_index 1jlmeabnqrifgkophcd
1090 json_schema['prefixItems'] = [ 1jlmeabnqrifgkophcd
1091 self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
1092 ]
1093 if variadic_item_index + 1 == len(schema['items_schema']): 1093 ↛ 1100line 1093 didn't jump to line 1100 because the condition on line 1093 was always true1jlmeabnqrifgkophcd
1094 # if the variadic item is the last item, then represent it faithfully
1095 json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index]) 1jlmeabnqrifgkophcd
1096 else:
1097 # otherwise, 'items' represents the schema for the variadic
1098 # item plus the suffix, so just allow anything for simplicity
1099 # for now
1100 json_schema['items'] = True
1101 else:
1102 prefixItems = [self.generate_inner(item) for item in schema['items_schema']] 1jlmeabnqrifgkophcd
1103 if prefixItems: 1jlmeabnqrifgkophcd
1104 json_schema['prefixItems'] = prefixItems 1jlmeabnqrifgkophcd
1105 json_schema['minItems'] = len(prefixItems) 1jlmeabnqrifgkophcd
1106 json_schema['maxItems'] = len(prefixItems) 1jlmeabnqrifgkophcd
1107 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) 1jlmeabnqrifgkophcd
1108 return json_schema 1jlmeabnqrifgkophcd
1110 def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1111 """Generates a JSON schema that matches a set schema.
1113 Args:
1114 schema: The core schema.
1116 Returns:
1117 The generated JSON schema.
1118 """
1119 return self._common_set_schema(schema) 1jlmeabnqrifgkophcd
1121 def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1122 """Generates a JSON schema that matches a frozenset schema.
1124 Args:
1125 schema: The core schema.
1127 Returns:
1128 The generated JSON schema.
1129 """
1130 return self._common_set_schema(schema) 1jlmeabnqrifgkophcd
1132 def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1133 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) 1jlmeabnqrifgkophcd
1134 json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema} 1jlmeabnqrifgkophcd
1135 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) 1jlmeabnqrifgkophcd
1136 return json_schema 1jlmeabnqrifgkophcd
1138 def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1139 """Returns a JSON schema that represents the provided GeneratorSchema.
1141 Args:
1142 schema: The schema.
1144 Returns:
1145 The generated JSON schema.
1146 """
1147 items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) 1jlmeabnqrifgkophcd
1148 json_schema = {'type': 'array', 'items': items_schema} 1jlmeabnqrifgkophcd
1149 self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) 1jlmeabnqrifgkophcd
1150 return json_schema 1jlmeabnqrifgkophcd
1152 def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1153 """Generates a JSON schema that matches a dict schema.
1155 Args:
1156 schema: The core schema.
1158 Returns:
1159 The generated JSON schema.
1160 """
1161 return self._common_dict_schema(schema) 1jlmeabnqrifgkophcd
1163 def frozendict_schema(self, schema: core_schema.FrozenDictSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1164 """Generates a JSON schema that matches a frozendict schema.
1166 Args:
1167 schema: The core schema.
1169 Returns:
1170 The generated JSON schema.
1171 """
1172 return self._common_dict_schema(schema) 1abfgcd
1174 def ordered_dict_schema(self, schema: core_schema.OrderedDictSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1175 """Generates a JSON schema that matches an `OrderedDict` schema.
1177 Args:
1178 schema: The core schema.
1180 Returns:
1181 The generated JSON schema.
1182 """
1183 return self._common_dict_schema(schema) 1jlmeabnqrifgkophcd
1185 def counter_schema(self, schema: core_schema.CounterSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1186 """Generates a JSON schema that matches a `Counter` schema.
1188 Args:
1189 schema: The core schema.
1191 Returns:
1192 The generated JSON schema.
1193 """
1194 return self._common_dict_schema(schema) 1jlmeabnqrifgkophcd
1196 def _common_dict_schema( 1jlmeabnqrifgskophcd
1197 self,
1198 schema: core_schema.DictSchema
1199 | core_schema.FrozenDictSchema
1200 | core_schema.OrderedDictSchema
1201 | core_schema.CounterSchema,
1202 ) -> JsonSchemaValue:
1203 json_schema: JsonSchemaValue = {'type': 'object'} 1jlmeabnqrifgkophcd
1205 keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {} 1jlmeabnqrifgkophcd
1206 if '$ref' not in keys_schema: 1jlmeabnqrifgkophcd
1207 keys_pattern = keys_schema.pop('pattern', None) 1jlmeabnqrifgkophcd
1208 # Don't give a title to patternProperties/propertyNames:
1209 keys_schema.pop('title', None) 1jlmeabnqrifgkophcd
1210 else:
1211 # Here, we assume that if the keys schema is a definition reference,
1212 # it can't be a simple string core schema (and thus no pattern can exist).
1213 # However, this is only in practice (in theory, a definition reference core
1214 # schema could be generated for a simple string schema).
1215 # Note that we avoid calling `self.resolve_ref_schema`, as it might not exist yet.
1216 keys_pattern = None 1jlmeabnqrifgkophcd
1218 values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {} 1jlmeabnqrifgkophcd
1219 # don't give a title to additionalProperties:
1220 values_schema.pop('title', None) 1jlmeabnqrifgkophcd
1222 if values_schema or keys_pattern is not None: 1jlmeabnqrifgkophcd
1223 if keys_pattern is None: 1jlmeabnqrifgkophcd
1224 json_schema['additionalProperties'] = values_schema 1jlmeabnqrifgkophcd
1225 else:
1226 json_schema['patternProperties'] = {keys_pattern: values_schema} 1jlmeabnqrifgkophcd
1227 else: # for `dict[str, Any]`, we allow any key and any value, since `str` is the default key type
1228 json_schema['additionalProperties'] = True 1jlmeabnqrifgkophcd
1230 if ( 1eabifghcd
1231 # The len check indicates that constraints are probably present:
1232 (keys_schema.get('type') == 'string' and len(keys_schema) > 1)
1233 # If this is a definition reference schema, it most likely has constraints:
1234 or '$ref' in keys_schema
1235 ):
1236 keys_schema.pop('type', None) 1jlmeabnqrifgkophcd
1237 json_schema['propertyNames'] = keys_schema 1jlmeabnqrifgkophcd
1239 self.update_with_validations(json_schema, schema, self.ValidationsMapping.object) 1jlmeabnqrifgkophcd
1240 return json_schema 1jlmeabnqrifgkophcd
1242 def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1243 """Generates a JSON schema that matches a function-before schema.
1245 Args:
1246 schema: The core schema.
1248 Returns:
1249 The generated JSON schema.
1250 """
1251 if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')): 1jlmeabnqrifgkophcd
1252 return self.generate_inner(input_schema) 1jlmeabnqrifgkophcd
1254 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1256 def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1257 """Generates a JSON schema that matches a function-after schema.
1259 Args:
1260 schema: The core schema.
1262 Returns:
1263 The generated JSON schema.
1264 """
1265 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1267 def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1268 """Generates a JSON schema that matches a function-plain schema.
1270 Args:
1271 schema: The core schema.
1273 Returns:
1274 The generated JSON schema.
1275 """
1276 if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')): 1276 ↛ 1279line 1276 didn't jump to line 1279 because the condition on line 1276 was always true1jlmeabnqrifgkophcd
1277 return self.generate_inner(input_schema) 1jlmeabnqrifgkophcd
1279 return self.handle_invalid_for_json_schema(
1280 schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})'
1281 )
1283 def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1284 """Generates a JSON schema that matches a function-wrap 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')): 1jlmeabnqrifgkophcd
1293 return self.generate_inner(input_schema) 1jlmeabnqrifgkophcd
1295 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1297 def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1298 """Generates a JSON schema that matches a schema with a default value.
1300 Args:
1301 schema: The core schema.
1303 Returns:
1304 The generated JSON schema.
1305 """
1306 json_schema = self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1308 default = self.get_default_value(schema) 1jlmeabnqrifgkophcd
1309 if default is NoDefault or default is MISSING: 1jlmeabnqrifgkophcd
1310 return json_schema 1jlmeabnqrifgkophcd
1312 # we reflect the application of custom plain, no-info serializers to defaults for
1313 # JSON Schemas viewed in serialization mode:
1314 # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
1315 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1316 # `_get_ser_schema_for_default_value()` is used to unpack potentially nested validator schemas:
1317 ser_schema = _get_ser_schema_for_default_value(schema['schema']) 1jlmeabnqrifgkophcd
1318 if ( 1eabifghcd
1319 ser_schema is not None
1320 and (ser_func := ser_schema.get('function'))
1321 and not (default is None and ser_schema.get('when_used') in ('unless-none', 'json-unless-none'))
1322 ):
1323 try: 1jlmeabnqrifgkophcd
1324 default = ser_func(default) # type: ignore 1jlmeabnqrifgkophcd
1325 except Exception: 1jlmeabnqrifgkophcd
1326 # It might be that the provided default needs to be validated (read: parsed) first
1327 # (assuming `validate_default` is enabled). However, we can't perform
1328 # such validation during JSON Schema generation so we don't support
1329 # this pattern for now.
1330 # (One example is when using `foo: ByteSize = '1MB'`, which validates and
1331 # serializes as an int. In this case, `ser_func` is `int` and `int('1MB')` fails).
1332 self.emit_warning( 1jlmeabnqrifgkophcd
1333 'non-serializable-default',
1334 f'Unable to serialize value {default!r} with the plain serializer; excluding default from JSON schema',
1335 )
1336 return json_schema 1jlmeabnqrifgkophcd
1338 # Sort set/frozenset defaults to ensure deterministic JSON schema generation
1339 # We only sort if len > 1 because sets of size 0 or 1 are already deterministic
1340 if isinstance(default, collections.abc.Set) and len(default) > 1: 1jlmeabnqrifgkophcd
1341 try: 1jlmeabnqrifgkophcd
1342 default = sorted(default) 1jlmeabnqrifgkophcd
1343 except TypeError: # pragma: no cover
1344 # If items aren't comparable (e.g. mixed types), we can't sort them.
1345 pass
1347 try: 1jlmeabnqrifgkophcd
1348 encoded_default = self.encode_default(default) 1jlmeabnqrifgkophcd
1349 except pydantic_core.PydanticSerializationError: 1jlmeabnqrifgkophcd
1350 self.emit_warning( 1jlmeabnqrifgkophcd
1351 'non-serializable-default',
1352 f'Default value {default} is not JSON serializable; excluding default from JSON schema',
1353 )
1354 # Return the inner schema, as though there was no default
1355 return json_schema 1jlmeabnqrifgkophcd
1357 json_schema['default'] = encoded_default 1jlmeabnqrifgkophcd
1358 return json_schema 1jlmeabnqrifgkophcd
1360 def get_default_value(self, schema: core_schema.WithDefaultSchema) -> Any: 1jlmeabnqrifgskophcd
1361 """Get the default value to be used when generating a JSON Schema for a core schema with a default.
1363 The default implementation is to use the statically defined default value. This method can be overridden
1364 if you want to make use of the default factory.
1366 Args:
1367 schema: The `'with-default'` core schema.
1369 Returns:
1370 The default value to use, or [`NoDefault`][pydantic.json_schema.NoDefault] if no default
1371 value is available.
1372 """
1373 return schema.get('default', NoDefault) 1jlmeabnqrifgkophcd
1375 def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1376 """Generates a JSON schema that matches a schema that allows null values.
1378 Args:
1379 schema: The core schema.
1381 Returns:
1382 The generated JSON schema.
1383 """
1384 null_schema = {'type': 'null'} 1jlmeabnqrifgkophcd
1385 inner_json_schema = self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1387 if inner_json_schema == null_schema: 1jlmeabnqrifgkophcd
1388 return null_schema 1jlmeabnqrifgkophcd
1389 else:
1390 return self.get_union_of_schemas([inner_json_schema, null_schema]) 1jlmeabnqrifgkophcd
1392 def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1393 """Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
1395 Args:
1396 schema: The core schema.
1398 Returns:
1399 The generated JSON schema.
1400 """
1401 generated: list[JsonSchemaValue] = [] 1jlmeabnqrifgkophcd
1403 for choice in core_schema.iter_union_choices(schema): 1jlmeabnqrifgkophcd
1404 try: 1jlmeabnqrifgkophcd
1405 generated.append(self.generate_inner(choice)) 1jlmeabnqrifgkophcd
1406 except PydanticOmit: # noqa: PERF203 1jlmeabnqrifgkophcd
1407 continue 1jlmeabnqrifgkophcd
1408 except PydanticInvalidForJsonSchema as exc: 1jlmeabnqrifgkophcd
1409 self.emit_warning('skipped-choice', exc.message) 1jlmeabnqrifgkophcd
1410 if len(generated) == 1: 1jlmeabnqrifgkophcd
1411 return generated[0] 1jlmeabnqrifgkophcd
1412 return self.get_union_of_schemas(generated) 1jlmeabnqrifgkophcd
1414 def get_union_of_schemas(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1415 """Returns the JSON Schema representation for the union of the provided JSON Schemas.
1417 The result depends on the configured `'union_format'`.
1419 Args:
1420 schemas: The list of JSON Schemas to be included in the union.
1422 Returns:
1423 The JSON Schema representing the union of schemas.
1424 """
1425 if self.union_format == 'primitive_type_array': 1jlmeabnqrifgkophcd
1426 types: list[str] = [] 1jlmeabnqrifgkophcd
1427 for schema in schemas: 1jlmeabnqrifgkophcd
1428 schema_types: list[str] | str | None = schema.get('type') 1jlmeabnqrifgkophcd
1429 if schema_types is None: 1jlmeabnqrifgkophcd
1430 # No type, meaning it can be a ref or an empty schema.
1431 break 1jlmeabnqrifgkophcd
1432 if not isinstance(schema_types, list): 1432 ↛ 1434line 1432 didn't jump to line 1434 because the condition on line 1432 was always true1jlmeabnqrifgkophcd
1433 schema_types = [schema_types] 1jlmeabnqrifgkophcd
1434 if not all(t in _PRIMITIVE_JSON_SCHEMA_TYPES for t in schema_types): 1jlmeabnqrifgkophcd
1435 break 1jlmeabnqrifgkophcd
1436 if len(schema) != 1: 1jlmeabnqrifgkophcd
1437 # We only want to include types that don't have any constraints. For instance,
1438 # if `schemas = [{'type': 'string', 'maxLength': 3}, {'type': 'string', 'minLength': 5}]`,
1439 # we don't want to produce `{'type': 'string', 'maxLength': 3, 'minLength': 5}`.
1440 # Same if we have some metadata (e.g. `title`) on a specific union member, we want to preserve it.
1441 break 1jlmeabnqrifgkophcd
1443 types.extend(schema_types) 1jlmeabnqrifgkophcd
1444 else:
1445 # If we got there, all the schemas where valid to be used with the `'primitive_type_array` format
1446 return {'type': list(dict.fromkeys(types))} 1jlmeabnqrifgkophcd
1448 return self.get_flattened_anyof(schemas) 1jlmeabnqrifgkophcd
1450 def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1451 """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where
1452 the schemas are tagged with a discriminator field that indicates which schema should be used to validate
1453 the value.
1455 Args:
1456 schema: The core schema.
1458 Returns:
1459 The generated JSON schema.
1460 """
1461 generated: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
1462 for k, v in schema['choices'].items(): 1jlmeabnqrifgkophcd
1463 if isinstance(k, Enum): 1jlmeabnqrifgkophcd
1464 k = k.value 1jlmeabnqrifgkophcd
1465 elif isinstance(k, bool): 1jlmeabnqrifgkophcd
1466 # Use the JSON representation so that the discriminator mapping
1467 # can be matched against the serialized payload value
1468 k = 'true' if k else 'false' 1jlmeabnqrifgkophcd
1469 elif k is None: 1jlmeabnqrifgkophcd
1470 k = 'null' 1jlmeabnqrifgkophcd
1471 try: 1jlmeabnqrifgkophcd
1472 # Use str(k) since keys must be strings for json; while not technically correct,
1473 # it's the closest that can be represented in valid JSON
1474 generated[str(k)] = self.generate_inner(v).copy() 1jlmeabnqrifgkophcd
1475 except PydanticOmit:
1476 continue
1477 except PydanticInvalidForJsonSchema as exc:
1478 self.emit_warning('skipped-choice', exc.message)
1480 one_of_choices = _deduplicate_schemas(generated.values()) 1jlmeabnqrifgkophcd
1481 json_schema: JsonSchemaValue = {'oneOf': one_of_choices} 1jlmeabnqrifgkophcd
1483 # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
1484 openapi_discriminator = self._extract_discriminator(schema, one_of_choices) 1jlmeabnqrifgkophcd
1485 if openapi_discriminator is not None: 1485 ↛ 1491line 1485 didn't jump to line 1491 because the condition on line 1485 was always true1jlmeabnqrifgkophcd
1486 json_schema['discriminator'] = { 1jlmeabnqrifgkophcd
1487 'propertyName': openapi_discriminator,
1488 'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
1489 }
1491 return json_schema 1jlmeabnqrifgkophcd
1493 def _extract_discriminator( 1jlmeabnqrifgskophcd
1494 self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict]
1495 ) -> str | None:
1496 """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final
1497 schema."""
1498 openapi_discriminator: str | None = None 1jlmeabnqrifgkophcd
1500 if isinstance(schema['discriminator'], str): 1jlmeabnqrifgkophcd
1501 return schema['discriminator'] 1jlmeabnqrifgkophcd
1503 if isinstance(schema['discriminator'], list): 1503 ↛ 1536line 1503 didn't jump to line 1536 because the condition on line 1503 was always true1jlmeabnqrifgkophcd
1504 # If the discriminator is a single item list containing a string, that is equivalent to the string case
1505 if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str): 1505 ↛ 1506line 1505 didn't jump to line 1506 because the condition on line 1505 was never true1jlmeabnqrifgkophcd
1506 return schema['discriminator'][0]
1507 # When an alias is used that is different from the field name, the discriminator will be a list of single
1508 # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is
1509 # more than one possible attribute, and looks for whether a single alias choice is present as a documented
1510 # property on all choices. If so, that property will be used as the OpenAPI discriminator.
1511 for alias_path in schema['discriminator']: 1511 ↛ 1536line 1511 didn't jump to line 1536 because the loop on line 1511 didn't complete1jlmeabnqrifgkophcd
1512 if not isinstance(alias_path, list): 1512 ↛ 1513line 1512 didn't jump to line 1513 because the condition on line 1512 was never true1jlmeabnqrifgkophcd
1513 break # this means that the discriminator is not a list of alias paths
1514 if len(alias_path) != 1: 1514 ↛ 1515line 1514 didn't jump to line 1515 because the condition on line 1514 was never true1jlmeabnqrifgkophcd
1515 continue # this means that the "alias" does not represent a single field
1516 alias = alias_path[0] 1jlmeabnqrifgkophcd
1517 if not isinstance(alias, str): 1517 ↛ 1518line 1517 didn't jump to line 1518 because the condition on line 1517 was never true1jlmeabnqrifgkophcd
1518 continue # this means that the "alias" does not represent a field
1519 alias_is_present_on_all_choices = True 1jlmeabnqrifgkophcd
1520 for choice in one_of_choices: 1jlmeabnqrifgkophcd
1521 try: 1jlmeabnqrifgkophcd
1522 choice = self.resolve_ref_schema(choice) 1jlmeabnqrifgkophcd
1523 except RuntimeError as exc:
1524 # TODO: fixme - this is a workaround for the fact that we can't always resolve refs
1525 # for tagged union choices at this point in the schema gen process, we might need to do
1526 # another pass at the end like we do for core schemas
1527 self.emit_warning('skipped-discriminator', str(exc))
1528 choice = {}
1529 properties = choice.get('properties', {}) 1jlmeabnqrifgkophcd
1530 if not isinstance(properties, dict) or alias not in properties: 1jlmeabnqrifgkophcd
1531 alias_is_present_on_all_choices = False 1jlmeabnqrifgkophcd
1532 break 1jlmeabnqrifgkophcd
1533 if alias_is_present_on_all_choices: 1jlmeabnqrifgkophcd
1534 openapi_discriminator = alias 1jlmeabnqrifgkophcd
1535 break 1jlmeabnqrifgkophcd
1536 return openapi_discriminator 1jlmeabnqrifgkophcd
1538 def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1539 """Generates a JSON schema that matches a core_schema.ChainSchema.
1541 When generating a schema for validation, we return the validation JSON schema for the first step in the chain.
1542 For serialization, we return the serialization JSON schema for the last step in the chain.
1544 Args:
1545 schema: The core schema.
1547 Returns:
1548 The generated JSON schema.
1549 """
1550 step_index = 0 if self.mode == 'validation' else -1 # use first step for validation, last for serialization 1jlmeabnqrifgkophcd
1551 return self.generate_inner(schema['steps'][step_index]) 1jlmeabnqrifgkophcd
1553 def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1554 """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the
1555 strict schema.
1557 Args:
1558 schema: The core schema.
1560 Returns:
1561 The generated JSON schema.
1562 """
1563 # TODO: Need to read the default value off of model config or whatever
1564 use_strict = schema.get('strict', False) # TODO: replace this default False 1jlmeabnqrifgkophcd
1565 # If your JSON schema fails to generate it is probably
1566 # because one of the following two branches failed.
1567 if use_strict: 1jlmeabnqrifgkophcd
1568 return self.generate_inner(schema['strict_schema']) 1jlmeabnqrifgkophcd
1569 else:
1570 return self.generate_inner(schema['lax_schema']) 1jlmeabnqrifgkophcd
1572 def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1573 """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the
1574 Python schema.
1576 The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override
1577 this method.
1579 Args:
1580 schema: The core schema.
1582 Returns:
1583 The generated JSON schema.
1584 """
1585 return self.generate_inner(schema['json_schema']) 1jlmeabnqrifgkophcd
1587 def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1588 """Generates a JSON schema that matches a schema that defines a typed dict.
1590 Args:
1591 schema: The core schema.
1593 Returns:
1594 The generated JSON schema.
1595 """
1596 total = schema.get('total', True) 1jlmeabnqrifgkophcd
1597 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ 1jlmeabnqrifgkophcd
1598 (name, self.field_is_required(field, total), field)
1599 for name, field in schema['fields'].items()
1600 if self.field_is_present(field)
1601 ]
1602 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1603 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) 1jlmeabnqrifgkophcd
1604 cls = schema.get('cls') 1jlmeabnqrifgkophcd
1605 config = _get_class_config(schema) 1jlmeabnqrifgkophcd
1606 with self._config_wrapper_stack.push(config): 1jlmeabnqrifgkophcd
1607 json_schema = self._named_required_fields_schema(named_required_fields) 1jlmeabnqrifgkophcd
1609 # There's some duplication between `extra_behavior` and
1610 # the config's `extra`/core config's `extra_fields_behavior`.
1611 # However, it is common to manually create TypedDictSchemas,
1612 # where you don't necessarily have a class.
1613 # At runtime, `extra_behavior` takes priority over the config
1614 # for validation, so follow the same for the JSON Schema:
1615 if 'extras_schema' in schema and schema['extras_schema'] != core_schema.any_schema(): 1jlmeabnqrifgkophcd
1616 allow_additional_props = self.generate_inner(schema['extras_schema']) 1jlmeabnqrifgkophcd
1617 else:
1618 allow_additional_props = True 1jlmeabnqrifgkophcd
1620 if schema.get('extra_behavior') == 'forbid': 1jlmeabnqrifgkophcd
1621 json_schema['additionalProperties'] = False 1jlmeabnqrifgkophcd
1622 elif schema.get('extra_behavior') == 'allow': 1jlmeabnqrifgkophcd
1623 json_schema['additionalProperties'] = allow_additional_props 1jlmeabnqrifgkophcd
1625 if cls is not None: 1jlmeabnqrifgkophcd
1626 # `_update_class_schema()` will not override
1627 # `additionalProperties` if already present:
1628 self._update_class_schema(json_schema, cls, config or {}) 1jlmeabnqrifgkophcd
1629 elif 'additionalProperties' not in json_schema: 1629 ↛ 1636line 1629 didn't jump to line 1636 because the condition on line 1629 was always true1jlmeabnqrifgkophcd
1630 extra = schema.get('config', {}).get('extra_fields_behavior') 1jlmeabnqrifgkophcd
1631 if extra == 'forbid': 1jlmeabnqrifgkophcd
1632 json_schema['additionalProperties'] = False 1jlmeabnqrifgkophcd
1633 elif extra == 'allow': 1jlmeabnqrifgkophcd
1634 json_schema['additionalProperties'] = allow_additional_props 1jlmeabnqrifgkophcd
1636 return json_schema 1jlmeabnqrifgkophcd
1638 @staticmethod 1jlmeabnqrifgskophcd
1639 def _name_required_computed_fields( 1jlmeabnqrifgskophcd
1640 computed_fields: list[ComputedField],
1641 ) -> list[tuple[str, bool, core_schema.ComputedField]]:
1642 return [ 1jlmeabnqrifgkophcd
1643 (field['property_name'], field.get('serialization_exclude_if') is None, field) for field in computed_fields
1644 ]
1646 def _named_required_fields_schema( 1jlmeabnqrifgskophcd
1647 self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]]
1648 ) -> JsonSchemaValue:
1649 properties: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
1650 required_fields: list[str] = [] 1jlmeabnqrifgkophcd
1651 for name, required, field in named_required_fields: 1jlmeabnqrifgkophcd
1652 if self.by_alias: 1jlmeabnqrifgkophcd
1653 name = self._get_alias_name(field, name) 1jlmeabnqrifgkophcd
1654 try: 1jlmeabnqrifgkophcd
1655 field_json_schema = self.generate_inner(field).copy() 1jlmeabnqrifgkophcd
1656 except PydanticOmit: 1jlmeabnqrifgkophcd
1657 continue 1jlmeabnqrifgkophcd
1658 if 'title' not in field_json_schema and self.field_title_should_be_set(field): 1jlmeabnqrifgkophcd
1659 title = self.get_title_from_name(name) 1jlmeabnqrifgkophcd
1660 field_json_schema['title'] = title 1jlmeabnqrifgkophcd
1661 field_json_schema = self.handle_ref_overrides(field_json_schema) 1jlmeabnqrifgkophcd
1662 properties[name] = field_json_schema 1jlmeabnqrifgkophcd
1663 if required: 1jlmeabnqrifgkophcd
1664 required_fields.append(name) 1jlmeabnqrifgkophcd
1666 json_schema = {'type': 'object', 'properties': properties} 1jlmeabnqrifgkophcd
1667 if required_fields: 1jlmeabnqrifgkophcd
1668 json_schema['required'] = required_fields 1jlmeabnqrifgkophcd
1669 return json_schema 1jlmeabnqrifgkophcd
1671 def _get_alias_name(self, field: CoreSchemaField, name: str) -> str: 1jlmeabnqrifgskophcd
1672 if field['type'] == 'computed-field': 1jlmeabnqrifgkophcd
1673 alias: Any = field.get('alias', name) 1jlmeabnqrifgkophcd
1674 elif self.mode == 'validation': 1jlmeabnqrifgkophcd
1675 use_alias = self._config.validate_by_alias if self._by_alias is None else self._by_alias 1jlmeabnqrifgkophcd
1676 alias = field.get('validation_alias', name) if use_alias else name 1jlmeabnqrifgkophcd
1677 else:
1678 alias = field.get('serialization_alias', name) 1jlmeabnqrifgkophcd
1679 if isinstance(alias, str): 1jlmeabnqrifgkophcd
1680 name = alias 1jlmeabnqrifgkophcd
1681 elif isinstance(alias, list): 1jlmeabnqrifgkophcd
1682 alias = cast('list[str] | str', alias) 1jlmeabnqrifgkophcd
1683 for path in alias: 1683 ↛ 1691line 1683 didn't jump to line 1691 because the loop on line 1683 didn't complete1jlmeabnqrifgkophcd
1684 if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str): 1jlmeabnqrifgkophcd
1685 # Use the first valid single-item string path; the code that constructs the alias array
1686 # should ensure the first such item is what belongs in the JSON schema
1687 name = path[0] 1jlmeabnqrifgkophcd
1688 break 1jlmeabnqrifgkophcd
1689 else:
1690 assert_never(alias)
1691 return name 1jlmeabnqrifgkophcd
1693 def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1694 """Generates a JSON schema that matches a schema that defines a typed dict field.
1696 Args:
1697 schema: The core schema.
1699 Returns:
1700 The generated JSON schema.
1701 """
1702 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1704 def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1705 """Generates a JSON schema that matches a schema that defines a dataclass field.
1707 Args:
1708 schema: The core schema.
1710 Returns:
1711 The generated JSON schema.
1712 """
1713 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1715 def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1716 """Generates a JSON schema that matches a schema that defines a model field.
1718 Args:
1719 schema: The core schema.
1721 Returns:
1722 The generated JSON schema.
1723 """
1724 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1726 def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1727 """Generates a JSON schema that matches a schema that defines a computed field.
1729 Args:
1730 schema: The core schema.
1732 Returns:
1733 The generated JSON schema.
1734 """
1735 return self.generate_inner(schema['return_schema']) 1jlmeabnqrifgkophcd
1737 def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1738 """Generates a JSON schema that matches a schema that defines a model.
1740 Args:
1741 schema: The core schema.
1743 Returns:
1744 The generated JSON schema.
1745 """
1746 # We do not use schema['model'].model_json_schema() here
1747 # because it could lead to inconsistent refs handling, etc.
1748 cls = cast('type[BaseModel]', schema['cls']) 1jlmeabnqrifgkophcd
1749 config = cls.model_config 1jlmeabnqrifgkophcd
1751 with self._config_wrapper_stack.push(config): 1jlmeabnqrifgkophcd
1752 json_schema = self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
1754 self._update_class_schema(json_schema, cls, config) 1jlmeabnqrifgkophcd
1756 return json_schema 1jlmeabnqrifgkophcd
1758 def _update_class_schema(self, json_schema: JsonSchemaValue, cls: type[Any], config: ConfigDict) -> None: 1jlmeabnqrifgskophcd
1759 """Update json_schema with the following, extracted from `config` and `cls`:
1761 * title
1762 * description
1763 * additional properties
1764 * json_schema_extra
1765 * deprecated
1767 Done in place, hence there's no return value as the original json_schema is mutated.
1768 No ref resolving is involved here, as that's not appropriate for simple updates.
1769 """
1770 from ._internal._dataclasses import is_stdlib_dataclass 1jlmeabnqrifgkophcd
1771 from .main import BaseModel 1jlmeabnqrifgkophcd
1773 if (config_title := config.get('title')) is not None: 1jlmeabnqrifgkophcd
1774 json_schema.setdefault('title', config_title) 1jlmeabnqrifgkophcd
1775 elif model_title_generator := config.get('model_title_generator'): 1jlmeabnqrifgkophcd
1776 title = model_title_generator(cls) 1jlmeabnqrifgkophcd
1777 if not isinstance(title, str): 1jlmeabnqrifgkophcd
1778 raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}') 1jlmeabnqrifgkophcd
1779 json_schema.setdefault('title', title) 1jlmeabnqrifgkophcd
1780 if 'title' not in json_schema: 1jlmeabnqrifgkophcd
1781 json_schema['title'] = cls.__name__ 1jlmeabnqrifgkophcd
1783 # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default
1784 if cls is BaseModel: 1jlmeabnqrifgkophcd
1785 docstring = None 1jlmeabnqrifgkophcd
1786 elif is_stdlib_dataclass(cls): # For Pydantic dataclasses, we already handle this at class creation 1jlmeabnqrifgkophcd
1787 # The `dataclass` module generates a `__doc__` based on the `inspect.signature()`
1788 # result, which we don't want to use as a description. Such `__doc__` startswith
1789 # `cls.__name__(`, which could lead to mistakenly discarding it if for some reason
1790 # an explicitly set class docstring follows the same pattern, but this is unlikely
1791 # to happen.
1792 doc = cls.__doc__ 1jlmeabnqrifgkophcd
1793 docstring = None if doc is None or doc.startswith(f'{cls.__name__}(') else doc 1jlmeabnqrifgkophcd
1794 else:
1795 docstring = cls.__doc__ 1jlmeabnqrifgkophcd
1797 if docstring: 1jlmeabnqrifgkophcd
1798 json_schema.setdefault('description', inspect.cleandoc(docstring)) 1jlmeabnqrifgkophcd
1800 extra = config.get('extra') 1jlmeabnqrifgkophcd
1801 if 'additionalProperties' not in json_schema: # This check is particularly important for `typed_dict_schema()` 1jlmeabnqrifgkophcd
1802 if extra == 'allow': 1jlmeabnqrifgkophcd
1803 json_schema['additionalProperties'] = True 1jlmeabnqrifgkophcd
1804 elif extra == 'forbid': 1jlmeabnqrifgkophcd
1805 json_schema['additionalProperties'] = False 1jlmeabnqrifgkophcd
1807 json_schema_extra = config.get('json_schema_extra') 1jlmeabnqrifgkophcd
1808 if issubclass(cls, BaseModel) and cls.__pydantic_root_model__: 1jlmeabnqrifgkophcd
1809 root_json_schema_extra = cls.model_fields['root'].json_schema_extra 1jlmeabnqrifgkophcd
1810 if json_schema_extra and root_json_schema_extra: 1jlmeabnqrifgkophcd
1811 raise ValueError( 1jlmeabnqrifgkophcd
1812 '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
1813 ' field must not be set simultaneously'
1814 )
1815 if root_json_schema_extra: 1jlmeabnqrifgkophcd
1816 json_schema_extra = root_json_schema_extra 1jlmeabnqrifgkophcd
1818 if isinstance(json_schema_extra, (staticmethod, classmethod)): 1jlmeabnqrifgkophcd
1819 # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable
1820 json_schema_extra = json_schema_extra.__get__(cls) 1jlmeabnqrifgkophcd
1822 if isinstance(json_schema_extra, dict): 1jlmeabnqrifgkophcd
1823 json_schema.update(json_schema_extra) 1jlmeabnqrifgkophcd
1824 elif callable(json_schema_extra): 1jlmeabnqrifgkophcd
1825 if len(_typing_extra.signature_no_eval(json_schema_extra).parameters) > 1: 1jlmeabnqrifgkophcd
1826 json_schema_extra = cast(Callable[[JsonDict, type[Any]], None], json_schema_extra) 1jlmeabnqrifgkophcd
1827 json_schema_extra(json_schema, cls) 1jlmeabnqrifgkophcd
1828 else:
1829 json_schema_extra = cast(Callable[[JsonDict], None], json_schema_extra) 1jlmeabnqrifgkophcd
1830 json_schema_extra(json_schema) 1jlmeabnqrifgkophcd
1831 elif json_schema_extra is not None: 1jlmeabnqrifgkophcd
1832 raise ValueError( 1jlmeabnqrifgkophcd
1833 f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None"
1834 )
1836 # Only the class decorated with `@deprecated` is deprecated, not its subclasses (the attribute is
1837 # inherited, but the runtime only warns on instantiation of the decorated class).
1838 if '__deprecated__' in cls.__dict__: 1jlmeabnqrifgkophcd
1839 json_schema.setdefault('deprecated', True) 1jlmeabnqrifgkophcd
1841 def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1842 """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
1844 Args:
1845 json_schema: The schema to resolve.
1847 Returns:
1848 The resolved schema.
1850 Raises:
1851 RuntimeError: If the schema reference can't be found in definitions.
1852 """
1853 while '$ref' in json_schema: 1jlmeabnqrifgkophcd
1854 ref = json_schema['$ref'] 1jlmeabnqrifgkophcd
1855 schema_to_update = self.get_schema_from_definitions(JsonRef(ref)) 1jlmeabnqrifgkophcd
1856 if schema_to_update is None: 1856 ↛ 1857line 1856 didn't jump to line 1857 because the condition on line 1856 was never true1jlmeabnqrifgkophcd
1857 raise RuntimeError(f'Cannot update undefined schema for $ref={ref}')
1858 json_schema = schema_to_update 1jlmeabnqrifgkophcd
1859 return json_schema 1jlmeabnqrifgkophcd
1861 def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1862 """Generates a JSON schema that matches a schema that defines a model's fields.
1864 Args:
1865 schema: The core schema.
1867 Returns:
1868 The generated JSON schema.
1869 """
1870 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ 1jlmeabnqrifgkophcd
1871 (name, self.field_is_required(field, total=True), field)
1872 for name, field in schema['fields'].items()
1873 if self.field_is_present(field)
1874 ]
1875 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1876 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) 1jlmeabnqrifgkophcd
1877 json_schema = self._named_required_fields_schema(named_required_fields) 1jlmeabnqrifgkophcd
1878 extras_schema = schema.get('extras_schema', None) 1jlmeabnqrifgkophcd
1879 if extras_schema is not None: 1jlmeabnqrifgkophcd
1880 schema_to_update = self.resolve_ref_schema(json_schema) 1jlmeabnqrifgkophcd
1881 schema_to_update['additionalProperties'] = self.generate_inner(extras_schema) 1jlmeabnqrifgkophcd
1882 return json_schema 1jlmeabnqrifgkophcd
1884 def field_is_present(self, field: CoreSchemaField) -> bool: 1jlmeabnqrifgskophcd
1885 """Whether the field should be included in the generated JSON schema.
1887 Args:
1888 field: The schema for the field itself.
1890 Returns:
1891 `True` if the field should be included in the generated JSON schema, `False` otherwise.
1892 """
1893 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1894 # If you still want to include the field in the generated JSON schema,
1895 # override this method and return True
1896 return not field.get('serialization_exclude') and not field.get('init_only') 1jlmeabnqrifgkophcd
1897 elif self.mode == 'validation': 1jlmeabnqrifgkophcd
1898 return True 1jlmeabnqrifgkophcd
1899 else:
1900 assert_never(self.mode)
1902 def field_is_required( 1jlmeabnqrifgskophcd
1903 self,
1904 field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
1905 total: bool,
1906 ) -> bool:
1907 """Whether the field should be marked as required in the generated JSON schema.
1908 (Note that this is irrelevant if the field is not present in the JSON schema.).
1910 Args:
1911 field: The schema for the field itself.
1912 total: Only applies to `TypedDictField`s.
1913 Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't
1914 explicitly specify `required=False` are required.
1916 Returns:
1917 `True` if the field should be marked as required in the generated JSON schema, `False` otherwise.
1918 """
1919 if field['type'] == 'typed-dict-field': 1jlmeabnqrifgkophcd
1920 required = field.get('required', total) 1jlmeabnqrifgkophcd
1921 else:
1922 required = field['schema']['type'] != 'default' 1jlmeabnqrifgkophcd
1924 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1925 has_exclude_if = field.get('serialization_exclude_if') is not None 1jlmeabnqrifgkophcd
1926 if self._config.json_schema_serialization_defaults_required: 1jlmeabnqrifgkophcd
1927 return not has_exclude_if 1jlmeabnqrifgkophcd
1928 else:
1929 return required and not has_exclude_if 1jlmeabnqrifgkophcd
1930 else:
1931 return required 1jlmeabnqrifgkophcd
1933 def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1934 """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
1936 Args:
1937 schema: The core schema.
1939 Returns:
1940 The generated JSON schema.
1941 """
1942 named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ 1jlmeabnqrifgkophcd
1943 (field['name'], self.field_is_required(field, total=True), field)
1944 for field in schema['fields']
1945 if self.field_is_present(field)
1946 ]
1947 if self.mode == 'serialization': 1jlmeabnqrifgkophcd
1948 named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) 1jlmeabnqrifgkophcd
1949 return self._named_required_fields_schema(named_required_fields) 1jlmeabnqrifgkophcd
1951 def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1952 """Generates a JSON schema that matches a schema that defines a dataclass.
1954 Args:
1955 schema: The core schema.
1957 Returns:
1958 The generated JSON schema.
1959 """
1961 cls = schema['cls'] 1jlmeabnqrifgkophcd
1962 config = _get_class_config(schema) 1jlmeabnqrifgkophcd
1964 with self._config_wrapper_stack.push(config): 1jlmeabnqrifgkophcd
1965 json_schema = self.generate_inner(schema['schema']).copy() 1jlmeabnqrifgkophcd
1967 # Only the parent's `extra` config value is relevant to the class schema. It is propagated
1968 # to the core config (and used for validation), so we reuse it:
1969 class_config = config or {} 1jlmeabnqrifgkophcd
1970 if 'extra' not in class_config and (extra := schema.get('config', {}).get('extra_fields_behavior')) is not None: 1jlmeabnqrifgkophcd
1971 class_config = cast('ConfigDict', {**class_config, 'extra': extra}) 1jlmeabnqrifgkophcd
1973 self._update_class_schema(json_schema, cls, class_config) 1jlmeabnqrifgkophcd
1975 return json_schema 1jlmeabnqrifgkophcd
1977 def named_tuple_field_schema(self, schema: core_schema.NamedTupleField) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1978 """Generates a JSON schema that matches a schema that defines a named tuple field.
1980 Args:
1981 schema: The core schema.
1983 Returns:
1984 The generated JSON schema.
1985 """
1986 return self.generate_inner(schema['schema'])
1988 def named_tuple_schema(self, schema: core_schema.NamedTupleSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
1989 """Generates a JSON schema that matches a schema that defines a named tuple.
1991 Args:
1992 schema: The core schema.
1994 Returns:
1995 The generated JSON schema.
1996 """
1997 prefix_items: list[JsonSchemaValue] = [] 1jlmeabnqrifgkophcd
1998 min_items = 0 1jlmeabnqrifgkophcd
2000 for field in schema['fields']: 1jlmeabnqrifgkophcd
2001 name = field['name'] 1jlmeabnqrifgkophcd
2002 if self.by_alias: 2002 ↛ 2007line 2002 didn't jump to line 2007 because the condition on line 2002 was always true1jlmeabnqrifgkophcd
2003 alias = field.get('validation_alias') 1jlmeabnqrifgkophcd
2004 if isinstance(alias, str): 2004 ↛ 2005line 2004 didn't jump to line 2005 because the condition on line 2004 was never true1jlmeabnqrifgkophcd
2005 name = alias
2007 field_schema = self.generate_inner(field['schema']).copy() 1jlmeabnqrifgkophcd
2008 if 'title' not in field_schema and self.field_title_should_be_set(field['schema']): 2008 ↛ 2010line 2008 didn't jump to line 2010 because the condition on line 2008 was always true1jlmeabnqrifgkophcd
2009 field_schema['title'] = self.get_title_from_name(name) 1jlmeabnqrifgkophcd
2010 prefix_items.append(field_schema) 1jlmeabnqrifgkophcd
2012 if field['schema']['type'] != 'default': 2012 ↛ 2000line 2012 didn't jump to line 2000 because the condition on line 2012 was always true1jlmeabnqrifgkophcd
2013 # This assumes that if the field has a default value,
2014 # the inner schema must be of type WithDefaultSchema.
2015 min_items += 1 1jlmeabnqrifgkophcd
2017 json_schema: JsonSchemaValue = {'type': 'array'} 1jlmeabnqrifgkophcd
2018 if prefix_items: 2018 ↛ 2020line 2018 didn't jump to line 2020 because the condition on line 2018 was always true1jlmeabnqrifgkophcd
2019 json_schema['prefixItems'] = prefix_items 1jlmeabnqrifgkophcd
2020 if min_items: 2020 ↛ 2022line 2020 didn't jump to line 2022 because the condition on line 2020 was always true1jlmeabnqrifgkophcd
2021 json_schema['minItems'] = min_items 1jlmeabnqrifgkophcd
2022 json_schema['maxItems'] = len(prefix_items) 1jlmeabnqrifgkophcd
2024 return json_schema 1jlmeabnqrifgkophcd
2026 def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2027 """Generates a JSON schema that matches a schema that defines a function's arguments.
2029 Args:
2030 schema: The core schema.
2032 Returns:
2033 The generated JSON schema.
2034 """
2035 prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments') 1jlmeabnqrifgkophcd
2037 arguments = schema['arguments_schema'] 1jlmeabnqrifgkophcd
2038 kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only'] 1jlmeabnqrifgkophcd
2039 kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}] 1jlmeabnqrifgkophcd
2040 p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only'] 1jlmeabnqrifgkophcd
2041 var_args_schema = schema.get('var_args_schema') 1jlmeabnqrifgkophcd
2042 var_kwargs_schema = schema.get('var_kwargs_schema') 1jlmeabnqrifgkophcd
2044 if prefer_positional: 2044 ↛ 2045line 2044 didn't jump to line 2045 because the condition on line 2044 was never true1jlmeabnqrifgkophcd
2045 positional_possible = not kw_only_arguments and not var_kwargs_schema
2046 if positional_possible:
2047 return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
2049 keyword_possible = not p_only_arguments and not var_args_schema 1jlmeabnqrifgkophcd
2050 if keyword_possible: 2050 ↛ 2057line 2050 didn't jump to line 2057 because the condition on line 2050 was always true1jlmeabnqrifgkophcd
2051 return self.kw_arguments_schema( 1jlmeabnqrifgkophcd
2052 kw_or_p_arguments + kw_only_arguments,
2053 var_kwargs_schema,
2054 var_kwargs_mode=schema.get('var_kwargs_mode') or 'uniform',
2055 )
2057 if not prefer_positional:
2058 positional_possible = not kw_only_arguments and not var_kwargs_schema
2059 if positional_possible:
2060 return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
2062 raise PydanticInvalidForJsonSchema(
2063 'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
2064 )
2066 def kw_arguments_schema( 1jlmeabnqrifgskophcd
2067 self,
2068 arguments: list[core_schema.ArgumentsParameter],
2069 var_kwargs_schema: CoreSchema | None,
2070 *,
2071 var_kwargs_mode: core_schema.VarKwargsMode = 'uniform',
2072 ) -> JsonSchemaValue:
2073 """Generates a JSON schema that matches a schema that defines a function's keyword arguments.
2075 Args:
2076 arguments: The core schema.
2077 var_kwargs_schema: The core schema of the variadic keyword arguments, if any.
2078 var_kwargs_mode: How the variadic keyword arguments are validated.
2080 Returns:
2081 The generated JSON schema.
2082 """
2083 properties: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
2084 required: list[str] = [] 1jlmeabnqrifgkophcd
2085 for argument in arguments: 1jlmeabnqrifgkophcd
2086 name = self.get_argument_name(argument) 1jlmeabnqrifgkophcd
2087 argument_schema = self.generate_inner(argument['schema']).copy() 1jlmeabnqrifgkophcd
2088 if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']): 2088 ↛ 2090line 2088 didn't jump to line 2090 because the condition on line 2088 was always true1jlmeabnqrifgkophcd
2089 argument_schema['title'] = self.get_title_from_name(name) 1jlmeabnqrifgkophcd
2090 properties[name] = argument_schema 1jlmeabnqrifgkophcd
2092 if argument['schema']['type'] != 'default': 2092 ↛ 2096line 2092 didn't jump to line 2096 because the condition on line 2092 was never true1jlmeabnqrifgkophcd
2093 # This assumes that if the argument has a default value,
2094 # the inner schema must be of type WithDefaultSchema.
2095 # I believe this is true, but I am not 100% sure
2096 required.append(name)
2098 json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties} 1jlmeabnqrifgkophcd
2099 if required: 2099 ↛ 2100line 2099 didn't jump to line 2100 because the condition on line 2099 was never true1jlmeabnqrifgkophcd
2100 json_schema['required'] = required
2102 if var_kwargs_schema is None: 2102 ↛ 2103line 2102 didn't jump to line 2103 because the condition on line 2102 was never true1jlmeabnqrifgkophcd
2103 json_schema['additionalProperties'] = False
2104 elif var_kwargs_mode == 'unpacked-typed-dict': 2104 ↛ 2118line 2104 didn't jump to line 2118 because the condition on line 2104 was always true1jlmeabnqrifgkophcd
2105 # The validator validates the extra keyword arguments against the typed dictionary,
2106 # so its properties are merged with the arguments ones (overlapping names are rejected
2107 # at schema generation time). The typed dictionary also controls extra keyword arguments.
2108 # Note: in theory, `resolve_ref_schema()` could fail, but in practice this can't happen
2109 # as the TypedDict's definition is generated before the arguments schema.
2110 typed_dict_json_schema = self.resolve_ref_schema(self.generate_inner(var_kwargs_schema)) 1jlmeabnqrifgkophcd
2111 properties.update(typed_dict_json_schema.get('properties', {})) 1jlmeabnqrifgkophcd
2112 required.extend(typed_dict_json_schema.get('required', [])) 1jlmeabnqrifgkophcd
2113 if required: 2113 ↛ 2115line 2113 didn't jump to line 2115 because the condition on line 2113 was always true1jlmeabnqrifgkophcd
2114 json_schema['required'] = required 1jlmeabnqrifgkophcd
2115 if 'additionalProperties' in typed_dict_json_schema: 1jlmeabnqrifgkophcd
2116 json_schema['additionalProperties'] = typed_dict_json_schema['additionalProperties'] 1jlmeabnqrifgkophcd
2117 else:
2118 additional_properties_schema = self.generate_inner(var_kwargs_schema)
2119 if additional_properties_schema:
2120 json_schema['additionalProperties'] = additional_properties_schema
2121 return json_schema 1jlmeabnqrifgkophcd
2123 def p_arguments_schema( 1jlmeabnqrifgskophcd
2124 self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
2125 ) -> JsonSchemaValue:
2126 """Generates a JSON schema that matches a schema that defines a function's positional arguments.
2128 Args:
2129 arguments: The core schema.
2131 Returns:
2132 The generated JSON schema.
2133 """
2134 prefix_items: list[JsonSchemaValue] = []
2135 min_items = 0
2137 for argument in arguments:
2138 name = self.get_argument_name(argument)
2140 argument_schema = self.generate_inner(argument['schema']).copy()
2141 if 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']):
2142 argument_schema['title'] = self.get_title_from_name(name)
2143 prefix_items.append(argument_schema)
2145 if argument['schema']['type'] != 'default':
2146 # This assumes that if the argument has a default value,
2147 # the inner schema must be of type WithDefaultSchema.
2148 # I believe this is true, but I am not 100% sure
2149 min_items += 1
2151 json_schema: JsonSchemaValue = {'type': 'array'}
2152 if prefix_items:
2153 json_schema['prefixItems'] = prefix_items
2154 if min_items:
2155 json_schema['minItems'] = min_items
2157 if var_args_schema:
2158 items_schema = self.generate_inner(var_args_schema)
2159 if items_schema:
2160 json_schema['items'] = items_schema
2161 else:
2162 json_schema['maxItems'] = len(prefix_items)
2164 return json_schema
2166 def get_argument_name(self, argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) -> str: 1jlmeabnqrifgskophcd
2167 """Retrieves the name of an argument.
2169 Args:
2170 argument: The core schema.
2172 Returns:
2173 The name of the argument.
2174 """
2175 name = argument['name'] 1jlmeabnqrifgkophcd
2176 if self.by_alias: 2176 ↛ 2182line 2176 didn't jump to line 2182 because the condition on line 2176 was always true1jlmeabnqrifgkophcd
2177 alias = argument.get('alias') 1jlmeabnqrifgkophcd
2178 if isinstance(alias, str): 1jlmeabnqrifgkophcd
2179 name = alias 1jlmeabnqrifgkophcd
2180 else:
2181 pass # might want to do something else? 1jlmeabnqrifgkophcd
2182 return name 1jlmeabnqrifgkophcd
2184 def arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2185 """Generates a JSON schema that matches a schema that defines a function's arguments.
2187 Args:
2188 schema: The core schema.
2190 Returns:
2191 The generated JSON schema.
2192 """
2193 arguments = schema['arguments_schema'] 1jlmeabnqrifgkophcd
2194 properties: dict[str, JsonSchemaValue] = {} 1jlmeabnqrifgkophcd
2195 required: list[str] = [] 1jlmeabnqrifgkophcd
2196 for argument in arguments: 1jlmeabnqrifgkophcd
2197 mode = argument.get('mode', 'positional_or_keyword') 1jlmeabnqrifgkophcd
2198 name = self.get_argument_name(argument) 1jlmeabnqrifgkophcd
2199 argument_schema = self.generate_inner(argument['schema']).copy() 1jlmeabnqrifgkophcd
2200 if mode == 'var_args': 1jlmeabnqrifgkophcd
2201 argument_schema = { 1jlmeabnqrifgkophcd
2202 'type': 'array',
2203 'items': argument_schema,
2204 'title': self.get_title_from_name(name),
2205 }
2206 elif mode == 'var_kwargs_uniform': 1jlmeabnqrifgkophcd
2207 argument_schema = { 1jlmeabnqrifgkophcd
2208 'type': 'object',
2209 'additionalProperties': argument_schema,
2210 'title': self.get_title_from_name(name),
2211 }
2212 elif 'title' not in argument_schema and self.field_title_should_be_set(argument['schema']): 1jlmeabnqrifgkophcd
2213 argument_schema['title'] = self.get_title_from_name(name) 1jlmeabnqrifgkophcd
2214 properties[name] = argument_schema 1jlmeabnqrifgkophcd
2216 if ( 1eabifghcd
2217 (mode == 'var_kwargs_unpacked_typed_dict' and 'required' in self.resolve_ref_schema(argument_schema))
2218 or mode not in {'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'}
2219 and argument['schema']['type'] != 'default'
2220 ):
2221 # This assumes that if the argument has a default value,
2222 # the inner schema must be of type WithDefaultSchema.
2223 # I believe this is true, but I am not 100% sure
2224 required.append(name) 1jlmeabnqrifgkophcd
2226 json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties} 1jlmeabnqrifgkophcd
2227 if required: 1jlmeabnqrifgkophcd
2228 json_schema['required'] = required 1jlmeabnqrifgkophcd
2229 # Unexpected arguments are rejected by default:
2230 if schema.get('extra_behavior', 'forbid') == 'forbid': 1jlmeabnqrifgkophcd
2231 json_schema['additionalProperties'] = False 1jlmeabnqrifgkophcd
2232 return json_schema 1jlmeabnqrifgkophcd
2234 def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2235 """Generates a JSON schema that matches a schema that defines a function call.
2237 Args:
2238 schema: The core schema.
2240 Returns:
2241 The generated JSON schema.
2242 """
2243 return self.generate_inner(schema['arguments_schema']) 1jlmeabnqrifgkophcd
2245 def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2246 """Generates a JSON schema that matches a schema that defines a custom error.
2248 Args:
2249 schema: The core schema.
2251 Returns:
2252 The generated JSON schema.
2253 """
2254 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
2256 def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2257 """Generates a JSON schema that matches a schema that defines a JSON object.
2259 Args:
2260 schema: The core schema.
2262 Returns:
2263 The generated JSON schema.
2264 """
2265 content_core_schema = schema.get('schema') or core_schema.any_schema() 1jlmeabnqrifgkophcd
2266 content_json_schema = self.generate_inner(content_core_schema) 1jlmeabnqrifgkophcd
2267 if self.mode == 'validation': 1jlmeabnqrifgkophcd
2268 return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema} 1jlmeabnqrifgkophcd
2269 else:
2270 # self.mode == 'serialization'
2271 return content_json_schema 1jlmeabnqrifgkophcd
2273 def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2274 """Generates a JSON schema that matches a schema that defines a URL.
2276 Args:
2277 schema: The core schema.
2279 Returns:
2280 The generated JSON schema.
2281 """
2282 json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1} 1jlmeabnqrifgkophcd
2283 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) 1jlmeabnqrifgkophcd
2284 return json_schema 1jlmeabnqrifgkophcd
2286 def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2287 """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
2289 Args:
2290 schema: The core schema.
2292 Returns:
2293 The generated JSON schema.
2294 """
2295 # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
2296 json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1} 1jlmeabnqrifgkophcd
2297 self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) 1jlmeabnqrifgkophcd
2298 return json_schema 1jlmeabnqrifgkophcd
2300 def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2301 """Generates a JSON schema that matches a UUID.
2303 Args:
2304 schema: The core schema.
2306 Returns:
2307 The generated JSON schema.
2308 """
2309 return {'type': 'string', 'format': 'uuid'} 1jlmeabnqrifgkophcd
2311 def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2312 """Generates a JSON schema that matches a schema that defines a JSON object with definitions.
2314 Args:
2315 schema: The core schema.
2317 Returns:
2318 The generated JSON schema.
2319 """
2320 for definition in schema['definitions']: 1jlmeabnqrifgkophcd
2321 try: 1jlmeabnqrifgkophcd
2322 self.generate_inner(definition) 1jlmeabnqrifgkophcd
2323 except PydanticInvalidForJsonSchema as e: # noqa: PERF203
2324 core_ref: CoreRef = CoreRef(definition['ref']) # type: ignore
2325 self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
2326 continue
2327 return self.generate_inner(schema['schema']) 1jlmeabnqrifgkophcd
2329 def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2330 """Generates a JSON schema that matches a schema that references a definition.
2332 Args:
2333 schema: The core schema.
2335 Returns:
2336 The generated JSON schema.
2337 """
2338 core_ref = CoreRef(schema['schema_ref']) 1jlmeabnqrifgkophcd
2339 _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref) 1jlmeabnqrifgkophcd
2340 return ref_json_schema 1jlmeabnqrifgkophcd
2342 def ser_schema( 1jlmeabnqrifgskophcd
2343 self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
2344 ) -> JsonSchemaValue | None:
2345 """Generates a JSON schema that matches a schema that defines a serialized object.
2347 Args:
2348 schema: The core schema.
2350 Returns:
2351 The generated JSON schema.
2352 """
2353 match schema: 1jlmeabnqrifgkophcd
2354 case {'type': 'function-plain' | 'function-wrap'}: 2354 ↛ 2359line 2354 didn't jump to line 2359 because the pattern on line 2354 always matched1jlmeabnqrifgkophcd
2355 # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
2356 return_schema = schema.get('return_schema') 1jlmeabnqrifgkophcd
2357 if return_schema is not None: 2357 ↛ 2365line 2357 didn't jump to line 2365 because the condition on line 2357 was always true1jlmeabnqrifgkophcd
2358 return self.generate_inner(return_schema) 1jlmeabnqrifgkophcd
2359 case {'type': 'format' | 'to-string'}:
2360 # FormatSerSchema or ToStringSerSchema
2361 return self.str_schema(core_schema.str_schema())
2362 case {'type': 'model'}:
2363 # ModelSerSchema
2364 return self.generate_inner(schema['schema'])
2365 return None
2367 def complex_schema(self, schema: core_schema.ComplexSchema) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2368 """Generates a JSON schema that matches a complex number.
2370 JSON has no standard way to represent complex numbers. Complex number is not a numeric
2371 type. Here we represent complex number as strings following the rule defined by Python.
2372 For instance, '1+2j' is an accepted complex string. Details can be found in
2373 [Python's `complex` documentation][complex].
2375 Args:
2376 schema: The core schema.
2378 Returns:
2379 The generated JSON schema.
2380 """
2381 return {'type': 'string'} 1jlmeabnqrifgkophcd
2383 # ### Utility methods
2385 def get_title_from_name(self, name: str) -> str: 1jlmeabnqrifgskophcd
2386 """Retrieves a title from a name.
2388 Args:
2389 name: The name to retrieve a title from.
2391 Returns:
2392 The title.
2393 """
2394 return name.title().replace('_', ' ').strip() 1jlmeabnqrifgkophcd
2396 def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool: 1jlmeabnqrifgskophcd
2397 """Returns true if a field with the given schema should have a title set based on the field name.
2399 Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title
2400 (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
2402 Args:
2403 schema: The schema to check.
2405 Returns:
2406 `True` if the field should have a title set, `False` otherwise.
2407 """
2408 if _core_utils.is_core_schema_field(schema): 1jlmeabnqrifgkophcd
2409 if schema['type'] == 'computed-field': 1jlmeabnqrifgkophcd
2410 field_schema = schema['return_schema'] 1jlmeabnqrifgkophcd
2411 else:
2412 field_schema = schema['schema'] 1jlmeabnqrifgkophcd
2413 return self.field_title_should_be_set(field_schema) 1jlmeabnqrifgkophcd
2415 elif _core_utils.is_core_schema(schema): 1jlmeabnqrifgkophcd
2416 if schema.get('ref'): # things with refs, such as models and enums, should not have titles set 1jlmeabnqrifgkophcd
2417 return False 1jlmeabnqrifgkophcd
2418 if schema['type'] in {'default', 'nullable', 'definitions'}: 1jlmeabnqrifgkophcd
2419 return self.field_title_should_be_set(schema['schema']) # type: ignore[typeddict-item] 1jlmeabnqrifgkophcd
2420 if schema['type'] == 'missing-sentinel' and (inner_schema := schema.get('schema')) is not None: 1jlmeabnqrifgkophcd
2421 return self.field_title_should_be_set(inner_schema) 1jlmeabnqrifgkophcd
2422 if _core_utils.is_function_with_inner_schema(schema): 1jlmeabnqrifgkophcd
2423 return self.field_title_should_be_set(schema['schema']) 1jlmeabnqrifgkophcd
2424 if schema['type'] == 'definition-ref': 1jlmeabnqrifgkophcd
2425 # Referenced schemas should not have titles set for the same reason
2426 # schemas with refs should not
2427 return False 1jlmeabnqrifgkophcd
2428 return True # anything else should have title set 1jlmeabnqrifgkophcd
2430 else:
2431 raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}') # pragma: no cover
2433 def normalize_name(self, name: str) -> str: 1jlmeabnqrifgskophcd
2434 """Normalizes a name to be used as a key in a dictionary.
2436 Args:
2437 name: The name to normalize.
2439 Returns:
2440 The normalized name.
2441 """
2442 return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__') 1jlmeabnqrifgkophcd
2444 def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef: 1jlmeabnqrifgskophcd
2445 """Override this method to change the way that definitions keys are generated from a core reference.
2447 Args:
2448 core_mode_ref: The core reference.
2450 Returns:
2451 The definitions key.
2452 """
2453 # Split the core ref into "components"; generic origins and arguments are each separate components
2454 core_ref, mode = core_mode_ref 1jlmeabnqrifgkophcd
2455 components = re.split(r'([\][,])', core_ref) 1jlmeabnqrifgkophcd
2456 # Remove IDs from each component
2457 components = [x.rsplit(':', 1)[0] for x in components] 1jlmeabnqrifgkophcd
2458 core_ref_no_id = ''.join(components) 1jlmeabnqrifgkophcd
2459 # Remove everything before the last period from each "component"
2460 components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components] 1jlmeabnqrifgkophcd
2461 short_ref = ''.join(components) 1jlmeabnqrifgkophcd
2463 mode_title = _MODE_TITLE_MAPPING[mode] 1jlmeabnqrifgkophcd
2465 # It is important that the generated defs_ref values be such that at least one choice will not
2466 # be generated for any other core_ref. Currently, this should be the case because we include
2467 # the id of the source type in the core_ref
2468 name = DefsRef(self.normalize_name(short_ref)) 1jlmeabnqrifgkophcd
2469 name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}') 1jlmeabnqrifgkophcd
2470 module_qualname = DefsRef(self.normalize_name(core_ref_no_id)) 1jlmeabnqrifgkophcd
2471 module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}') 1jlmeabnqrifgkophcd
2472 module_qualname_id = DefsRef(self.normalize_name(core_ref)) 1jlmeabnqrifgkophcd
2473 occurrence_index = self._collision_index.get(module_qualname_id) 1jlmeabnqrifgkophcd
2474 if occurrence_index is None: 1jlmeabnqrifgkophcd
2475 self._collision_counter[module_qualname] += 1 1jlmeabnqrifgkophcd
2476 occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname] 1jlmeabnqrifgkophcd
2478 module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}') 1jlmeabnqrifgkophcd
2479 module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}') 1jlmeabnqrifgkophcd
2481 self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [ 1jlmeabnqrifgkophcd
2482 name,
2483 name_mode,
2484 module_qualname,
2485 module_qualname_mode,
2486 module_qualname_occurrence,
2487 module_qualname_occurrence_mode,
2488 ]
2490 return module_qualname_occurrence_mode 1jlmeabnqrifgkophcd
2492 def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]: 1jlmeabnqrifgskophcd
2493 """This method wraps the get_defs_ref method with some cache-lookup/population logic,
2494 and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
2496 Args:
2497 core_ref: The core reference to get the definitions reference for.
2499 Returns:
2500 A tuple of the definitions reference and the JSON schema that will refer to it.
2501 """
2502 core_mode_ref = (core_ref, self.mode) 1jlmeabnqrifgkophcd
2503 maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref) 1jlmeabnqrifgkophcd
2504 if maybe_defs_ref is not None: 1jlmeabnqrifgkophcd
2505 json_ref = self.core_to_json_refs[core_mode_ref] 1jlmeabnqrifgkophcd
2506 return maybe_defs_ref, {'$ref': json_ref} 1jlmeabnqrifgkophcd
2508 defs_ref = self.get_defs_ref(core_mode_ref) 1jlmeabnqrifgkophcd
2510 # populate the ref translation mappings
2511 self.core_to_defs_refs[core_mode_ref] = defs_ref 1jlmeabnqrifgkophcd
2512 self.defs_to_core_refs[defs_ref] = core_mode_ref 1jlmeabnqrifgkophcd
2514 json_ref = JsonRef(self.ref_template.format(model=defs_ref)) 1jlmeabnqrifgkophcd
2515 self.core_to_json_refs[core_mode_ref] = json_ref 1jlmeabnqrifgkophcd
2516 self.json_to_defs_refs[json_ref] = defs_ref 1jlmeabnqrifgkophcd
2517 ref_json_schema = {'$ref': json_ref} 1jlmeabnqrifgkophcd
2518 return defs_ref, ref_json_schema 1jlmeabnqrifgkophcd
2520 def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2521 """Remove any sibling keys that are redundant with the referenced schema.
2523 Args:
2524 json_schema: The schema to remove redundant sibling keys from.
2526 Returns:
2527 The schema with redundant sibling keys removed.
2528 """
2529 if '$ref' in json_schema: 1jlmeabnqrifgkophcd
2530 # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
2531 json_schema = json_schema.copy() 1jlmeabnqrifgkophcd
2533 referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref'])) 1jlmeabnqrifgkophcd
2534 if referenced_json_schema is None: 1jlmeabnqrifgkophcd
2535 # This can happen when building schemas for models with not-yet-defined references.
2536 # It may be a good idea to do a recursive pass at the end of the generation to remove
2537 # any redundant override keys.
2538 return json_schema 1jlmeabnqrifgkophcd
2539 for k, v in list(json_schema.items()): 1jlmeabnqrifgkophcd
2540 if k == '$ref': 1jlmeabnqrifgkophcd
2541 continue 1jlmeabnqrifgkophcd
2542 if k in referenced_json_schema and referenced_json_schema[k] == v: 1jlmeabnqrifgkophcd
2543 del json_schema[k] # redundant key 1jlmeabnqrifgkophcd
2545 return json_schema 1jlmeabnqrifgkophcd
2547 def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None: 1jlmeabnqrifgskophcd
2548 try: 1jlmeabnqrifgkophcd
2549 def_ref = self.json_to_defs_refs[json_ref] 1jlmeabnqrifgkophcd
2550 if def_ref in self._core_defs_invalid_for_json_schema: 2550 ↛ 2551line 2550 didn't jump to line 2551 because the condition on line 2550 was never true1jlmeabnqrifgkophcd
2551 raise self._core_defs_invalid_for_json_schema[def_ref]
2552 return self.definitions.get(def_ref, None) 1jlmeabnqrifgkophcd
2553 except KeyError: 1jlmeabnqrifgkophcd
2554 if json_ref.startswith(('http://', 'https://')): 2554 ↛ 2556line 2554 didn't jump to line 2556 because the condition on line 2554 was always true1jlmeabnqrifgkophcd
2555 return None 1jlmeabnqrifgkophcd
2556 raise
2558 def encode_default(self, dft: Any) -> Any: 1jlmeabnqrifgskophcd
2559 """Encode a default value to a JSON-serializable value.
2561 This is used to encode default values for fields in the generated JSON schema.
2563 Args:
2564 dft: The default value to encode.
2566 Returns:
2567 The encoded default value.
2568 """
2569 from .type_adapter import TypeAdapter, _type_has_config 1jlmeabnqrifgkophcd
2571 config = self._config.config_dict 1jlmeabnqrifgkophcd
2572 if self.mode == 'validation' and ('ser_json_temporal' in config or 'ser_json_timedelta' in config): 1jlmeabnqrifgkophcd
2573 # Temporal serialization formats aren't applied to validation JSON Schemas (see `_common_temporal_schema()`),
2574 # so they shouldn't be applied to the default either:
2575 config = cast( 1jlmeabnqrifgkophcd
2576 'ConfigDict',
2577 {k: v for k, v in config.items() if k not in ('ser_json_temporal', 'ser_json_timedelta')},
2578 )
2579 try: 1jlmeabnqrifgkophcd
2580 # Types with their own config (e.g. models) can't be used with a config, so we serialize "as Any",
2581 # which will serialize using their own serializer.
2582 return TypeAdapter(Any if _type_has_config(type(dft)) else type(dft), config=config).dump_python( 1jlmeabnqrifgkophcd
2583 dft, by_alias=self.by_alias, mode='json'
2584 )
2585 except Exception as e: 1jlmeabnqrifgkophcd
2586 raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}') from e 1jlmeabnqrifgkophcd
2588 def update_with_validations( 1jlmeabnqrifgskophcd
2589 self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
2590 ) -> None:
2591 """Update the json_schema with the corresponding validations specified in the core_schema,
2592 using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
2594 Args:
2595 json_schema: The JSON schema to update.
2596 core_schema: The core schema to get the validations from.
2597 mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
2598 """
2599 for core_key, json_schema_key in mapping.items(): 1jlmeabnqrifgkophcd
2600 if core_key in core_schema: 1jlmeabnqrifgkophcd
2601 json_schema[json_schema_key] = core_schema[core_key] 1jlmeabnqrifgkophcd
2603 class ValidationsMapping: 1jlmeabnqrifgskophcd
2604 """This class just contains mappings from core_schema attribute names to the corresponding
2605 JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in
2606 principle override this class in a subclass of GenerateJsonSchema (by inheriting from
2607 GenerateJsonSchema.ValidationsMapping) to change these mappings.
2608 """
2610 numeric = { 1jlmeabnqrifgskophcd
2611 'multiple_of': 'multipleOf',
2612 'le': 'maximum',
2613 'ge': 'minimum',
2614 'lt': 'exclusiveMaximum',
2615 'gt': 'exclusiveMinimum',
2616 }
2617 bytes = { 1jlmeabnqrifgskophcd
2618 'min_length': 'minLength',
2619 'max_length': 'maxLength',
2620 }
2621 string = { 1jlmeabnqrifgskophcd
2622 'min_length': 'minLength',
2623 'max_length': 'maxLength',
2624 'pattern': 'pattern',
2625 }
2626 array = { 1jlmeabnqrifgskophcd
2627 'min_length': 'minItems',
2628 'max_length': 'maxItems',
2629 }
2630 object = { 1jlmeabnqrifgskophcd
2631 'min_length': 'minProperties',
2632 'max_length': 'maxProperties',
2633 }
2635 def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2636 members = [] 1jlmeabnqrifgkophcd
2637 for schema in schemas: 1jlmeabnqrifgkophcd
2638 if len(schema) == 1 and 'anyOf' in schema: 1jlmeabnqrifgkophcd
2639 members.extend(schema['anyOf']) 1jlmeabnqrifgkophcd
2640 else:
2641 members.append(schema) 1jlmeabnqrifgkophcd
2642 members = _deduplicate_schemas(members) 1jlmeabnqrifgkophcd
2643 if len(members) == 1: 1jlmeabnqrifgkophcd
2644 return members[0] 1jlmeabnqrifgkophcd
2645 return {'anyOf': members} 1jlmeabnqrifgkophcd
2647 def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]: 1jlmeabnqrifgskophcd
2648 """Get all values corresponding to the key '$ref' anywhere in the json_schema."""
2649 json_refs: dict[JsonRef, int] = Counter() 1jlmeabnqrifgkophcd
2651 def _add_json_refs(schema: Any) -> None: 1jlmeabnqrifgkophcd
2652 if isinstance(schema, dict): 1jlmeabnqrifgkophcd
2653 if '$ref' in schema: 1jlmeabnqrifgkophcd
2654 json_ref = JsonRef(schema['$ref']) 1jlmeabnqrifgkophcd
2655 if not isinstance(json_ref, str): 1jlmeabnqrifgkophcd
2656 return # in this case, '$ref' might have been the name of a property 1jlmeabnqrifgkophcd
2657 already_visited = json_ref in json_refs 1jlmeabnqrifgkophcd
2658 json_refs[json_ref] += 1 1jlmeabnqrifgkophcd
2659 if already_visited: 1jlmeabnqrifgkophcd
2660 return # prevent recursion on a definition that was already visited 1jlmeabnqrifgkophcd
2661 try: 1jlmeabnqrifgkophcd
2662 defs_ref = self.json_to_defs_refs[json_ref] 1jlmeabnqrifgkophcd
2663 if defs_ref in self._core_defs_invalid_for_json_schema: 2663 ↛ 2664line 2663 didn't jump to line 2664 because the condition on line 2663 was never true1jlmeabnqrifgkophcd
2664 raise self._core_defs_invalid_for_json_schema[defs_ref]
2665 _add_json_refs(self.definitions[defs_ref]) 1jlmeabnqrifgkophcd
2666 except KeyError: 1jlmeabnqrifgkophcd
2667 if not json_ref.startswith(('http://', 'https://')): 2667 ↛ 2668line 2667 didn't jump to line 2668 because the condition on line 2667 was never true1jlmeabnqrifgkophcd
2668 raise
2670 for k, v in schema.items(): 1jlmeabnqrifgkophcd
2671 if k == 'examples' and isinstance(v, list): 1jlmeabnqrifgkophcd
2672 # Skip examples that may contain arbitrary values and references
2673 # (see the comment in `_get_all_json_refs` for more details).
2674 continue 1jlmeabnqrifgkophcd
2675 _add_json_refs(v) 1jlmeabnqrifgkophcd
2676 elif isinstance(schema, list): 1jlmeabnqrifgkophcd
2677 for v in schema: 1jlmeabnqrifgkophcd
2678 _add_json_refs(v) 1jlmeabnqrifgkophcd
2680 _add_json_refs(json_schema) 1jlmeabnqrifgkophcd
2681 return json_refs 1jlmeabnqrifgkophcd
2683 def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue: 1jlmeabnqrifgskophcd
2684 raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}') 1jlmeabnqrifgkophcd
2686 def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None: 1jlmeabnqrifgskophcd
2687 """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method."""
2688 message = self.render_warning_message(kind, detail) 1jlmeabnqrifgkophcd
2689 if message is not None: 1jlmeabnqrifgkophcd
2690 warnings.warn(message, PydanticJsonSchemaWarning) 1jlmeabnqrifgkophcd
2692 def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None: 1jlmeabnqrifgskophcd
2693 """This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
2695 You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema
2696 to modify what warnings are generated. If you want more control, you can override this method;
2697 just return None in situations where you don't want warnings to be emitted.
2699 Args:
2700 kind: The kind of warning to render. It can be one of the following:
2702 - 'skipped-choice': A choice field was skipped because it had no valid choices.
2703 - 'non-serializable-default': A default value was skipped because it was not JSON-serializable.
2704 detail: A string with additional details about the warning.
2706 Returns:
2707 The formatted warning message, or `None` if no warning should be emitted.
2708 """
2709 if kind in self.ignored_warning_kinds: 1jlmeabnqrifgkophcd
2710 return None 1jlmeabnqrifgkophcd
2711 return f'{detail} [{kind}]' 1jlmeabnqrifgkophcd
2713 def _build_definitions_remapping(self) -> _DefinitionsRemapping: 1jlmeabnqrifgskophcd
2714 defs_to_json: dict[DefsRef, JsonRef] = {} 1jlmeabnqrifgkophcd
2715 for defs_refs in self._prioritized_defsref_choices.values(): 1jlmeabnqrifgkophcd
2716 for defs_ref in defs_refs: 1jlmeabnqrifgkophcd
2717 json_ref = JsonRef(self.ref_template.format(model=defs_ref)) 1jlmeabnqrifgkophcd
2718 defs_to_json[defs_ref] = json_ref 1jlmeabnqrifgkophcd
2720 return _DefinitionsRemapping.from_prioritized_choices( 1jlmeabnqrifgkophcd
2721 self._prioritized_defsref_choices, defs_to_json, self.definitions
2722 )
2724 def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None: 1jlmeabnqrifgskophcd
2725 visited_defs_refs: set[DefsRef] = set() 1jlmeabnqrifgkophcd
2726 unvisited_json_refs = _get_all_json_refs(schema) 1jlmeabnqrifgkophcd
2727 while unvisited_json_refs: 1jlmeabnqrifgkophcd
2728 next_json_ref = unvisited_json_refs.pop() 1jlmeabnqrifgkophcd
2729 try: 1jlmeabnqrifgkophcd
2730 next_defs_ref = self.json_to_defs_refs[next_json_ref] 1jlmeabnqrifgkophcd
2731 if next_defs_ref in visited_defs_refs: 1jlmeabnqrifgkophcd
2732 continue 1jlmeabnqrifgkophcd
2733 visited_defs_refs.add(next_defs_ref) 1jlmeabnqrifgkophcd
2734 unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref])) 1jlmeabnqrifgkophcd
2735 except KeyError: 1jlmeabnqrifgkophcd
2736 if not next_json_ref.startswith(('http://', 'https://')): 2736 ↛ 2737line 2736 didn't jump to line 2737 because the condition on line 2736 was never true1jlmeabnqrifgkophcd
2737 raise
2739 self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs} 1jlmeabnqrifgkophcd
2742# ##### Start JSON Schema Generation Functions #####
2745def model_json_schema( 1jlmeabnqrifgskophcd
2746 cls: type[BaseModel] | type[PydanticDataclass],
2747 by_alias: bool | None = None,
2748 ref_template: str = DEFAULT_REF_TEMPLATE,
2749 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
2750 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
2751 mode: JsonSchemaMode = 'validation',
2752) -> dict[str, Any]:
2753 """Utility function to generate a JSON Schema for a model.
2755 Args:
2756 cls: The model class to generate a JSON Schema for.
2757 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
2758 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
2759 schemas). An explicit value takes precedence over the configuration.
2760 ref_template: The template to use for generating JSON Schema references.
2761 union_format: The format to use when combining schemas from unions together. Can be one of:
2763 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
2764 keyword to combine schemas (the default).
2765 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
2766 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
2767 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
2768 `any_of`.
2769 schema_generator: The class to use for generating the JSON Schema.
2770 mode: The mode to use for generating the JSON Schema. It can be one of the following:
2772 - 'validation': Generate a JSON Schema for validating data.
2773 - 'serialization': Generate a JSON Schema for serializing data.
2775 Returns:
2776 The generated JSON Schema.
2777 """
2778 from .main import BaseModel 1jlmeabnqrifgkophcd
2780 schema_generator_instance = schema_generator( 1jlmeabnqrifgkophcd
2781 by_alias=by_alias, ref_template=ref_template, union_format=union_format
2782 )
2784 if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema): 1jlmeabnqrifgkophcd
2785 cls.__pydantic_core_schema__.rebuild() 1jlmeabnqrifgkophcd
2787 if cls is BaseModel: 2787 ↛ 2788line 2787 didn't jump to line 2788 because the condition on line 2787 was never true1jlmeabnqrifgkophcd
2788 raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')
2790 assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it' 1jlmeabnqrifgkophcd
2791 return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode) 1jlmeabnqrifgkophcd
2794def models_json_schema( 1jlmeabnqrifgskophcd
2795 models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
2796 *,
2797 by_alias: bool | None = None,
2798 title: str | None = None,
2799 description: str | None = None,
2800 ref_template: str = DEFAULT_REF_TEMPLATE,
2801 union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
2802 schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
2803) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
2804 """Utility function to generate a JSON Schema for multiple models.
2806 Args:
2807 models: A sequence of tuples of the form (model, mode).
2808 by_alias: Whether to use field aliases as keys in the generated JSON Schema. If `None` (the default),
2809 aliases are used unless disabled by the configuration (i.e. `validate_by_alias=False` for validation
2810 schemas). An explicit value takes precedence over the configuration.
2811 title: The title of the generated JSON Schema.
2812 description: The description of the generated JSON Schema.
2813 ref_template: The reference template to use for generating JSON Schema references.
2814 union_format: The format to use when combining schemas from unions together. Can be one of:
2816 - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
2817 keyword to combine schemas (the default).
2818 - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
2819 keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
2820 type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
2821 `any_of`.
2822 schema_generator: The schema generator to use for generating the JSON Schema.
2824 Returns:
2825 A tuple where:
2826 - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
2827 whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
2828 JsonRef references to definitions that are defined in the second returned element.)
2829 - The second element is a JSON schema containing all definitions referenced in the first returned
2830 element, along with the optional title and description keys.
2831 """
2832 for cls, _ in models: 1jlmeabnqrifgkophcd
2833 if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema): 2833 ↛ 2834line 2833 didn't jump to line 2834 because the condition on line 2833 was never true1jlmeabnqrifgkophcd
2834 cls.__pydantic_core_schema__.rebuild()
2836 instance = schema_generator(by_alias=by_alias, ref_template=ref_template, union_format=union_format) 1jlmeabnqrifgkophcd
2837 inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [ 1jlmeabnqrifgkophcd
2838 (m, mode, m.__pydantic_core_schema__) for m, mode in models
2839 ]
2840 json_schemas_map, definitions = instance.generate_definitions(inputs) 1jlmeabnqrifgkophcd
2842 json_schema: dict[str, Any] = {} 1jlmeabnqrifgkophcd
2843 if definitions: 1jlmeabnqrifgkophcd
2844 json_schema['$defs'] = definitions 1jlmeabnqrifgkophcd
2845 if title: 1jlmeabnqrifgkophcd
2846 json_schema['title'] = title 1jlmeabnqrifgkophcd
2847 if description: 1jlmeabnqrifgkophcd
2848 json_schema['description'] = description 1jlmeabnqrifgkophcd
2850 return json_schemas_map, json_schema 1jlmeabnqrifgkophcd
2853# ##### End JSON Schema Generation Functions #####
2856# Decimal JSON Schema pattern utilities.
2857# Note: while we could use `\d` to represent digits (`Decimal` objects allow Unicode decimal digits), we use [0-9] instead:
2858# - to reduce complexity (`\d` expands to a large set, and with `max_digits`/`decimal_places` constraints set, it can blow
2859# the compile limit on some engines).
2860# - [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)
2861# while it allows any Unicode decimal digit in Python.
2864def _repeat(atom: str, min_count: int, max_count: int) -> str: 1jlmeabnqrifgskophcd
2865 """Build a regex repetition of `atom` between `min_count` and `max_count` times (inclusive), using the shortest quantifier."""
2866 if min_count > max_count or max_count == 0: 1jlmeabnqrifgkophcd
2867 return '' 1jlmeabnqrifgkophcd
2868 if min_count == max_count: 1jlmeabnqrifgkophcd
2869 return atom if min_count == 1 else f'{atom}{{{min_count}}}' 1jlmeabnqrifgkophcd
2870 if (min_count, max_count) == (0, 1): 1jlmeabnqrifgkophcd
2871 return f'{atom}?' 1jlmeabnqrifgkophcd
2872 return f'{atom}{{{min_count},{max_count}}}' 1jlmeabnqrifgkophcd
2875def _int_range_pattern(max_value: int) -> str: 1jlmeabnqrifgskophcd
2876 """Build a regex matching the integers between 1 and `max_value` (inclusive), without leading zeros."""
2877 digits = str(max_value) 1jlmeabnqrifgkophcd
2878 length = len(digits) 1jlmeabnqrifgkophcd
2879 alts: list[str] = [f'[1-9]{_repeat("[0-9]", k - 1, k - 1)}' for k in range(1, length)] 1jlmeabnqrifgkophcd
2880 for i, char in enumerate(digits): 1jlmeabnqrifgkophcd
2881 d = int(char) 1jlmeabnqrifgkophcd
2882 low = 1 if i == 0 else 0 1jlmeabnqrifgkophcd
2883 high = d if i == length - 1 else d - 1 1jlmeabnqrifgkophcd
2884 if high >= low: 2884 ↛ 2880line 2884 didn't jump to line 2880 because the condition on line 2884 was always true1jlmeabnqrifgkophcd
2885 char_class = str(low) if low == high else f'[{low}-{high}]' 1jlmeabnqrifgkophcd
2886 alts.append(f'{digits[:i]}{char_class}{_repeat("[0-9]", length - i - 1, length - i - 1)}') 1jlmeabnqrifgkophcd
2887 return alts[0] if len(alts) == 1 else f'(?:{"|".join(alts)})' 1jlmeabnqrifgkophcd
2890def _decimal_validation_pattern(max_digits: int | None, decimal_places: int | None, allow_inf_nan: bool) -> str: 1jlmeabnqrifgskophcd
2891 """Build the decimal pattern for the `'validation'` mode."""
2893 number = r'(?:[0-9]+\.?[0-9]*|\.[0-9]+)' # e.g. 1, 1., .5 1jlmeabnqrifgkophcd
2894 exponent = r'[eE][+-]?[0-9]+' # e.g. e5, E5, e-7 1jlmeabnqrifgkophcd
2895 # e.g. Infinity, inf, NaN, sNaN, NaN123 (case-insensitive). Spelled out explicitly, as inline flags
2896 # aren't supported by all regular expression engines:
2897 non_finite = r'|[iI][nN][fF](?:[iI][nN][iI][tT][yY])?|[sS]?[nN][aA][nN][0-9]*' if allow_inf_nan else '' 1jlmeabnqrifgkophcd
2898 if max_digits is None and decimal_places is None: 1jlmeabnqrifgkophcd
2899 return rf'^[+-]?(?:{number}(?:{exponent})?{non_finite})$' 1jlmeabnqrifgkophcd
2901 alts: list[str] = [] 1jlmeabnqrifgkophcd
2902 if max_digits is not None and decimal_places is not None: 1jlmeabnqrifgkophcd
2903 # If `decimal_places > max_digits`, no whole digits are allowed and `max_digits` bounds the decimal places:
2904 whole = max(0, max_digits - decimal_places) 1jlmeabnqrifgkophcd
2905 places = min(max_digits, decimal_places) 1jlmeabnqrifgkophcd
2906 int_part = f'0*{_repeat("[0-9]", 1, whole)}' if whole else '0+' 1jlmeabnqrifgkophcd
2907 opt_int_part = f'0*{_repeat("[0-9]", 0, whole)}' 1jlmeabnqrifgkophcd
2908 opt_frac_part = rf'\.{_repeat("[0-9]", 0, places)}0*' 1jlmeabnqrifgkophcd
2909 frac_part = rf'\.{_repeat("[0-9]", 1, places)}0*' if places else r'\.0+' 1jlmeabnqrifgkophcd
2910 if whole: 1jlmeabnqrifgkophcd
2911 alts += [f'{int_part}(?:{opt_frac_part})?', f'{opt_int_part}{frac_part}'] 1jlmeabnqrifgkophcd
2912 else:
2913 # No whole digits are allowed: a bare integer part (even `0`) counts as one whole digit,
2914 # so only forms with a fractional part (which have zero whole digits) are valid:
2915 alts.append(f'{opt_int_part}{frac_part}') 1jlmeabnqrifgkophcd
2916 elif max_digits is not None: 1jlmeabnqrifgkophcd
2917 # The whole part and decimal part must have at most `max_digits` digits in total,
2918 # so we enumerate the possible widths of the whole part:
2919 int_part = f'0*{_repeat("[0-9]", 1, max_digits)}' if max_digits else '0+' 1jlmeabnqrifgkophcd
2920 alts.append(rf'{int_part}(?:\.0*)?') 1jlmeabnqrifgkophcd
2921 alts += [ 1jlmeabnqrifgkophcd
2922 rf'0*{_repeat("[0-9]", whole, whole)}\.{_repeat("[0-9]", 1, max_digits - whole)}0*'
2923 for whole in range(max_digits)
2924 ] or [r'0*\.0+']
2925 else:
2926 assert decimal_places is not None 1jlmeabnqrifgkophcd
2927 opt_frac_part = rf'\.{_repeat("[0-9]", 0, decimal_places)}0*' 1jlmeabnqrifgkophcd
2928 frac_part = rf'\.{_repeat("[0-9]", 1, decimal_places)}0*' if decimal_places else r'\.0+' 1jlmeabnqrifgkophcd
2929 alts += [f'[0-9]+(?:{opt_frac_part})?', f'[0-9]*{frac_part}'] 1jlmeabnqrifgkophcd
2931 alts.append(f'{number}{exponent}') 1jlmeabnqrifgkophcd
2932 return rf'^[+-]?(?:{"|".join(alts)}{non_finite})$' 1jlmeabnqrifgkophcd
2935def _decimal_serialization_pattern(max_digits: int | None, decimal_places: int | None, allow_inf_nan: bool) -> str: 1jlmeabnqrifgskophcd
2936 """Build the decimal pattern for the `'serialization'` mode.
2938 Decimals are serialized using `str()`, producing either:
2940 - The plain notation (`'123.45'`), when the exponent is lower than or equal to 0 and the adjusted
2941 exponent is greater than or equal to -6.
2942 - The scientific notation otherwise (`'1E+3'`, `'1.5E-7'`, `'0E-10'`), with a single digit before
2943 the optional decimal point and an always signed exponent.
2945 Trailing zeros of the decimal part are preserved by `str()`, but aren't counted by the validation logic.
2946 """
2948 def frac_part(places: int) -> str: 1jlmeabnqrifgkophcd
2949 return rf'\.{_repeat("[0-9]", 1, places)}0*' if places else r'\.0+' 1jlmeabnqrifgkophcd
2951 alts: list[str] = [] 1jlmeabnqrifgkophcd
2953 # Plain notation:
2954 if max_digits is not None and decimal_places is not None: 1jlmeabnqrifgkophcd
2955 whole = max(0, max_digits - decimal_places) 1jlmeabnqrifgkophcd
2956 places = min(max_digits, decimal_places) 1jlmeabnqrifgkophcd
2957 int_part = f'(?:0|[1-9]{_repeat("[0-9]", 0, whole - 1)})' if whole else '0' 1jlmeabnqrifgkophcd
2958 if whole: 1jlmeabnqrifgkophcd
2959 alts.append(f'{int_part}(?:{frac_part(places)})?') 1jlmeabnqrifgkophcd
2960 else:
2961 # No whole digits are allowed: a bare `0` counts as one whole digit, so a decimal
2962 # satisfying the constraints is always serialized with a fractional part:
2963 alts.append(f'{int_part}{frac_part(places)}') 1jlmeabnqrifgkophcd
2964 elif max_digits is not None: 1jlmeabnqrifgkophcd
2965 # The whole part and decimal part must have at most `max_digits` digits in total,
2966 # so we enumerate the possible widths of the whole part:
2967 alts.append(rf'0(?:\.{_repeat("[0-9]", 1, max_digits)}0*)?') 1jlmeabnqrifgkophcd
2968 alts += [ 1jlmeabnqrifgkophcd
2969 f'[1-9]{_repeat("[0-9]", whole - 1, whole - 1)}(?:{frac_part(max_digits - whole)})?'
2970 for whole in range(1, max_digits + 1)
2971 ]
2972 elif decimal_places is not None: 1jlmeabnqrifgkophcd
2973 alts.append(f'(?:0|[1-9][0-9]*)(?:{frac_part(decimal_places)})?') 1jlmeabnqrifgkophcd
2974 else:
2975 alts.append(r'(?:0|[1-9][0-9]*)(?:\.[0-9]+)?') 1jlmeabnqrifgkophcd
2977 # Zero with an exponent (e.g. `'0E-10'`), which normalizes to zero and thus satisfies any constraint,
2978 # unless no whole digits are allowed and the exponent is positive (such a zero counts as one
2979 # whole digit, e.g. `0E+1` is rejected when `max_digits <= decimal_places`):
2980 if max_digits is not None and decimal_places is not None and max_digits <= decimal_places: 1jlmeabnqrifgkophcd
2981 alts.append(r'0E-[1-9][0-9]*') 1jlmeabnqrifgkophcd
2982 else:
2983 alts.append(r'0E[+-][1-9][0-9]*') 1jlmeabnqrifgkophcd
2985 # Scientific notation with a positive exponent `k` (e.g. `'1.5E+3'`): the value has `k + 1` whole digits
2986 # and no decimal places:
2987 if max_digits is None: 1jlmeabnqrifgkophcd
2988 alts.append(r'[1-9](?:\.[0-9]+)?E\+[1-9][0-9]*') 1jlmeabnqrifgkophcd
2989 else:
2990 max_exponent = max_digits - (decimal_places or 0) - 1 1jlmeabnqrifgkophcd
2991 if max_exponent >= 1: 1jlmeabnqrifgkophcd
2992 alts.append(rf'[1-9](?:\.[0-9]+)?E\+{_int_range_pattern(max_exponent)}') 1jlmeabnqrifgkophcd
2994 # Scientific notation with a negative exponent `k` (`k >= 7`, e.g. `'1.5E-7'`): the value has no whole digits,
2995 # and `k` + (the number of significant decimal digits of the coefficient) decimal places:
2996 if max_digits is None and decimal_places is None: 1jlmeabnqrifgkophcd
2997 alts.append(r'[1-9](?:\.[0-9]+)?E-[1-9][0-9]*') 1jlmeabnqrifgkophcd
2998 else:
2999 max_places = min(c for c in (max_digits, decimal_places) if c is not None) 1jlmeabnqrifgkophcd
3000 alts += [f'[1-9](?:{frac_part(max_places - k)})?E-{k}' for k in range(7, max_places + 1)] 1jlmeabnqrifgkophcd
3002 if allow_inf_nan: 1jlmeabnqrifgkophcd
3003 # `str()` produces `'Infinity'`, `'NaN'` and `'sNaN'` (with an optional payload):
3004 alts += ['Infinity', 's?NaN[0-9]*'] 1jlmeabnqrifgkophcd
3006 return rf'^-?(?:{"|".join(alts)})$' 1jlmeabnqrifgkophcd
3009def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]: 1jlmeabnqrifgskophcd
3010 return list({_make_json_hashable(schema): schema for schema in schemas}.values()) 1jlmeabnqrifgkophcd
3013_HashableJsonValue: TypeAlias = ( 1jlmeabnqrifgskophcd
3014 int | float | str | bool | None | tuple['_HashableJsonValue', ...] | tuple[tuple[str, '_HashableJsonValue'], ...]
3015)
3018def _make_json_hashable(value: JsonValue) -> _HashableJsonValue: 1jlmeabnqrifgskophcd
3019 if isinstance(value, dict): 1jlmeabnqrifgkophcd
3020 return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items())) 1jlmeabnqrifgkophcd
3021 elif isinstance(value, list): 1jlmeabnqrifgkophcd
3022 return tuple(_make_json_hashable(v) for v in value) 1jlmeabnqrifgkophcd
3023 else:
3024 return value 1jlmeabnqrifgkophcd
3027@dataclasses.dataclass(slots=True) 1jlmeabnqrifgskophcd
3028class WithJsonSchema: 1jlmeabnqrifgskophcd
3029 """!!! abstract "Usage Documentation"
3030 [`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
3032 An annotation used to override the JSON Schema for a type.
3034 This is useful when you want to set a JSON Schema for a type that don't produce any JSON Schemas by default
3035 (e.g. [`Callable`][collections.abc.Callable]).
3037 If `mode` is set this will only apply to that schema generation mode, allowing you to set different JSON Schemas for validation and serialization.
3039 !!! note
3040 If the `WithJsonSchema` annotation is coupled with the [`Field()`][pydantic.Field] function, the behavior overriding will vary depending on the location:
3042 * If the [`Annotated`][typing.Annotated] metadata is specified at the "top-level" field, `Field()` metadata arguments
3043 (excluding [constraints](../concepts/fields.md#field-constraints)) such as `title` and `description` will be applied on
3044 top of the `WithJsonSchema`, no matter the order:
3046 ```python
3047 from typing import Annotated
3049 from pydantic import BaseModel, Field, WithJsonSchema
3051 class Model(BaseModel):
3052 field: Annotated[
3053 int,
3054 Field(title='My Field'),
3055 WithJsonSchema({'type': 'integer', 'extra': 'data'}),
3056 ]
3058 Model.model_json_schema()['properties']['field']
3059 #> {'type': 'integer', 'extra': 'data', 'title': 'My Field'}
3060 ```
3062 * If the [`Annotated`][typing.Annotated] metadata is specified on a specific inner type, `WithJsonSchema` will unconditionally
3063 override the JSON Schema:
3065 ```python
3066 from typing import Annotated
3068 from pydantic import BaseModel, Field, WithJsonSchema
3070 class Model(BaseModel):
3071 field: list[
3072 Annotated[
3073 int,
3074 Field(title='My Field'),
3075 WithJsonSchema({'type': 'integer', 'extra': 'data'}),
3076 ]
3077 ]
3079 Model.model_json_schema()['properties']['field']
3080 #> {'items': {'extra': 'data', 'type': 'integer'}, 'title': 'Field', 'type': 'array'}
3081 ```
3083 See also the documentation about [the annotated pattern](../concepts/fields.md#the-annotated-pattern).
3084 """
3086 json_schema: JsonSchemaValue | None 1jlmeabnqrifgskophcd
3087 mode: Literal['validation', 'serialization'] | None = None 1jlmeabnqrifgskophcd
3089 def __get_pydantic_json_schema__( 1jlmeabnqrifgskophcd
3090 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
3091 ) -> JsonSchemaValue:
3092 if self.mode is not None and self.mode != handler.mode: 1jlmeabnqrifgkophcd
3093 return handler(core_schema) 1jlmeabkophcd
3094 if self.json_schema is None: 1jlmeabnqrifgkophcd
3095 # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema
3096 raise PydanticOmit 1jlmeabnqrifgkophcd
3097 else:
3098 return self.json_schema.copy() 1jlmeabnqrifgkophcd
3100 def __hash__(self) -> int: 1jlmeabnqrifgskophcd
3101 return hash(self.mode) 1jlmeabnqrifgkophcd
3104class Examples: 1jlmeabnqrifgskophcd
3105 """Add examples to a JSON schema.
3107 If the JSON Schema already contains examples, the provided examples
3108 will be appended.
3110 If `mode` is set this will only apply to that schema generation mode,
3111 allowing you to add different examples for validation and serialization.
3112 """
3114 def __init__(self, examples: list[Any], mode: Literal['validation', 'serialization'] | None = None) -> None: 1jlmeabnqrifgskophcd
3115 self.examples = examples 1jlmeabnqrifgkophcd
3116 self.mode = mode 1jlmeabnqrifgkophcd
3118 def __get_pydantic_json_schema__( 1jlmeabnqrifgskophcd
3119 self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
3120 ) -> JsonSchemaValue:
3121 mode = self.mode or handler.mode 1jlmeabnqrifgkophcd
3122 json_schema = handler(core_schema) 1jlmeabnqrifgkophcd
3123 if mode != handler.mode: 3123 ↛ 3124line 3123 didn't jump to line 3124 because the condition on line 3123 was never true1jlmeabnqrifgkophcd
3124 return json_schema
3125 examples = json_schema.get('examples') 1jlmeabnqrifgkophcd
3126 if examples is None: 1jlmeabnqrifgkophcd
3127 json_schema['examples'] = to_jsonable_python(self.examples) 1jlmeabnqrifgkophcd
3128 elif isinstance(examples, list): 3128 ↛ 3131line 3128 didn't jump to line 3131 because the condition on line 3128 was always true1jlmeabnqrifgkophcd
3129 json_schema['examples'] = to_jsonable_python(examples + self.examples) 1jlmeabnqrifgkophcd
3131 return json_schema 1jlmeabnqrifgkophcd
3133 def __hash__(self) -> int: 1jlmeabnqrifgskophcd
3134 return hash(self.mode) 1jlmeabnqrifgkophcd
3137def _get_all_json_refs(item: Any) -> set[JsonRef]: 1jlmeabnqrifgskophcd
3138 """Get all the definitions references from a JSON schema."""
3139 refs: set[JsonRef] = set() 1jlmeabnqrifgkophcd
3140 stack = [item] 1jlmeabnqrifgkophcd
3142 while stack: 1jlmeabnqrifgkophcd
3143 current = stack.pop() 1jlmeabnqrifgkophcd
3144 if isinstance(current, dict): 1jlmeabnqrifgkophcd
3145 for key, value in current.items(): 1jlmeabnqrifgkophcd
3146 if key == 'examples' and isinstance(value, list): 1jlmeabnqrifgkophcd
3147 # Skip examples that may contain arbitrary values and references
3148 # (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
3149 # of type list is necessary to avoid skipping valid portions of the schema,
3150 # for instance when "examples" is used as a property key. A more robust solution
3151 # could be found, but would require more advanced JSON Schema parsing logic.
3152 continue 1jlmeabnqrifgkophcd
3153 if key == '$ref' and isinstance(value, str): 1jlmeabnqrifgkophcd
3154 refs.add(JsonRef(value)) 1jlmeabnqrifgkophcd
3155 elif isinstance(value, dict): 1jlmeabnqrifgkophcd
3156 stack.append(value) 1jlmeabnqrifgkophcd
3157 elif isinstance(value, list): 1jlmeabnqrifgkophcd
3158 stack.extend(value) 1jlmeabnqrifgkophcd
3159 elif isinstance(current, list): 1jlmeabnqrifgkophcd
3160 stack.extend(current) 1jlmeabnqrifgkophcd
3162 return refs 1jlmeabnqrifgkophcd
3165AnyType = TypeVar('AnyType') 1jlmeabnqrifgskophcd
3167if TYPE_CHECKING: 1jlmeabnqrifgskophcd
3168 SkipJsonSchema = Annotated[AnyType, ...]
3169else:
3171 @dataclasses.dataclass(slots=True) 1jlmeabnqrifgskophcd
3172 class SkipJsonSchema: 1jlmeabnqrifgskophcd
3173 """!!! abstract "Usage Documentation"
3174 [`SkipJsonSchema` Annotation](../concepts/json_schema.md#skipjsonschema-annotation)
3176 Add this as an annotation on a field to skip generating a JSON schema for that field.
3178 Example:
3179 ```python
3180 from pprint import pprint
3182 from pydantic import BaseModel
3183 from pydantic.json_schema import SkipJsonSchema
3185 class Model(BaseModel):
3186 a: int | None = None # (1)!
3187 b: int | SkipJsonSchema[None] = None # (2)!
3188 c: SkipJsonSchema[int | None] = None # (3)!
3190 pprint(Model.model_json_schema())
3191 '''
3192 {
3193 'properties': {
3194 'a': {
3195 'anyOf': [
3196 {'type': 'integer'},
3197 {'type': 'null'}
3198 ],
3199 'default': None,
3200 'title': 'A'
3201 },
3202 'b': {
3203 'default': None,
3204 'title': 'B',
3205 'type': 'integer'
3206 }
3207 },
3208 'title': 'Model',
3209 'type': 'object'
3210 }
3211 '''
3212 ```
3214 1. The integer and null types are both included in the schema for `a`.
3215 2. The integer type is the only type included in the schema for `b`.
3216 3. The entirety of the `c` field is omitted from the schema.
3217 """
3219 def __class_getitem__(cls, item: AnyType) -> AnyType: 1jlmeabnqrifgskophcd
3220 return Annotated[item, cls()] 1jlmeabnqrifgkophcd
3222 def __get_pydantic_json_schema__( 1jlmeabnqrifgskophcd
3223 self, core_schema: CoreSchema, handler: GetJsonSchemaHandler
3224 ) -> JsonSchemaValue:
3225 raise PydanticOmit 1jlmeabnqrifgkophcd
3227 def __hash__(self) -> int: 1jlmeabnqrifgskophcd
3228 return hash(type(self)) 1jlmeabnqrifgkophcd
3231def _get_class_config( 1jlmeabnqrifgskophcd
3232 schema: core_schema.ModelSchema | core_schema.DataclassSchema | core_schema.TypedDictSchema,
3233) -> ConfigDict | None:
3234 """Get the config of the class a model, dataclass or typed dictionary schema was built from."""
3235 if schema['type'] == 'model': 1jlmeabnqrifgkophcd
3236 return cast('type[BaseModel]', schema['cls']).model_config 1jlmeabnqrifgkophcd
3237 # If a (stdlib) dataclass or typed dictionary doesn't have config, the parent's config is used
3238 # (as during core schema generation), hence a default of `None`:
3239 if schema['type'] == 'dataclass': 1jlmeabnqrifgkophcd
3240 return getattr(schema['cls'], '__pydantic_config__', None) 1jlmeabnqrifgkophcd
3241 if (cls := schema.get('cls')) is not None: 1jlmeabnqrifgkophcd
3242 try: 1jlmeabnqrifgkophcd
3243 return _decorators.get_attribute_from_bases(cls, '__pydantic_config__') 1jlmeabnqrifgkophcd
3244 except AttributeError: 1jlmeabnqrifgkophcd
3245 pass 1jlmeabnqrifgkophcd
3246 return None 1jlmeabnqrifgkophcd
3249def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None: 1jlmeabnqrifgskophcd
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 ( 1jeabnifgkhcd
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) 1jlmeabnqrifgkophcd
3260 if _core_utils.is_function_with_inner_schema(schema): 1jlmeabnqrifgkophcd
3261 return _get_ser_schema_for_default_value(schema['schema']) 1jlmeabnqrifgkophcd
3264def _is_nullable_schema(schema: CoreSchemaOrField) -> bool: 1jlmeabnqrifgskophcd
3265 """Whether the schema is a `'nullable'` schema, possibly wrapped in default, validator function, chain,
3266 lax-or-strict and JSON-or-Python schemas.
3268 For the latter three, the same inner schema as the one used to generate the serialization JSON Schema
3269 is checked (see the corresponding `GenerateJsonSchema` methods).
3270 """
3271 if schema['type'] == 'default' or _core_utils.is_function_with_inner_schema(schema): 1jlmeabnqrifgkophcd
3272 return _is_nullable_schema(schema['schema']) 1jlmeabnqrifgkophcd
3273 if schema['type'] == 'chain': 1jlmeabnqrifgkophcd
3274 return _is_nullable_schema(schema['steps'][-1]) 1jlmeabnqrifgkophcd
3275 if schema['type'] == 'lax-or-strict': 1jlmeabnqrifgkophcd
3276 # See TODO in `GenerateJsonSchema.lax_or_strict_schema()`:
3277 return _is_nullable_schema(schema['strict_schema'] if schema.get('strict', False) else schema['lax_schema']) 1jlmeabnqrifgkophcd
3278 if schema['type'] == 'json-or-python': 1jlmeabnqrifgkophcd
3279 return _is_nullable_schema(schema['json_schema']) 1jlmeabnqrifgkophcd
3280 return schema['type'] == 'nullable' 1jlmeabnqrifgkophcd