選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

2696 行
113 KiB

  1. """!!! abstract "Usage Documentation"
  2. [JSON Schema](../concepts/json_schema.md)
  3. The `json_schema` module contains classes and functions to allow the way [JSON Schema](https://json-schema.org/)
  4. is generated to be customized.
  5. In general you shouldn't need to use this module directly; instead, you can use
  6. [`BaseModel.model_json_schema`][pydantic.BaseModel.model_json_schema] and
  7. [`TypeAdapter.json_schema`][pydantic.TypeAdapter.json_schema].
  8. """
  9. from __future__ import annotations as _annotations
  10. import dataclasses
  11. import inspect
  12. import math
  13. import os
  14. import re
  15. import warnings
  16. from collections import Counter, defaultdict
  17. from collections.abc import Hashable, Iterable, Sequence
  18. from copy import deepcopy
  19. from enum import Enum
  20. from re import Pattern
  21. from typing import (
  22. TYPE_CHECKING,
  23. Annotated,
  24. Any,
  25. Callable,
  26. Literal,
  27. NewType,
  28. TypeVar,
  29. Union,
  30. cast,
  31. overload,
  32. )
  33. import pydantic_core
  34. from pydantic_core import CoreSchema, PydanticOmit, core_schema, to_jsonable_python
  35. from pydantic_core.core_schema import ComputedField
  36. from typing_extensions import TypeAlias, assert_never, deprecated, final
  37. from typing_inspection.introspection import get_literal_values
  38. from pydantic.warnings import PydanticDeprecatedSince26, PydanticDeprecatedSince29
  39. from ._internal import (
  40. _config,
  41. _core_metadata,
  42. _core_utils,
  43. _decorators,
  44. _internal_dataclass,
  45. _mock_val_ser,
  46. _schema_generation_shared,
  47. )
  48. from .annotated_handlers import GetJsonSchemaHandler
  49. from .config import JsonDict, JsonValue
  50. from .errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError
  51. if TYPE_CHECKING:
  52. from . import ConfigDict
  53. from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField
  54. from ._internal._dataclasses import PydanticDataclass
  55. from ._internal._schema_generation_shared import GetJsonSchemaFunction
  56. from .main import BaseModel
  57. CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType]
  58. """
  59. A type alias for defined schema types that represents a union of
  60. `core_schema.CoreSchemaType` and
  61. `core_schema.CoreSchemaFieldType`.
  62. """
  63. JsonSchemaValue = dict[str, Any]
  64. """
  65. A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values.
  66. """
  67. JsonSchemaMode = Literal['validation', 'serialization']
  68. """
  69. A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'.
  70. For some types, the inputs to validation differ from the outputs of serialization. For example,
  71. computed fields will only be present when serializing, and should not be provided when
  72. validating. This flag provides a way to indicate whether you want the JSON schema required
  73. for validation inputs, or that will be matched by serialization outputs.
  74. """
  75. _MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'}
  76. JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default', 'skipped-discriminator']
  77. """
  78. A type alias representing the kinds of warnings that can be emitted during JSON schema generation.
  79. See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
  80. for more details.
  81. """
  82. class PydanticJsonSchemaWarning(UserWarning):
  83. """This class is used to emit warnings produced during JSON schema generation.
  84. See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
  85. [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message]
  86. methods for more details; these can be overridden to control warning behavior.
  87. """
  88. NoDefault = object()
  89. """A sentinel value used to indicate that no default value should be used when generating a JSON Schema
  90. for a core schema with a default value.
  91. """
  92. # ##### JSON Schema Generation #####
  93. DEFAULT_REF_TEMPLATE = '#/$defs/{model}'
  94. """The default format string used to generate reference names."""
  95. # There are three types of references relevant to building JSON schemas:
  96. # 1. core_schema "ref" values; these are not exposed as part of the JSON schema
  97. # * these might look like the fully qualified path of a model, its id, or something similar
  98. CoreRef = NewType('CoreRef', str)
  99. # 2. keys of the "definitions" object that will eventually go into the JSON schema
  100. # * by default, these look like "MyModel", though may change in the presence of collisions
  101. # * eventually, we may want to make it easier to modify the way these names are generated
  102. DefsRef = NewType('DefsRef', str)
  103. # 3. the values corresponding to the "$ref" key in the schema
  104. # * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"}
  105. JsonRef = NewType('JsonRef', str)
  106. CoreModeRef = tuple[CoreRef, JsonSchemaMode]
  107. JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable)
  108. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  109. class _DefinitionsRemapping:
  110. defs_remapping: dict[DefsRef, DefsRef]
  111. json_remapping: dict[JsonRef, JsonRef]
  112. @staticmethod
  113. def from_prioritized_choices(
  114. prioritized_choices: dict[DefsRef, list[DefsRef]],
  115. defs_to_json: dict[DefsRef, JsonRef],
  116. definitions: dict[DefsRef, JsonSchemaValue],
  117. ) -> _DefinitionsRemapping:
  118. """
  119. This function should produce a remapping that replaces complex DefsRef with the simpler ones from the
  120. prioritized_choices such that applying the name remapping would result in an equivalent JSON schema.
  121. """
  122. # We need to iteratively simplify the definitions until we reach a fixed point.
  123. # The reason for this is that outer definitions may reference inner definitions that get simplified
  124. # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified
  125. # the inner definitions.
  126. copied_definitions = deepcopy(definitions)
  127. definitions_schema = {'$defs': copied_definitions}
  128. for _iter in range(100): # prevent an infinite loop in the case of a bug, 100 iterations should be enough
  129. # For every possible remapped DefsRef, collect all schemas that that DefsRef might be used for:
  130. schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list)
  131. for defs_ref in copied_definitions:
  132. alternatives = prioritized_choices[defs_ref]
  133. for alternative in alternatives:
  134. schemas_for_alternatives[alternative].append(copied_definitions[defs_ref])
  135. # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef
  136. # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef.
  137. for defs_ref in schemas_for_alternatives:
  138. schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref])
  139. # Build the remapping
  140. defs_remapping: dict[DefsRef, DefsRef] = {}
  141. json_remapping: dict[JsonRef, JsonRef] = {}
  142. for original_defs_ref in definitions:
  143. alternatives = prioritized_choices[original_defs_ref]
  144. # Pick the first alternative that has only one schema, since that means there is no collision
  145. remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1)
  146. defs_remapping[original_defs_ref] = remapped_defs_ref
  147. json_remapping[defs_to_json[original_defs_ref]] = defs_to_json[remapped_defs_ref]
  148. remapping = _DefinitionsRemapping(defs_remapping, json_remapping)
  149. new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions})
  150. if definitions_schema == new_definitions_schema:
  151. # We've reached the fixed point
  152. return remapping
  153. definitions_schema = new_definitions_schema
  154. raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions')
  155. def remap_defs_ref(self, ref: DefsRef) -> DefsRef:
  156. return self.defs_remapping.get(ref, ref)
  157. def remap_json_ref(self, ref: JsonRef) -> JsonRef:
  158. return self.json_remapping.get(ref, ref)
  159. def remap_json_schema(self, schema: Any) -> Any:
  160. """
  161. Recursively update the JSON schema replacing all $refs
  162. """
  163. if isinstance(schema, str):
  164. # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings
  165. return self.remap_json_ref(JsonRef(schema))
  166. elif isinstance(schema, list):
  167. return [self.remap_json_schema(item) for item in schema]
  168. elif isinstance(schema, dict):
  169. for key, value in schema.items():
  170. if key == '$ref' and isinstance(value, str):
  171. schema['$ref'] = self.remap_json_ref(JsonRef(value))
  172. elif key == '$defs':
  173. schema['$defs'] = {
  174. self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
  175. for key, value in schema['$defs'].items()
  176. }
  177. else:
  178. schema[key] = self.remap_json_schema(value)
  179. return schema
  180. class GenerateJsonSchema:
  181. """!!! abstract "Usage Documentation"
  182. [Customizing the JSON Schema Generation Process](../concepts/json_schema.md#customizing-the-json-schema-generation-process)
  183. A class for generating JSON schemas.
  184. This class generates JSON schemas based on configured parameters. The default schema dialect
  185. is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema).
  186. The class uses `by_alias` to configure how fields with
  187. multiple names are handled and `ref_template` to format reference names.
  188. Attributes:
  189. schema_dialect: The JSON schema dialect used to generate the schema. See
  190. [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4)
  191. in the JSON Schema documentation for more information about dialects.
  192. ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will
  193. do nothing if its argument `kind` is in `ignored_warning_kinds`;
  194. this value can be modified on subclasses to easily control which warnings are emitted.
  195. by_alias: Whether to use field aliases when generating the schema.
  196. ref_template: The format string used when generating reference names.
  197. core_to_json_refs: A mapping of core refs to JSON refs.
  198. core_to_defs_refs: A mapping of core refs to definition refs.
  199. defs_to_core_refs: A mapping of definition refs to core refs.
  200. json_to_defs_refs: A mapping of JSON refs to definition refs.
  201. definitions: Definitions in the schema.
  202. Args:
  203. by_alias: Whether to use field aliases in the generated schemas.
  204. ref_template: The format string to use when generating reference names.
  205. Raises:
  206. JsonSchemaError: If the instance of the class is inadvertently reused after generating a schema.
  207. """
  208. schema_dialect = 'https://json-schema.org/draft/2020-12/schema'
  209. # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`;
  210. # this value can be modified on subclasses to easily control which warnings are emitted
  211. ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'}
  212. def __init__(self, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE):
  213. self.by_alias = by_alias
  214. self.ref_template = ref_template
  215. self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {}
  216. self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {}
  217. self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {}
  218. self.json_to_defs_refs: dict[JsonRef, DefsRef] = {}
  219. self.definitions: dict[DefsRef, JsonSchemaValue] = {}
  220. self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))
  221. self._mode: JsonSchemaMode = 'validation'
  222. # The following includes a mapping of a fully-unique defs ref choice to a list of preferred
  223. # alternatives, which are generally simpler, such as only including the class name.
  224. # At the end of schema generation, we use these to produce a JSON schema with more human-readable
  225. # definitions, which would also work better in a generated OpenAPI client, etc.
  226. self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {}
  227. self._collision_counter: dict[str, int] = defaultdict(int)
  228. self._collision_index: dict[str, int] = {}
  229. self._schema_type_to_method = self.build_schema_type_to_method()
  230. # When we encounter definitions we need to try to build them immediately
  231. # so that they are available schemas that reference them
  232. # But it's possible that CoreSchema was never going to be used
  233. # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing
  234. # the reference) so instead of failing altogether if we can't build a definition we
  235. # store the error raised and re-throw it if we end up needing that def
  236. self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {}
  237. # This changes to True after generating a schema, to prevent issues caused by accidental reuse
  238. # of a single instance of a schema generator
  239. self._used = False
  240. @property
  241. def _config(self) -> _config.ConfigWrapper:
  242. return self._config_wrapper_stack.tail
  243. @property
  244. def mode(self) -> JsonSchemaMode:
  245. if self._config.json_schema_mode_override is not None:
  246. return self._config.json_schema_mode_override
  247. else:
  248. return self._mode
  249. def build_schema_type_to_method(
  250. self,
  251. ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]:
  252. """Builds a dictionary mapping fields to methods for generating JSON schemas.
  253. Returns:
  254. A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method.
  255. Raises:
  256. TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type.
  257. """
  258. mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {}
  259. core_schema_types: list[CoreSchemaOrFieldType] = list(get_literal_values(CoreSchemaOrFieldType))
  260. for key in core_schema_types:
  261. method_name = f'{key.replace("-", "_")}_schema'
  262. try:
  263. mapping[key] = getattr(self, method_name)
  264. except AttributeError as e: # pragma: no cover
  265. if os.getenv('PYDANTIC_PRIVATE_ALLOW_UNHANDLED_SCHEMA_TYPES'):
  266. continue
  267. raise TypeError(
  268. f'No method for generating JsonSchema for core_schema.type={key!r} '
  269. f'(expected: {type(self).__name__}.{method_name})'
  270. ) from e
  271. return mapping
  272. def generate_definitions(
  273. self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]
  274. ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]:
  275. """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a
  276. mapping that links the input keys to the definition references.
  277. Args:
  278. inputs: A sequence of tuples, where:
  279. - The first element is a JSON schema key type.
  280. - The second element is the JSON mode: either 'validation' or 'serialization'.
  281. - The third element is a core schema.
  282. Returns:
  283. A tuple where:
  284. - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
  285. whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
  286. JsonRef references to definitions that are defined in the second returned element.)
  287. - The second element is a dictionary whose keys are definition references for the JSON schemas
  288. from the first returned element, and whose values are the actual JSON schema definitions.
  289. Raises:
  290. PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema.
  291. """
  292. if self._used:
  293. raise PydanticUserError(
  294. 'This JSON schema generator has already been used to generate a JSON schema. '
  295. f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
  296. code='json-schema-already-used',
  297. )
  298. for _, mode, schema in inputs:
  299. self._mode = mode
  300. self.generate_inner(schema)
  301. definitions_remapping = self._build_definitions_remapping()
  302. json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}
  303. for key, mode, schema in inputs:
  304. self._mode = mode
  305. json_schema = self.generate_inner(schema)
  306. json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema)
  307. json_schema = {'$defs': self.definitions}
  308. json_schema = definitions_remapping.remap_json_schema(json_schema)
  309. self._used = True
  310. return json_schemas_map, self.sort(json_schema['$defs']) # type: ignore
  311. def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue:
  312. """Generates a JSON schema for a specified schema in a specified mode.
  313. Args:
  314. schema: A Pydantic model.
  315. mode: The mode in which to generate the schema. Defaults to 'validation'.
  316. Returns:
  317. A JSON schema representing the specified schema.
  318. Raises:
  319. PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema.
  320. """
  321. self._mode = mode
  322. if self._used:
  323. raise PydanticUserError(
  324. 'This JSON schema generator has already been used to generate a JSON schema. '
  325. f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.',
  326. code='json-schema-already-used',
  327. )
  328. json_schema: JsonSchemaValue = self.generate_inner(schema)
  329. json_ref_counts = self.get_json_ref_counts(json_schema)
  330. ref = cast(JsonRef, json_schema.get('$ref'))
  331. while ref is not None: # may need to unpack multiple levels
  332. ref_json_schema = self.get_schema_from_definitions(ref)
  333. if json_ref_counts[ref] == 1 and ref_json_schema is not None and len(json_schema) == 1:
  334. # "Unpack" the ref since this is the only reference and there are no sibling keys
  335. json_schema = ref_json_schema.copy() # copy to prevent recursive dict reference
  336. json_ref_counts[ref] -= 1
  337. ref = cast(JsonRef, json_schema.get('$ref'))
  338. ref = None
  339. self._garbage_collect_definitions(json_schema)
  340. definitions_remapping = self._build_definitions_remapping()
  341. if self.definitions:
  342. json_schema['$defs'] = self.definitions
  343. json_schema = definitions_remapping.remap_json_schema(json_schema)
  344. # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding
  345. # this method and adding the following line after a call to super().generate(schema):
  346. # json_schema['$schema'] = self.schema_dialect
  347. self._used = True
  348. return self.sort(json_schema)
  349. def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: # noqa: C901
  350. """Generates a JSON schema for a given core schema.
  351. Args:
  352. schema: The given core schema.
  353. Returns:
  354. The generated JSON schema.
  355. TODO: the nested function definitions here seem like bad practice, I'd like to unpack these
  356. in a future PR. It'd be great if we could shorten the call stack a bit for JSON schema generation,
  357. and I think there's potential for that here.
  358. """
  359. # If a schema with the same CoreRef has been handled, just return a reference to it
  360. # Note that this assumes that it will _never_ be the case that the same CoreRef is used
  361. # on types that should have different JSON schemas
  362. if 'ref' in schema:
  363. core_ref = CoreRef(schema['ref']) # type: ignore[typeddict-item]
  364. core_mode_ref = (core_ref, self.mode)
  365. if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions:
  366. return {'$ref': self.core_to_json_refs[core_mode_ref]}
  367. def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  368. if 'ref' in core_schema:
  369. core_ref = CoreRef(core_schema['ref']) # type: ignore[typeddict-item]
  370. defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
  371. json_ref = JsonRef(ref_json_schema['$ref'])
  372. # Replace the schema if it's not a reference to itself
  373. # What we want to avoid is having the def be just a ref to itself
  374. # which is what would happen if we blindly assigned any
  375. if json_schema.get('$ref', None) != json_ref:
  376. self.definitions[defs_ref] = json_schema
  377. self._core_defs_invalid_for_json_schema.pop(defs_ref, None)
  378. json_schema = ref_json_schema
  379. return json_schema
  380. def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue:
  381. """Generate a JSON schema based on the input schema.
  382. Args:
  383. schema_or_field: The core schema to generate a JSON schema from.
  384. Returns:
  385. The generated JSON schema.
  386. Raises:
  387. TypeError: If an unexpected schema type is encountered.
  388. """
  389. # Generate the core-schema-type-specific bits of the schema generation:
  390. json_schema: JsonSchemaValue | None = None
  391. if self.mode == 'serialization' and 'serialization' in schema_or_field:
  392. # In this case, we skip the JSON Schema generation of the schema
  393. # and use the `'serialization'` schema instead (canonical example:
  394. # `Annotated[int, PlainSerializer(str)]`).
  395. ser_schema = schema_or_field['serialization'] # type: ignore
  396. json_schema = self.ser_schema(ser_schema)
  397. # It might be that the 'serialization'` is skipped depending on `when_used`.
  398. # This is only relevant for `nullable` schemas though, so we special case here.
  399. if (
  400. json_schema is not None
  401. and ser_schema.get('when_used') in ('unless-none', 'json-unless-none')
  402. and schema_or_field['type'] == 'nullable'
  403. ):
  404. json_schema = self.get_flattened_anyof([{'type': 'null'}, json_schema])
  405. if json_schema is None:
  406. if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field):
  407. generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']]
  408. json_schema = generate_for_schema_type(schema_or_field)
  409. else:
  410. raise TypeError(f'Unexpected schema type: schema={schema_or_field}')
  411. return json_schema
  412. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func)
  413. metadata = cast(_core_metadata.CoreMetadata, schema.get('metadata', {}))
  414. # TODO: I dislike that we have to wrap these basic dict updates in callables, is there any way around this?
  415. if js_updates := metadata.get('pydantic_js_updates'):
  416. def js_updates_handler_func(
  417. schema_or_field: CoreSchemaOrField,
  418. current_handler: GetJsonSchemaHandler = current_handler,
  419. ) -> JsonSchemaValue:
  420. json_schema = {**current_handler(schema_or_field), **js_updates}
  421. return json_schema
  422. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_updates_handler_func)
  423. if js_extra := metadata.get('pydantic_js_extra'):
  424. def js_extra_handler_func(
  425. schema_or_field: CoreSchemaOrField,
  426. current_handler: GetJsonSchemaHandler = current_handler,
  427. ) -> JsonSchemaValue:
  428. json_schema = current_handler(schema_or_field)
  429. if isinstance(js_extra, dict):
  430. json_schema.update(to_jsonable_python(js_extra))
  431. elif callable(js_extra):
  432. # similar to typing issue in _update_class_schema when we're working with callable js extra
  433. js_extra(json_schema) # type: ignore
  434. return json_schema
  435. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, js_extra_handler_func)
  436. for js_modify_function in metadata.get('pydantic_js_functions', ()):
  437. def new_handler_func(
  438. schema_or_field: CoreSchemaOrField,
  439. current_handler: GetJsonSchemaHandler = current_handler,
  440. js_modify_function: GetJsonSchemaFunction = js_modify_function,
  441. ) -> JsonSchemaValue:
  442. json_schema = js_modify_function(schema_or_field, current_handler)
  443. if _core_utils.is_core_schema(schema_or_field):
  444. json_schema = populate_defs(schema_or_field, json_schema)
  445. original_schema = current_handler.resolve_ref_schema(json_schema)
  446. ref = json_schema.pop('$ref', None)
  447. if ref and json_schema:
  448. original_schema.update(json_schema)
  449. return original_schema
  450. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
  451. for js_modify_function in metadata.get('pydantic_js_annotation_functions', ()):
  452. def new_handler_func(
  453. schema_or_field: CoreSchemaOrField,
  454. current_handler: GetJsonSchemaHandler = current_handler,
  455. js_modify_function: GetJsonSchemaFunction = js_modify_function,
  456. ) -> JsonSchemaValue:
  457. return js_modify_function(schema_or_field, current_handler)
  458. current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func)
  459. json_schema = current_handler(schema)
  460. if _core_utils.is_core_schema(schema):
  461. json_schema = populate_defs(schema, json_schema)
  462. return json_schema
  463. def sort(self, value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue:
  464. """Override this method to customize the sorting of the JSON schema (e.g., don't sort at all, sort all keys unconditionally, etc.)
  465. By default, alphabetically sort the keys in the JSON schema, skipping the 'properties' and 'default' keys to preserve field definition order.
  466. This sort is recursive, so it will sort all nested dictionaries as well.
  467. """
  468. sorted_dict: dict[str, JsonSchemaValue] = {}
  469. keys = value.keys()
  470. if parent_key not in ('properties', 'default'):
  471. keys = sorted(keys)
  472. for key in keys:
  473. sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
  474. return sorted_dict
  475. def _sort_recursive(self, value: Any, parent_key: str | None = None) -> Any:
  476. """Recursively sort a JSON schema value."""
  477. if isinstance(value, dict):
  478. sorted_dict: dict[str, JsonSchemaValue] = {}
  479. keys = value.keys()
  480. if parent_key not in ('properties', 'default'):
  481. keys = sorted(keys)
  482. for key in keys:
  483. sorted_dict[key] = self._sort_recursive(value[key], parent_key=key)
  484. return sorted_dict
  485. elif isinstance(value, list):
  486. sorted_list: list[JsonSchemaValue] = []
  487. for item in value:
  488. sorted_list.append(self._sort_recursive(item, parent_key))
  489. return sorted_list
  490. else:
  491. return value
  492. # ### Schema generation methods
  493. def invalid_schema(self, schema: core_schema.InvalidSchema) -> JsonSchemaValue:
  494. """Placeholder - should never be called."""
  495. raise RuntimeError('Cannot generate schema for invalid_schema. This is a bug! Please report it.')
  496. def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue:
  497. """Generates a JSON schema that matches any value.
  498. Args:
  499. schema: The core schema.
  500. Returns:
  501. The generated JSON schema.
  502. """
  503. return {}
  504. def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue:
  505. """Generates a JSON schema that matches `None`.
  506. Args:
  507. schema: The core schema.
  508. Returns:
  509. The generated JSON schema.
  510. """
  511. return {'type': 'null'}
  512. def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue:
  513. """Generates a JSON schema that matches a bool value.
  514. Args:
  515. schema: The core schema.
  516. Returns:
  517. The generated JSON schema.
  518. """
  519. return {'type': 'boolean'}
  520. def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue:
  521. """Generates a JSON schema that matches an int value.
  522. Args:
  523. schema: The core schema.
  524. Returns:
  525. The generated JSON schema.
  526. """
  527. json_schema: dict[str, Any] = {'type': 'integer'}
  528. self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
  529. json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
  530. return json_schema
  531. def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue:
  532. """Generates a JSON schema that matches a float value.
  533. Args:
  534. schema: The core schema.
  535. Returns:
  536. The generated JSON schema.
  537. """
  538. json_schema: dict[str, Any] = {'type': 'number'}
  539. self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric)
  540. json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}}
  541. return json_schema
  542. def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
  543. """Generates a JSON schema that matches a decimal value.
  544. Args:
  545. schema: The core schema.
  546. Returns:
  547. The generated JSON schema.
  548. """
  549. json_schema = self.str_schema(core_schema.str_schema())
  550. if self.mode == 'validation':
  551. multiple_of = schema.get('multiple_of')
  552. le = schema.get('le')
  553. ge = schema.get('ge')
  554. lt = schema.get('lt')
  555. gt = schema.get('gt')
  556. json_schema = {
  557. 'anyOf': [
  558. self.float_schema(
  559. core_schema.float_schema(
  560. allow_inf_nan=schema.get('allow_inf_nan'),
  561. multiple_of=None if multiple_of is None else float(multiple_of),
  562. le=None if le is None else float(le),
  563. ge=None if ge is None else float(ge),
  564. lt=None if lt is None else float(lt),
  565. gt=None if gt is None else float(gt),
  566. )
  567. ),
  568. json_schema,
  569. ],
  570. }
  571. return json_schema
  572. def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue:
  573. """Generates a JSON schema that matches a string value.
  574. Args:
  575. schema: The core schema.
  576. Returns:
  577. The generated JSON schema.
  578. """
  579. json_schema = {'type': 'string'}
  580. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  581. if isinstance(json_schema.get('pattern'), Pattern):
  582. # TODO: should we add regex flags to the pattern?
  583. json_schema['pattern'] = json_schema.get('pattern').pattern # type: ignore
  584. return json_schema
  585. def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue:
  586. """Generates a JSON schema that matches a bytes value.
  587. Args:
  588. schema: The core schema.
  589. Returns:
  590. The generated JSON schema.
  591. """
  592. json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'}
  593. self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
  594. return json_schema
  595. def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue:
  596. """Generates a JSON schema that matches a date value.
  597. Args:
  598. schema: The core schema.
  599. Returns:
  600. The generated JSON schema.
  601. """
  602. return {'type': 'string', 'format': 'date'}
  603. def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:
  604. """Generates a JSON schema that matches a time value.
  605. Args:
  606. schema: The core schema.
  607. Returns:
  608. The generated JSON schema.
  609. """
  610. return {'type': 'string', 'format': 'time'}
  611. def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:
  612. """Generates a JSON schema that matches a datetime value.
  613. Args:
  614. schema: The core schema.
  615. Returns:
  616. The generated JSON schema.
  617. """
  618. return {'type': 'string', 'format': 'date-time'}
  619. def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:
  620. """Generates a JSON schema that matches a timedelta value.
  621. Args:
  622. schema: The core schema.
  623. Returns:
  624. The generated JSON schema.
  625. """
  626. if self._config.ser_json_timedelta == 'float':
  627. return {'type': 'number'}
  628. return {'type': 'string', 'format': 'duration'}
  629. def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
  630. """Generates a JSON schema that matches a literal value.
  631. Args:
  632. schema: The core schema.
  633. Returns:
  634. The generated JSON schema.
  635. """
  636. expected = [to_jsonable_python(v.value if isinstance(v, Enum) else v) for v in schema['expected']]
  637. result: dict[str, Any] = {}
  638. if len(expected) == 1:
  639. result['const'] = expected[0]
  640. else:
  641. result['enum'] = expected
  642. types = {type(e) for e in expected}
  643. if types == {str}:
  644. result['type'] = 'string'
  645. elif types == {int}:
  646. result['type'] = 'integer'
  647. elif types == {float}:
  648. result['type'] = 'number'
  649. elif types == {bool}:
  650. result['type'] = 'boolean'
  651. elif types == {list}:
  652. result['type'] = 'array'
  653. elif types == {type(None)}:
  654. result['type'] = 'null'
  655. return result
  656. def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue:
  657. """Generates a JSON schema that matches an Enum value.
  658. Args:
  659. schema: The core schema.
  660. Returns:
  661. The generated JSON schema.
  662. """
  663. enum_type = schema['cls']
  664. description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__)
  665. if (
  666. description == 'An enumeration.'
  667. ): # This is the default value provided by enum.EnumMeta.__new__; don't use it
  668. description = None
  669. result: dict[str, Any] = {'title': enum_type.__name__, 'description': description}
  670. result = {k: v for k, v in result.items() if v is not None}
  671. expected = [to_jsonable_python(v.value) for v in schema['members']]
  672. result['enum'] = expected
  673. types = {type(e) for e in expected}
  674. if isinstance(enum_type, str) or types == {str}:
  675. result['type'] = 'string'
  676. elif isinstance(enum_type, int) or types == {int}:
  677. result['type'] = 'integer'
  678. elif isinstance(enum_type, float) or types == {float}:
  679. result['type'] = 'number'
  680. elif types == {bool}:
  681. result['type'] = 'boolean'
  682. elif types == {list}:
  683. result['type'] = 'array'
  684. return result
  685. def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue:
  686. """Handles JSON schema generation for a core schema that checks if a value is an instance of a class.
  687. Unless overridden in a subclass, this raises an error.
  688. Args:
  689. schema: The core schema.
  690. Returns:
  691. The generated JSON schema.
  692. """
  693. return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})')
  694. def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue:
  695. """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class.
  696. For backwards compatibility with v1, this does not raise an error, but can be overridden to change this.
  697. Args:
  698. schema: The core schema.
  699. Returns:
  700. The generated JSON schema.
  701. """
  702. # Note: This is for compatibility with V1; you can override if you want different behavior.
  703. return {}
  704. def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue:
  705. """Generates a JSON schema that matches a callable value.
  706. Unless overridden in a subclass, this raises an error.
  707. Args:
  708. schema: The core schema.
  709. Returns:
  710. The generated JSON schema.
  711. """
  712. return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema')
  713. def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue:
  714. """Returns a schema that matches a list schema.
  715. Args:
  716. schema: The core schema.
  717. Returns:
  718. The generated JSON schema.
  719. """
  720. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  721. json_schema = {'type': 'array', 'items': items_schema}
  722. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  723. return json_schema
  724. @deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None)
  725. @final
  726. def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  727. """Replaced by `tuple_schema`."""
  728. warnings.warn(
  729. '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.',
  730. PydanticDeprecatedSince26,
  731. stacklevel=2,
  732. )
  733. return self.tuple_schema(schema)
  734. @deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None)
  735. @final
  736. def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  737. """Replaced by `tuple_schema`."""
  738. warnings.warn(
  739. '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.',
  740. PydanticDeprecatedSince26,
  741. stacklevel=2,
  742. )
  743. return self.tuple_schema(schema)
  744. def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue:
  745. """Generates a JSON schema that matches a tuple schema e.g. `tuple[int,
  746. str, bool]` or `tuple[int, ...]`.
  747. Args:
  748. schema: The core schema.
  749. Returns:
  750. The generated JSON schema.
  751. """
  752. json_schema: JsonSchemaValue = {'type': 'array'}
  753. if 'variadic_item_index' in schema:
  754. variadic_item_index = schema['variadic_item_index']
  755. if variadic_item_index > 0:
  756. json_schema['minItems'] = variadic_item_index
  757. json_schema['prefixItems'] = [
  758. self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index]
  759. ]
  760. if variadic_item_index + 1 == len(schema['items_schema']):
  761. # if the variadic item is the last item, then represent it faithfully
  762. json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index])
  763. else:
  764. # otherwise, 'items' represents the schema for the variadic
  765. # item plus the suffix, so just allow anything for simplicity
  766. # for now
  767. json_schema['items'] = True
  768. else:
  769. prefixItems = [self.generate_inner(item) for item in schema['items_schema']]
  770. if prefixItems:
  771. json_schema['prefixItems'] = prefixItems
  772. json_schema['minItems'] = len(prefixItems)
  773. json_schema['maxItems'] = len(prefixItems)
  774. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  775. return json_schema
  776. def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue:
  777. """Generates a JSON schema that matches a set schema.
  778. Args:
  779. schema: The core schema.
  780. Returns:
  781. The generated JSON schema.
  782. """
  783. return self._common_set_schema(schema)
  784. def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue:
  785. """Generates a JSON schema that matches a frozenset schema.
  786. Args:
  787. schema: The core schema.
  788. Returns:
  789. The generated JSON schema.
  790. """
  791. return self._common_set_schema(schema)
  792. def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue:
  793. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  794. json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema}
  795. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  796. return json_schema
  797. def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue:
  798. """Returns a JSON schema that represents the provided GeneratorSchema.
  799. Args:
  800. schema: The schema.
  801. Returns:
  802. The generated JSON schema.
  803. """
  804. items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema'])
  805. json_schema = {'type': 'array', 'items': items_schema}
  806. self.update_with_validations(json_schema, schema, self.ValidationsMapping.array)
  807. return json_schema
  808. def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue:
  809. """Generates a JSON schema that matches a dict schema.
  810. Args:
  811. schema: The core schema.
  812. Returns:
  813. The generated JSON schema.
  814. """
  815. json_schema: JsonSchemaValue = {'type': 'object'}
  816. keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {}
  817. if '$ref' not in keys_schema:
  818. keys_pattern = keys_schema.pop('pattern', None)
  819. # Don't give a title to patternProperties/propertyNames:
  820. keys_schema.pop('title', None)
  821. else:
  822. # Here, we assume that if the keys schema is a definition reference,
  823. # it can't be a simple string core schema (and thus no pattern can exist).
  824. # However, this is only in practice (in theory, a definition reference core
  825. # schema could be generated for a simple string schema).
  826. # Note that we avoid calling `self.resolve_ref_schema`, as it might not exist yet.
  827. keys_pattern = None
  828. values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {}
  829. # don't give a title to additionalProperties:
  830. values_schema.pop('title', None)
  831. if values_schema or keys_pattern is not None:
  832. if keys_pattern is None:
  833. json_schema['additionalProperties'] = values_schema
  834. else:
  835. json_schema['patternProperties'] = {keys_pattern: values_schema}
  836. else: # for `dict[str, Any]`, we allow any key and any value, since `str` is the default key type
  837. json_schema['additionalProperties'] = True
  838. if (
  839. # The len check indicates that constraints are probably present:
  840. (keys_schema.get('type') == 'string' and len(keys_schema) > 1)
  841. # If this is a definition reference schema, it most likely has constraints:
  842. or '$ref' in keys_schema
  843. ):
  844. keys_schema.pop('type', None)
  845. json_schema['propertyNames'] = keys_schema
  846. self.update_with_validations(json_schema, schema, self.ValidationsMapping.object)
  847. return json_schema
  848. def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue:
  849. """Generates a JSON schema that matches a function-before schema.
  850. Args:
  851. schema: The core schema.
  852. Returns:
  853. The generated JSON schema.
  854. """
  855. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  856. return self.generate_inner(input_schema)
  857. return self.generate_inner(schema['schema'])
  858. def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue:
  859. """Generates a JSON schema that matches a function-after schema.
  860. Args:
  861. schema: The core schema.
  862. Returns:
  863. The generated JSON schema.
  864. """
  865. return self.generate_inner(schema['schema'])
  866. def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue:
  867. """Generates a JSON schema that matches a function-plain schema.
  868. Args:
  869. schema: The core schema.
  870. Returns:
  871. The generated JSON schema.
  872. """
  873. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  874. return self.generate_inner(input_schema)
  875. return self.handle_invalid_for_json_schema(
  876. schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})'
  877. )
  878. def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue:
  879. """Generates a JSON schema that matches a function-wrap schema.
  880. Args:
  881. schema: The core schema.
  882. Returns:
  883. The generated JSON schema.
  884. """
  885. if self.mode == 'validation' and (input_schema := schema.get('json_schema_input_schema')):
  886. return self.generate_inner(input_schema)
  887. return self.generate_inner(schema['schema'])
  888. def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
  889. """Generates a JSON schema that matches a schema with a default value.
  890. Args:
  891. schema: The core schema.
  892. Returns:
  893. The generated JSON schema.
  894. """
  895. json_schema = self.generate_inner(schema['schema'])
  896. default = self.get_default_value(schema)
  897. if default is NoDefault:
  898. return json_schema
  899. # we reflect the application of custom plain, no-info serializers to defaults for
  900. # JSON Schemas viewed in serialization mode:
  901. # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208
  902. if (
  903. self.mode == 'serialization'
  904. and (ser_schema := schema['schema'].get('serialization'))
  905. and (ser_func := ser_schema.get('function'))
  906. and ser_schema.get('type') == 'function-plain'
  907. and not ser_schema.get('info_arg')
  908. and not (default is None and ser_schema.get('when_used') in ('unless-none', 'json-unless-none'))
  909. ):
  910. try:
  911. default = ser_func(default) # type: ignore
  912. except Exception:
  913. # It might be that the provided default needs to be validated (read: parsed) first
  914. # (assuming `validate_default` is enabled). However, we can't perform
  915. # such validation during JSON Schema generation so we don't support
  916. # this pattern for now.
  917. # (One example is when using `foo: ByteSize = '1MB'`, which validates and
  918. # serializes as an int. In this case, `ser_func` is `int` and `int('1MB')` fails).
  919. self.emit_warning(
  920. 'non-serializable-default',
  921. f'Unable to serialize value {default!r} with the plain serializer; excluding default from JSON schema',
  922. )
  923. return json_schema
  924. try:
  925. encoded_default = self.encode_default(default)
  926. except pydantic_core.PydanticSerializationError:
  927. self.emit_warning(
  928. 'non-serializable-default',
  929. f'Default value {default} is not JSON serializable; excluding default from JSON schema',
  930. )
  931. # Return the inner schema, as though there was no default
  932. return json_schema
  933. json_schema['default'] = encoded_default
  934. return json_schema
  935. def get_default_value(self, schema: core_schema.WithDefaultSchema) -> Any:
  936. """Get the default value to be used when generating a JSON Schema for a core schema with a default.
  937. The default implementation is to use the statically defined default value. This method can be overridden
  938. if you want to make use of the default factory.
  939. Args:
  940. schema: The `'with-default'` core schema.
  941. Returns:
  942. The default value to use, or [`NoDefault`][pydantic.json_schema.NoDefault] if no default
  943. value is available.
  944. """
  945. return schema.get('default', NoDefault)
  946. def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue:
  947. """Generates a JSON schema that matches a schema that allows null values.
  948. Args:
  949. schema: The core schema.
  950. Returns:
  951. The generated JSON schema.
  952. """
  953. null_schema = {'type': 'null'}
  954. inner_json_schema = self.generate_inner(schema['schema'])
  955. if inner_json_schema == null_schema:
  956. return null_schema
  957. else:
  958. # Thanks to the equality check against `null_schema` above, I think 'oneOf' would also be valid here;
  959. # I'll use 'anyOf' for now, but it could be changed it if it would work better with some external tooling
  960. return self.get_flattened_anyof([inner_json_schema, null_schema])
  961. def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue:
  962. """Generates a JSON schema that matches a schema that allows values matching any of the given schemas.
  963. Args:
  964. schema: The core schema.
  965. Returns:
  966. The generated JSON schema.
  967. """
  968. generated: list[JsonSchemaValue] = []
  969. choices = schema['choices']
  970. for choice in choices:
  971. # choice will be a tuple if an explicit label was provided
  972. choice_schema = choice[0] if isinstance(choice, tuple) else choice
  973. try:
  974. generated.append(self.generate_inner(choice_schema))
  975. except PydanticOmit:
  976. continue
  977. except PydanticInvalidForJsonSchema as exc:
  978. self.emit_warning('skipped-choice', exc.message)
  979. if len(generated) == 1:
  980. return generated[0]
  981. return self.get_flattened_anyof(generated)
  982. def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue:
  983. """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where
  984. the schemas are tagged with a discriminator field that indicates which schema should be used to validate
  985. the value.
  986. Args:
  987. schema: The core schema.
  988. Returns:
  989. The generated JSON schema.
  990. """
  991. generated: dict[str, JsonSchemaValue] = {}
  992. for k, v in schema['choices'].items():
  993. if isinstance(k, Enum):
  994. k = k.value
  995. try:
  996. # Use str(k) since keys must be strings for json; while not technically correct,
  997. # it's the closest that can be represented in valid JSON
  998. generated[str(k)] = self.generate_inner(v).copy()
  999. except PydanticOmit:
  1000. continue
  1001. except PydanticInvalidForJsonSchema as exc:
  1002. self.emit_warning('skipped-choice', exc.message)
  1003. one_of_choices = _deduplicate_schemas(generated.values())
  1004. json_schema: JsonSchemaValue = {'oneOf': one_of_choices}
  1005. # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema
  1006. openapi_discriminator = self._extract_discriminator(schema, one_of_choices)
  1007. if openapi_discriminator is not None:
  1008. json_schema['discriminator'] = {
  1009. 'propertyName': openapi_discriminator,
  1010. 'mapping': {k: v.get('$ref', v) for k, v in generated.items()},
  1011. }
  1012. return json_schema
  1013. def _extract_discriminator(
  1014. self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict]
  1015. ) -> str | None:
  1016. """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final
  1017. schema."""
  1018. openapi_discriminator: str | None = None
  1019. if isinstance(schema['discriminator'], str):
  1020. return schema['discriminator']
  1021. if isinstance(schema['discriminator'], list):
  1022. # If the discriminator is a single item list containing a string, that is equivalent to the string case
  1023. if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str):
  1024. return schema['discriminator'][0]
  1025. # When an alias is used that is different from the field name, the discriminator will be a list of single
  1026. # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is
  1027. # more than one possible attribute, and looks for whether a single alias choice is present as a documented
  1028. # property on all choices. If so, that property will be used as the OpenAPI discriminator.
  1029. for alias_path in schema['discriminator']:
  1030. if not isinstance(alias_path, list):
  1031. break # this means that the discriminator is not a list of alias paths
  1032. if len(alias_path) != 1:
  1033. continue # this means that the "alias" does not represent a single field
  1034. alias = alias_path[0]
  1035. if not isinstance(alias, str):
  1036. continue # this means that the "alias" does not represent a field
  1037. alias_is_present_on_all_choices = True
  1038. for choice in one_of_choices:
  1039. try:
  1040. choice = self.resolve_ref_schema(choice)
  1041. except RuntimeError as exc:
  1042. # TODO: fixme - this is a workaround for the fact that we can't always resolve refs
  1043. # for tagged union choices at this point in the schema gen process, we might need to do
  1044. # another pass at the end like we do for core schemas
  1045. self.emit_warning('skipped-discriminator', str(exc))
  1046. choice = {}
  1047. properties = choice.get('properties', {})
  1048. if not isinstance(properties, dict) or alias not in properties:
  1049. alias_is_present_on_all_choices = False
  1050. break
  1051. if alias_is_present_on_all_choices:
  1052. openapi_discriminator = alias
  1053. break
  1054. return openapi_discriminator
  1055. def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue:
  1056. """Generates a JSON schema that matches a core_schema.ChainSchema.
  1057. When generating a schema for validation, we return the validation JSON schema for the first step in the chain.
  1058. For serialization, we return the serialization JSON schema for the last step in the chain.
  1059. Args:
  1060. schema: The core schema.
  1061. Returns:
  1062. The generated JSON schema.
  1063. """
  1064. step_index = 0 if self.mode == 'validation' else -1 # use first step for validation, last for serialization
  1065. return self.generate_inner(schema['steps'][step_index])
  1066. def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue:
  1067. """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the
  1068. strict schema.
  1069. Args:
  1070. schema: The core schema.
  1071. Returns:
  1072. The generated JSON schema.
  1073. """
  1074. # TODO: Need to read the default value off of model config or whatever
  1075. use_strict = schema.get('strict', False) # TODO: replace this default False
  1076. # If your JSON schema fails to generate it is probably
  1077. # because one of the following two branches failed.
  1078. if use_strict:
  1079. return self.generate_inner(schema['strict_schema'])
  1080. else:
  1081. return self.generate_inner(schema['lax_schema'])
  1082. def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue:
  1083. """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the
  1084. Python schema.
  1085. The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override
  1086. this method.
  1087. Args:
  1088. schema: The core schema.
  1089. Returns:
  1090. The generated JSON schema.
  1091. """
  1092. return self.generate_inner(schema['json_schema'])
  1093. def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue:
  1094. """Generates a JSON schema that matches a schema that defines a typed dict.
  1095. Args:
  1096. schema: The core schema.
  1097. Returns:
  1098. The generated JSON schema.
  1099. """
  1100. total = schema.get('total', True)
  1101. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1102. (name, self.field_is_required(field, total), field)
  1103. for name, field in schema['fields'].items()
  1104. if self.field_is_present(field)
  1105. ]
  1106. if self.mode == 'serialization':
  1107. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1108. cls = schema.get('cls')
  1109. config = _get_typed_dict_config(cls)
  1110. with self._config_wrapper_stack.push(config):
  1111. json_schema = self._named_required_fields_schema(named_required_fields)
  1112. if cls is not None:
  1113. self._update_class_schema(json_schema, cls, config)
  1114. else:
  1115. extra = config.get('extra')
  1116. if extra == 'forbid':
  1117. json_schema['additionalProperties'] = False
  1118. elif extra == 'allow':
  1119. json_schema['additionalProperties'] = True
  1120. return json_schema
  1121. @staticmethod
  1122. def _name_required_computed_fields(
  1123. computed_fields: list[ComputedField],
  1124. ) -> list[tuple[str, bool, core_schema.ComputedField]]:
  1125. return [(field['property_name'], True, field) for field in computed_fields]
  1126. def _named_required_fields_schema(
  1127. self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]]
  1128. ) -> JsonSchemaValue:
  1129. properties: dict[str, JsonSchemaValue] = {}
  1130. required_fields: list[str] = []
  1131. for name, required, field in named_required_fields:
  1132. if self.by_alias:
  1133. name = self._get_alias_name(field, name)
  1134. try:
  1135. field_json_schema = self.generate_inner(field).copy()
  1136. except PydanticOmit:
  1137. continue
  1138. if 'title' not in field_json_schema and self.field_title_should_be_set(field):
  1139. title = self.get_title_from_name(name)
  1140. field_json_schema['title'] = title
  1141. field_json_schema = self.handle_ref_overrides(field_json_schema)
  1142. properties[name] = field_json_schema
  1143. if required:
  1144. required_fields.append(name)
  1145. json_schema = {'type': 'object', 'properties': properties}
  1146. if required_fields:
  1147. json_schema['required'] = required_fields
  1148. return json_schema
  1149. def _get_alias_name(self, field: CoreSchemaField, name: str) -> str:
  1150. if field['type'] == 'computed-field':
  1151. alias: Any = field.get('alias', name)
  1152. elif self.mode == 'validation':
  1153. alias = field.get('validation_alias', name)
  1154. else:
  1155. alias = field.get('serialization_alias', name)
  1156. if isinstance(alias, str):
  1157. name = alias
  1158. elif isinstance(alias, list):
  1159. alias = cast('list[str] | str', alias)
  1160. for path in alias:
  1161. if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str):
  1162. # Use the first valid single-item string path; the code that constructs the alias array
  1163. # should ensure the first such item is what belongs in the JSON schema
  1164. name = path[0]
  1165. break
  1166. else:
  1167. assert_never(alias)
  1168. return name
  1169. def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue:
  1170. """Generates a JSON schema that matches a schema that defines a typed dict field.
  1171. Args:
  1172. schema: The core schema.
  1173. Returns:
  1174. The generated JSON schema.
  1175. """
  1176. return self.generate_inner(schema['schema'])
  1177. def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue:
  1178. """Generates a JSON schema that matches a schema that defines a dataclass field.
  1179. Args:
  1180. schema: The core schema.
  1181. Returns:
  1182. The generated JSON schema.
  1183. """
  1184. return self.generate_inner(schema['schema'])
  1185. def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue:
  1186. """Generates a JSON schema that matches a schema that defines a model field.
  1187. Args:
  1188. schema: The core schema.
  1189. Returns:
  1190. The generated JSON schema.
  1191. """
  1192. return self.generate_inner(schema['schema'])
  1193. def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue:
  1194. """Generates a JSON schema that matches a schema that defines a computed field.
  1195. Args:
  1196. schema: The core schema.
  1197. Returns:
  1198. The generated JSON schema.
  1199. """
  1200. return self.generate_inner(schema['return_schema'])
  1201. def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
  1202. """Generates a JSON schema that matches a schema that defines a model.
  1203. Args:
  1204. schema: The core schema.
  1205. Returns:
  1206. The generated JSON schema.
  1207. """
  1208. # We do not use schema['model'].model_json_schema() here
  1209. # because it could lead to inconsistent refs handling, etc.
  1210. cls = cast('type[BaseModel]', schema['cls'])
  1211. config = cls.model_config
  1212. with self._config_wrapper_stack.push(config):
  1213. json_schema = self.generate_inner(schema['schema'])
  1214. self._update_class_schema(json_schema, cls, config)
  1215. return json_schema
  1216. def _update_class_schema(self, json_schema: JsonSchemaValue, cls: type[Any], config: ConfigDict) -> None:
  1217. """Update json_schema with the following, extracted from `config` and `cls`:
  1218. * title
  1219. * description
  1220. * additional properties
  1221. * json_schema_extra
  1222. * deprecated
  1223. Done in place, hence there's no return value as the original json_schema is mutated.
  1224. No ref resolving is involved here, as that's not appropriate for simple updates.
  1225. """
  1226. from .main import BaseModel
  1227. from .root_model import RootModel
  1228. if (config_title := config.get('title')) is not None:
  1229. json_schema.setdefault('title', config_title)
  1230. elif model_title_generator := config.get('model_title_generator'):
  1231. title = model_title_generator(cls)
  1232. if not isinstance(title, str):
  1233. raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')
  1234. json_schema.setdefault('title', title)
  1235. if 'title' not in json_schema:
  1236. json_schema['title'] = cls.__name__
  1237. # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default
  1238. docstring = None if cls is BaseModel or dataclasses.is_dataclass(cls) else cls.__doc__
  1239. if docstring:
  1240. json_schema.setdefault('description', inspect.cleandoc(docstring))
  1241. elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):
  1242. json_schema.setdefault('description', root_description)
  1243. extra = config.get('extra')
  1244. if 'additionalProperties' not in json_schema:
  1245. if extra == 'allow':
  1246. json_schema['additionalProperties'] = True
  1247. elif extra == 'forbid':
  1248. json_schema['additionalProperties'] = False
  1249. json_schema_extra = config.get('json_schema_extra')
  1250. if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:
  1251. root_json_schema_extra = cls.model_fields['root'].json_schema_extra
  1252. if json_schema_extra and root_json_schema_extra:
  1253. raise ValueError(
  1254. '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'
  1255. ' field must not be set simultaneously'
  1256. )
  1257. if root_json_schema_extra:
  1258. json_schema_extra = root_json_schema_extra
  1259. if isinstance(json_schema_extra, (staticmethod, classmethod)):
  1260. # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable
  1261. json_schema_extra = json_schema_extra.__get__(cls)
  1262. if isinstance(json_schema_extra, dict):
  1263. json_schema.update(json_schema_extra)
  1264. elif callable(json_schema_extra):
  1265. # FIXME: why are there type ignores here? We support two signatures for json_schema_extra callables...
  1266. if len(inspect.signature(json_schema_extra).parameters) > 1:
  1267. json_schema_extra(json_schema, cls) # type: ignore
  1268. else:
  1269. json_schema_extra(json_schema) # type: ignore
  1270. elif json_schema_extra is not None:
  1271. raise ValueError(
  1272. f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None"
  1273. )
  1274. if hasattr(cls, '__deprecated__'):
  1275. json_schema['deprecated'] = True
  1276. def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  1277. """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema.
  1278. Args:
  1279. json_schema: The schema to resolve.
  1280. Returns:
  1281. The resolved schema.
  1282. Raises:
  1283. RuntimeError: If the schema reference can't be found in definitions.
  1284. """
  1285. while '$ref' in json_schema:
  1286. ref = json_schema['$ref']
  1287. schema_to_update = self.get_schema_from_definitions(JsonRef(ref))
  1288. if schema_to_update is None:
  1289. raise RuntimeError(f'Cannot update undefined schema for $ref={ref}')
  1290. json_schema = schema_to_update
  1291. return json_schema
  1292. def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue:
  1293. """Generates a JSON schema that matches a schema that defines a model's fields.
  1294. Args:
  1295. schema: The core schema.
  1296. Returns:
  1297. The generated JSON schema.
  1298. """
  1299. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1300. (name, self.field_is_required(field, total=True), field)
  1301. for name, field in schema['fields'].items()
  1302. if self.field_is_present(field)
  1303. ]
  1304. if self.mode == 'serialization':
  1305. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1306. json_schema = self._named_required_fields_schema(named_required_fields)
  1307. extras_schema = schema.get('extras_schema', None)
  1308. if extras_schema is not None:
  1309. schema_to_update = self.resolve_ref_schema(json_schema)
  1310. schema_to_update['additionalProperties'] = self.generate_inner(extras_schema)
  1311. return json_schema
  1312. def field_is_present(self, field: CoreSchemaField) -> bool:
  1313. """Whether the field should be included in the generated JSON schema.
  1314. Args:
  1315. field: The schema for the field itself.
  1316. Returns:
  1317. `True` if the field should be included in the generated JSON schema, `False` otherwise.
  1318. """
  1319. if self.mode == 'serialization':
  1320. # If you still want to include the field in the generated JSON schema,
  1321. # override this method and return True
  1322. return not field.get('serialization_exclude')
  1323. elif self.mode == 'validation':
  1324. return True
  1325. else:
  1326. assert_never(self.mode)
  1327. def field_is_required(
  1328. self,
  1329. field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField,
  1330. total: bool,
  1331. ) -> bool:
  1332. """Whether the field should be marked as required in the generated JSON schema.
  1333. (Note that this is irrelevant if the field is not present in the JSON schema.).
  1334. Args:
  1335. field: The schema for the field itself.
  1336. total: Only applies to `TypedDictField`s.
  1337. Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't
  1338. explicitly specify `required=False` are required.
  1339. Returns:
  1340. `True` if the field should be marked as required in the generated JSON schema, `False` otherwise.
  1341. """
  1342. if self.mode == 'serialization' and self._config.json_schema_serialization_defaults_required:
  1343. return not field.get('serialization_exclude')
  1344. else:
  1345. if field['type'] == 'typed-dict-field':
  1346. return field.get('required', total)
  1347. else:
  1348. return field['schema']['type'] != 'default'
  1349. def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue:
  1350. """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments.
  1351. Args:
  1352. schema: The core schema.
  1353. Returns:
  1354. The generated JSON schema.
  1355. """
  1356. named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [
  1357. (field['name'], self.field_is_required(field, total=True), field)
  1358. for field in schema['fields']
  1359. if self.field_is_present(field)
  1360. ]
  1361. if self.mode == 'serialization':
  1362. named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', [])))
  1363. return self._named_required_fields_schema(named_required_fields)
  1364. def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
  1365. """Generates a JSON schema that matches a schema that defines a dataclass.
  1366. Args:
  1367. schema: The core schema.
  1368. Returns:
  1369. The generated JSON schema.
  1370. """
  1371. from ._internal._dataclasses import is_builtin_dataclass
  1372. cls = schema['cls']
  1373. config: ConfigDict = getattr(cls, '__pydantic_config__', cast('ConfigDict', {}))
  1374. with self._config_wrapper_stack.push(config):
  1375. json_schema = self.generate_inner(schema['schema']).copy()
  1376. self._update_class_schema(json_schema, cls, config)
  1377. # Dataclass-specific handling of description
  1378. if is_builtin_dataclass(cls):
  1379. # vanilla dataclass; don't use cls.__doc__ as it will contain the class signature by default
  1380. description = None
  1381. else:
  1382. description = None if cls.__doc__ is None else inspect.cleandoc(cls.__doc__)
  1383. if description:
  1384. json_schema['description'] = description
  1385. return json_schema
  1386. def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue:
  1387. """Generates a JSON schema that matches a schema that defines a function's arguments.
  1388. Args:
  1389. schema: The core schema.
  1390. Returns:
  1391. The generated JSON schema.
  1392. """
  1393. prefer_positional = schema.get('metadata', {}).get('pydantic_js_prefer_positional_arguments')
  1394. arguments = schema['arguments_schema']
  1395. kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only']
  1396. kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}]
  1397. p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only']
  1398. var_args_schema = schema.get('var_args_schema')
  1399. var_kwargs_schema = schema.get('var_kwargs_schema')
  1400. if prefer_positional:
  1401. positional_possible = not kw_only_arguments and not var_kwargs_schema
  1402. if positional_possible:
  1403. return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
  1404. keyword_possible = not p_only_arguments and not var_args_schema
  1405. if keyword_possible:
  1406. return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema)
  1407. if not prefer_positional:
  1408. positional_possible = not kw_only_arguments and not var_kwargs_schema
  1409. if positional_possible:
  1410. return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema)
  1411. raise PydanticInvalidForJsonSchema(
  1412. 'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments'
  1413. )
  1414. def kw_arguments_schema(
  1415. self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None
  1416. ) -> JsonSchemaValue:
  1417. """Generates a JSON schema that matches a schema that defines a function's keyword arguments.
  1418. Args:
  1419. arguments: The core schema.
  1420. Returns:
  1421. The generated JSON schema.
  1422. """
  1423. properties: dict[str, JsonSchemaValue] = {}
  1424. required: list[str] = []
  1425. for argument in arguments:
  1426. name = self.get_argument_name(argument)
  1427. argument_schema = self.generate_inner(argument['schema']).copy()
  1428. argument_schema['title'] = self.get_title_from_name(name)
  1429. properties[name] = argument_schema
  1430. if argument['schema']['type'] != 'default':
  1431. # This assumes that if the argument has a default value,
  1432. # the inner schema must be of type WithDefaultSchema.
  1433. # I believe this is true, but I am not 100% sure
  1434. required.append(name)
  1435. json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
  1436. if required:
  1437. json_schema['required'] = required
  1438. if var_kwargs_schema:
  1439. additional_properties_schema = self.generate_inner(var_kwargs_schema)
  1440. if additional_properties_schema:
  1441. json_schema['additionalProperties'] = additional_properties_schema
  1442. else:
  1443. json_schema['additionalProperties'] = False
  1444. return json_schema
  1445. def p_arguments_schema(
  1446. self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None
  1447. ) -> JsonSchemaValue:
  1448. """Generates a JSON schema that matches a schema that defines a function's positional arguments.
  1449. Args:
  1450. arguments: The core schema.
  1451. Returns:
  1452. The generated JSON schema.
  1453. """
  1454. prefix_items: list[JsonSchemaValue] = []
  1455. min_items = 0
  1456. for argument in arguments:
  1457. name = self.get_argument_name(argument)
  1458. argument_schema = self.generate_inner(argument['schema']).copy()
  1459. argument_schema['title'] = self.get_title_from_name(name)
  1460. prefix_items.append(argument_schema)
  1461. if argument['schema']['type'] != 'default':
  1462. # This assumes that if the argument has a default value,
  1463. # the inner schema must be of type WithDefaultSchema.
  1464. # I believe this is true, but I am not 100% sure
  1465. min_items += 1
  1466. json_schema: JsonSchemaValue = {'type': 'array'}
  1467. if prefix_items:
  1468. json_schema['prefixItems'] = prefix_items
  1469. if min_items:
  1470. json_schema['minItems'] = min_items
  1471. if var_args_schema:
  1472. items_schema = self.generate_inner(var_args_schema)
  1473. if items_schema:
  1474. json_schema['items'] = items_schema
  1475. else:
  1476. json_schema['maxItems'] = len(prefix_items)
  1477. return json_schema
  1478. def get_argument_name(self, argument: core_schema.ArgumentsParameter | core_schema.ArgumentsV3Parameter) -> str:
  1479. """Retrieves the name of an argument.
  1480. Args:
  1481. argument: The core schema.
  1482. Returns:
  1483. The name of the argument.
  1484. """
  1485. name = argument['name']
  1486. if self.by_alias:
  1487. alias = argument.get('alias')
  1488. if isinstance(alias, str):
  1489. name = alias
  1490. else:
  1491. pass # might want to do something else?
  1492. return name
  1493. def arguments_v3_schema(self, schema: core_schema.ArgumentsV3Schema) -> JsonSchemaValue:
  1494. """Generates a JSON schema that matches a schema that defines a function's arguments.
  1495. Args:
  1496. schema: The core schema.
  1497. Returns:
  1498. The generated JSON schema.
  1499. """
  1500. arguments = schema['arguments_schema']
  1501. properties: dict[str, JsonSchemaValue] = {}
  1502. required: list[str] = []
  1503. for argument in arguments:
  1504. mode = argument.get('mode', 'positional_or_keyword')
  1505. name = self.get_argument_name(argument)
  1506. argument_schema = self.generate_inner(argument['schema']).copy()
  1507. if mode == 'var_args':
  1508. argument_schema = {'type': 'array', 'items': argument_schema}
  1509. elif mode == 'var_kwargs_uniform':
  1510. argument_schema = {'type': 'object', 'additionalProperties': argument_schema}
  1511. argument_schema.setdefault('title', self.get_title_from_name(name))
  1512. properties[name] = argument_schema
  1513. if (
  1514. (mode == 'var_kwargs_unpacked_typed_dict' and 'required' in argument_schema)
  1515. or mode not in {'var_args', 'var_kwargs_uniform', 'var_kwargs_unpacked_typed_dict'}
  1516. and argument['schema']['type'] != 'default'
  1517. ):
  1518. # This assumes that if the argument has a default value,
  1519. # the inner schema must be of type WithDefaultSchema.
  1520. # I believe this is true, but I am not 100% sure
  1521. required.append(name)
  1522. json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties}
  1523. if required:
  1524. json_schema['required'] = required
  1525. return json_schema
  1526. def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue:
  1527. """Generates a JSON schema that matches a schema that defines a function call.
  1528. Args:
  1529. schema: The core schema.
  1530. Returns:
  1531. The generated JSON schema.
  1532. """
  1533. return self.generate_inner(schema['arguments_schema'])
  1534. def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue:
  1535. """Generates a JSON schema that matches a schema that defines a custom error.
  1536. Args:
  1537. schema: The core schema.
  1538. Returns:
  1539. The generated JSON schema.
  1540. """
  1541. return self.generate_inner(schema['schema'])
  1542. def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue:
  1543. """Generates a JSON schema that matches a schema that defines a JSON object.
  1544. Args:
  1545. schema: The core schema.
  1546. Returns:
  1547. The generated JSON schema.
  1548. """
  1549. content_core_schema = schema.get('schema') or core_schema.any_schema()
  1550. content_json_schema = self.generate_inner(content_core_schema)
  1551. if self.mode == 'validation':
  1552. return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema}
  1553. else:
  1554. # self.mode == 'serialization'
  1555. return content_json_schema
  1556. def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue:
  1557. """Generates a JSON schema that matches a schema that defines a URL.
  1558. Args:
  1559. schema: The core schema.
  1560. Returns:
  1561. The generated JSON schema.
  1562. """
  1563. json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1}
  1564. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  1565. return json_schema
  1566. def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue:
  1567. """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts.
  1568. Args:
  1569. schema: The core schema.
  1570. Returns:
  1571. The generated JSON schema.
  1572. """
  1573. # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec
  1574. json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1}
  1575. self.update_with_validations(json_schema, schema, self.ValidationsMapping.string)
  1576. return json_schema
  1577. def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue:
  1578. """Generates a JSON schema that matches a UUID.
  1579. Args:
  1580. schema: The core schema.
  1581. Returns:
  1582. The generated JSON schema.
  1583. """
  1584. return {'type': 'string', 'format': 'uuid'}
  1585. def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue:
  1586. """Generates a JSON schema that matches a schema that defines a JSON object with definitions.
  1587. Args:
  1588. schema: The core schema.
  1589. Returns:
  1590. The generated JSON schema.
  1591. """
  1592. for definition in schema['definitions']:
  1593. try:
  1594. self.generate_inner(definition)
  1595. except PydanticInvalidForJsonSchema as e:
  1596. core_ref: CoreRef = CoreRef(definition['ref']) # type: ignore
  1597. self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e
  1598. continue
  1599. return self.generate_inner(schema['schema'])
  1600. def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue:
  1601. """Generates a JSON schema that matches a schema that references a definition.
  1602. Args:
  1603. schema: The core schema.
  1604. Returns:
  1605. The generated JSON schema.
  1606. """
  1607. core_ref = CoreRef(schema['schema_ref'])
  1608. _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref)
  1609. return ref_json_schema
  1610. def ser_schema(
  1611. self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema
  1612. ) -> JsonSchemaValue | None:
  1613. """Generates a JSON schema that matches a schema that defines a serialized object.
  1614. Args:
  1615. schema: The core schema.
  1616. Returns:
  1617. The generated JSON schema.
  1618. """
  1619. schema_type = schema['type']
  1620. if schema_type == 'function-plain' or schema_type == 'function-wrap':
  1621. # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema
  1622. return_schema = schema.get('return_schema')
  1623. if return_schema is not None:
  1624. return self.generate_inner(return_schema)
  1625. elif schema_type == 'format' or schema_type == 'to-string':
  1626. # FormatSerSchema or ToStringSerSchema
  1627. return self.str_schema(core_schema.str_schema())
  1628. elif schema['type'] == 'model':
  1629. # ModelSerSchema
  1630. return self.generate_inner(schema['schema'])
  1631. return None
  1632. def complex_schema(self, schema: core_schema.ComplexSchema) -> JsonSchemaValue:
  1633. """Generates a JSON schema that matches a complex number.
  1634. JSON has no standard way to represent complex numbers. Complex number is not a numeric
  1635. type. Here we represent complex number as strings following the rule defined by Python.
  1636. For instance, '1+2j' is an accepted complex string. Details can be found in
  1637. [Python's `complex` documentation][complex].
  1638. Args:
  1639. schema: The core schema.
  1640. Returns:
  1641. The generated JSON schema.
  1642. """
  1643. return {'type': 'string'}
  1644. # ### Utility methods
  1645. def get_title_from_name(self, name: str) -> str:
  1646. """Retrieves a title from a name.
  1647. Args:
  1648. name: The name to retrieve a title from.
  1649. Returns:
  1650. The title.
  1651. """
  1652. return name.title().replace('_', ' ').strip()
  1653. def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool:
  1654. """Returns true if a field with the given schema should have a title set based on the field name.
  1655. Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title
  1656. (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses).
  1657. Args:
  1658. schema: The schema to check.
  1659. Returns:
  1660. `True` if the field should have a title set, `False` otherwise.
  1661. """
  1662. if _core_utils.is_core_schema_field(schema):
  1663. if schema['type'] == 'computed-field':
  1664. field_schema = schema['return_schema']
  1665. else:
  1666. field_schema = schema['schema']
  1667. return self.field_title_should_be_set(field_schema)
  1668. elif _core_utils.is_core_schema(schema):
  1669. if schema.get('ref'): # things with refs, such as models and enums, should not have titles set
  1670. return False
  1671. if schema['type'] in {'default', 'nullable', 'definitions'}:
  1672. return self.field_title_should_be_set(schema['schema']) # type: ignore[typeddict-item]
  1673. if _core_utils.is_function_with_inner_schema(schema):
  1674. return self.field_title_should_be_set(schema['schema'])
  1675. if schema['type'] == 'definition-ref':
  1676. # Referenced schemas should not have titles set for the same reason
  1677. # schemas with refs should not
  1678. return False
  1679. return True # anything else should have title set
  1680. else:
  1681. raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}') # pragma: no cover
  1682. def normalize_name(self, name: str) -> str:
  1683. """Normalizes a name to be used as a key in a dictionary.
  1684. Args:
  1685. name: The name to normalize.
  1686. Returns:
  1687. The normalized name.
  1688. """
  1689. return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__')
  1690. def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
  1691. """Override this method to change the way that definitions keys are generated from a core reference.
  1692. Args:
  1693. core_mode_ref: The core reference.
  1694. Returns:
  1695. The definitions key.
  1696. """
  1697. # Split the core ref into "components"; generic origins and arguments are each separate components
  1698. core_ref, mode = core_mode_ref
  1699. components = re.split(r'([\][,])', core_ref)
  1700. # Remove IDs from each component
  1701. components = [x.rsplit(':', 1)[0] for x in components]
  1702. core_ref_no_id = ''.join(components)
  1703. # Remove everything before the last period from each "component"
  1704. components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
  1705. short_ref = ''.join(components)
  1706. mode_title = _MODE_TITLE_MAPPING[mode]
  1707. # It is important that the generated defs_ref values be such that at least one choice will not
  1708. # be generated for any other core_ref. Currently, this should be the case because we include
  1709. # the id of the source type in the core_ref
  1710. name = DefsRef(self.normalize_name(short_ref))
  1711. name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}')
  1712. module_qualname = DefsRef(self.normalize_name(core_ref_no_id))
  1713. module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}')
  1714. module_qualname_id = DefsRef(self.normalize_name(core_ref))
  1715. occurrence_index = self._collision_index.get(module_qualname_id)
  1716. if occurrence_index is None:
  1717. self._collision_counter[module_qualname] += 1
  1718. occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname]
  1719. module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}')
  1720. module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}')
  1721. self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [
  1722. name,
  1723. name_mode,
  1724. module_qualname,
  1725. module_qualname_mode,
  1726. module_qualname_occurrence,
  1727. module_qualname_occurrence_mode,
  1728. ]
  1729. return module_qualname_occurrence_mode
  1730. def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]:
  1731. """This method wraps the get_defs_ref method with some cache-lookup/population logic,
  1732. and returns both the produced defs_ref and the JSON schema that will refer to the right definition.
  1733. Args:
  1734. core_ref: The core reference to get the definitions reference for.
  1735. Returns:
  1736. A tuple of the definitions reference and the JSON schema that will refer to it.
  1737. """
  1738. core_mode_ref = (core_ref, self.mode)
  1739. maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref)
  1740. if maybe_defs_ref is not None:
  1741. json_ref = self.core_to_json_refs[core_mode_ref]
  1742. return maybe_defs_ref, {'$ref': json_ref}
  1743. defs_ref = self.get_defs_ref(core_mode_ref)
  1744. # populate the ref translation mappings
  1745. self.core_to_defs_refs[core_mode_ref] = defs_ref
  1746. self.defs_to_core_refs[defs_ref] = core_mode_ref
  1747. json_ref = JsonRef(self.ref_template.format(model=defs_ref))
  1748. self.core_to_json_refs[core_mode_ref] = json_ref
  1749. self.json_to_defs_refs[json_ref] = defs_ref
  1750. ref_json_schema = {'$ref': json_ref}
  1751. return defs_ref, ref_json_schema
  1752. def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:
  1753. """Remove any sibling keys that are redundant with the referenced schema.
  1754. Args:
  1755. json_schema: The schema to remove redundant sibling keys from.
  1756. Returns:
  1757. The schema with redundant sibling keys removed.
  1758. """
  1759. if '$ref' in json_schema:
  1760. # prevent modifications to the input; this copy may be safe to drop if there is significant overhead
  1761. json_schema = json_schema.copy()
  1762. referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref']))
  1763. if referenced_json_schema is None:
  1764. # This can happen when building schemas for models with not-yet-defined references.
  1765. # It may be a good idea to do a recursive pass at the end of the generation to remove
  1766. # any redundant override keys.
  1767. return json_schema
  1768. for k, v in list(json_schema.items()):
  1769. if k == '$ref':
  1770. continue
  1771. if k in referenced_json_schema and referenced_json_schema[k] == v:
  1772. del json_schema[k] # redundant key
  1773. return json_schema
  1774. def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None:
  1775. try:
  1776. def_ref = self.json_to_defs_refs[json_ref]
  1777. if def_ref in self._core_defs_invalid_for_json_schema:
  1778. raise self._core_defs_invalid_for_json_schema[def_ref]
  1779. return self.definitions.get(def_ref, None)
  1780. except KeyError:
  1781. if json_ref.startswith(('http://', 'https://')):
  1782. return None
  1783. raise
  1784. def encode_default(self, dft: Any) -> Any:
  1785. """Encode a default value to a JSON-serializable value.
  1786. This is used to encode default values for fields in the generated JSON schema.
  1787. Args:
  1788. dft: The default value to encode.
  1789. Returns:
  1790. The encoded default value.
  1791. """
  1792. from .type_adapter import TypeAdapter, _type_has_config
  1793. config = self._config
  1794. try:
  1795. default = (
  1796. dft
  1797. if _type_has_config(type(dft))
  1798. else TypeAdapter(type(dft), config=config.config_dict).dump_python(
  1799. dft, by_alias=self.by_alias, mode='json'
  1800. )
  1801. )
  1802. except PydanticSchemaGenerationError:
  1803. raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}')
  1804. return pydantic_core.to_jsonable_python(
  1805. default, timedelta_mode=config.ser_json_timedelta, bytes_mode=config.ser_json_bytes, by_alias=self.by_alias
  1806. )
  1807. def update_with_validations(
  1808. self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str]
  1809. ) -> None:
  1810. """Update the json_schema with the corresponding validations specified in the core_schema,
  1811. using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema.
  1812. Args:
  1813. json_schema: The JSON schema to update.
  1814. core_schema: The core schema to get the validations from.
  1815. mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names.
  1816. """
  1817. for core_key, json_schema_key in mapping.items():
  1818. if core_key in core_schema:
  1819. json_schema[json_schema_key] = core_schema[core_key]
  1820. class ValidationsMapping:
  1821. """This class just contains mappings from core_schema attribute names to the corresponding
  1822. JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in
  1823. principle override this class in a subclass of GenerateJsonSchema (by inheriting from
  1824. GenerateJsonSchema.ValidationsMapping) to change these mappings.
  1825. """
  1826. numeric = {
  1827. 'multiple_of': 'multipleOf',
  1828. 'le': 'maximum',
  1829. 'ge': 'minimum',
  1830. 'lt': 'exclusiveMaximum',
  1831. 'gt': 'exclusiveMinimum',
  1832. }
  1833. bytes = {
  1834. 'min_length': 'minLength',
  1835. 'max_length': 'maxLength',
  1836. }
  1837. string = {
  1838. 'min_length': 'minLength',
  1839. 'max_length': 'maxLength',
  1840. 'pattern': 'pattern',
  1841. }
  1842. array = {
  1843. 'min_length': 'minItems',
  1844. 'max_length': 'maxItems',
  1845. }
  1846. object = {
  1847. 'min_length': 'minProperties',
  1848. 'max_length': 'maxProperties',
  1849. }
  1850. def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue:
  1851. members = []
  1852. for schema in schemas:
  1853. if len(schema) == 1 and 'anyOf' in schema:
  1854. members.extend(schema['anyOf'])
  1855. else:
  1856. members.append(schema)
  1857. members = _deduplicate_schemas(members)
  1858. if len(members) == 1:
  1859. return members[0]
  1860. return {'anyOf': members}
  1861. def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]:
  1862. """Get all values corresponding to the key '$ref' anywhere in the json_schema."""
  1863. json_refs: dict[JsonRef, int] = Counter()
  1864. def _add_json_refs(schema: Any) -> None:
  1865. if isinstance(schema, dict):
  1866. if '$ref' in schema:
  1867. json_ref = JsonRef(schema['$ref'])
  1868. if not isinstance(json_ref, str):
  1869. return # in this case, '$ref' might have been the name of a property
  1870. already_visited = json_ref in json_refs
  1871. json_refs[json_ref] += 1
  1872. if already_visited:
  1873. return # prevent recursion on a definition that was already visited
  1874. try:
  1875. defs_ref = self.json_to_defs_refs[json_ref]
  1876. if defs_ref in self._core_defs_invalid_for_json_schema:
  1877. raise self._core_defs_invalid_for_json_schema[defs_ref]
  1878. _add_json_refs(self.definitions[defs_ref])
  1879. except KeyError:
  1880. if not json_ref.startswith(('http://', 'https://')):
  1881. raise
  1882. for k, v in schema.items():
  1883. if k == 'examples' and isinstance(v, list):
  1884. # Skip examples that may contain arbitrary values and references
  1885. # (see the comment in `_get_all_json_refs` for more details).
  1886. continue
  1887. _add_json_refs(v)
  1888. elif isinstance(schema, list):
  1889. for v in schema:
  1890. _add_json_refs(v)
  1891. _add_json_refs(json_schema)
  1892. return json_refs
  1893. def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue:
  1894. raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}')
  1895. def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None:
  1896. """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method."""
  1897. message = self.render_warning_message(kind, detail)
  1898. if message is not None:
  1899. warnings.warn(message, PydanticJsonSchemaWarning)
  1900. def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None:
  1901. """This method is responsible for ignoring warnings as desired, and for formatting the warning messages.
  1902. You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema
  1903. to modify what warnings are generated. If you want more control, you can override this method;
  1904. just return None in situations where you don't want warnings to be emitted.
  1905. Args:
  1906. kind: The kind of warning to render. It can be one of the following:
  1907. - 'skipped-choice': A choice field was skipped because it had no valid choices.
  1908. - 'non-serializable-default': A default value was skipped because it was not JSON-serializable.
  1909. detail: A string with additional details about the warning.
  1910. Returns:
  1911. The formatted warning message, or `None` if no warning should be emitted.
  1912. """
  1913. if kind in self.ignored_warning_kinds:
  1914. return None
  1915. return f'{detail} [{kind}]'
  1916. def _build_definitions_remapping(self) -> _DefinitionsRemapping:
  1917. defs_to_json: dict[DefsRef, JsonRef] = {}
  1918. for defs_refs in self._prioritized_defsref_choices.values():
  1919. for defs_ref in defs_refs:
  1920. json_ref = JsonRef(self.ref_template.format(model=defs_ref))
  1921. defs_to_json[defs_ref] = json_ref
  1922. return _DefinitionsRemapping.from_prioritized_choices(
  1923. self._prioritized_defsref_choices, defs_to_json, self.definitions
  1924. )
  1925. def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None:
  1926. visited_defs_refs: set[DefsRef] = set()
  1927. unvisited_json_refs = _get_all_json_refs(schema)
  1928. while unvisited_json_refs:
  1929. next_json_ref = unvisited_json_refs.pop()
  1930. try:
  1931. next_defs_ref = self.json_to_defs_refs[next_json_ref]
  1932. if next_defs_ref in visited_defs_refs:
  1933. continue
  1934. visited_defs_refs.add(next_defs_ref)
  1935. unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref]))
  1936. except KeyError:
  1937. if not next_json_ref.startswith(('http://', 'https://')):
  1938. raise
  1939. self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs}
  1940. # ##### Start JSON Schema Generation Functions #####
  1941. def model_json_schema(
  1942. cls: type[BaseModel] | type[PydanticDataclass],
  1943. by_alias: bool = True,
  1944. ref_template: str = DEFAULT_REF_TEMPLATE,
  1945. schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
  1946. mode: JsonSchemaMode = 'validation',
  1947. ) -> dict[str, Any]:
  1948. """Utility function to generate a JSON Schema for a model.
  1949. Args:
  1950. cls: The model class to generate a JSON Schema for.
  1951. by_alias: If `True` (the default), fields will be serialized according to their alias.
  1952. If `False`, fields will be serialized according to their attribute name.
  1953. ref_template: The template to use for generating JSON Schema references.
  1954. schema_generator: The class to use for generating the JSON Schema.
  1955. mode: The mode to use for generating the JSON Schema. It can be one of the following:
  1956. - 'validation': Generate a JSON Schema for validating data.
  1957. - 'serialization': Generate a JSON Schema for serializing data.
  1958. Returns:
  1959. The generated JSON Schema.
  1960. """
  1961. from .main import BaseModel
  1962. schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template)
  1963. if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
  1964. cls.__pydantic_core_schema__.rebuild()
  1965. if cls is BaseModel:
  1966. raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.')
  1967. assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
  1968. return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode)
  1969. def models_json_schema(
  1970. models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]],
  1971. *,
  1972. by_alias: bool = True,
  1973. title: str | None = None,
  1974. description: str | None = None,
  1975. ref_template: str = DEFAULT_REF_TEMPLATE,
  1976. schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
  1977. ) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]:
  1978. """Utility function to generate a JSON Schema for multiple models.
  1979. Args:
  1980. models: A sequence of tuples of the form (model, mode).
  1981. by_alias: Whether field aliases should be used as keys in the generated JSON Schema.
  1982. title: The title of the generated JSON Schema.
  1983. description: The description of the generated JSON Schema.
  1984. ref_template: The reference template to use for generating JSON Schema references.
  1985. schema_generator: The schema generator to use for generating the JSON Schema.
  1986. Returns:
  1987. A tuple where:
  1988. - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
  1989. whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
  1990. JsonRef references to definitions that are defined in the second returned element.)
  1991. - The second element is a JSON schema containing all definitions referenced in the first returned
  1992. element, along with the optional title and description keys.
  1993. """
  1994. for cls, _ in models:
  1995. if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema):
  1996. cls.__pydantic_core_schema__.rebuild()
  1997. instance = schema_generator(by_alias=by_alias, ref_template=ref_template)
  1998. inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [
  1999. (m, mode, m.__pydantic_core_schema__) for m, mode in models
  2000. ]
  2001. json_schemas_map, definitions = instance.generate_definitions(inputs)
  2002. json_schema: dict[str, Any] = {}
  2003. if definitions:
  2004. json_schema['$defs'] = definitions
  2005. if title:
  2006. json_schema['title'] = title
  2007. if description:
  2008. json_schema['description'] = description
  2009. return json_schemas_map, json_schema
  2010. # ##### End JSON Schema Generation Functions #####
  2011. _HashableJsonValue: TypeAlias = Union[
  2012. int, float, str, bool, None, tuple['_HashableJsonValue', ...], tuple[tuple[str, '_HashableJsonValue'], ...]
  2013. ]
  2014. def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]:
  2015. return list({_make_json_hashable(schema): schema for schema in schemas}.values())
  2016. def _make_json_hashable(value: JsonValue) -> _HashableJsonValue:
  2017. if isinstance(value, dict):
  2018. return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items()))
  2019. elif isinstance(value, list):
  2020. return tuple(_make_json_hashable(v) for v in value)
  2021. else:
  2022. return value
  2023. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  2024. class WithJsonSchema:
  2025. """!!! abstract "Usage Documentation"
  2026. [`WithJsonSchema` Annotation](../concepts/json_schema.md#withjsonschema-annotation)
  2027. Add this as an annotation on a field to override the (base) JSON schema that would be generated for that field.
  2028. This provides a way to set a JSON schema for types that would otherwise raise errors when producing a JSON schema,
  2029. such as Callable, or types that have an is-instance core schema, without needing to go so far as creating a
  2030. custom subclass of pydantic.json_schema.GenerateJsonSchema.
  2031. Note that any _modifications_ to the schema that would normally be made (such as setting the title for model fields)
  2032. will still be performed.
  2033. If `mode` is set this will only apply to that schema generation mode, allowing you
  2034. to set different json schemas for validation and serialization.
  2035. """
  2036. json_schema: JsonSchemaValue | None
  2037. mode: Literal['validation', 'serialization'] | None = None
  2038. def __get_pydantic_json_schema__(
  2039. self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
  2040. ) -> JsonSchemaValue:
  2041. mode = self.mode or handler.mode
  2042. if mode != handler.mode:
  2043. return handler(core_schema)
  2044. if self.json_schema is None:
  2045. # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema
  2046. raise PydanticOmit
  2047. else:
  2048. return self.json_schema.copy()
  2049. def __hash__(self) -> int:
  2050. return hash(type(self.mode))
  2051. class Examples:
  2052. """Add examples to a JSON schema.
  2053. If the JSON Schema already contains examples, the provided examples
  2054. will be appended.
  2055. If `mode` is set this will only apply to that schema generation mode,
  2056. allowing you to add different examples for validation and serialization.
  2057. """
  2058. @overload
  2059. @deprecated('Using a dict for `examples` is deprecated since v2.9 and will be removed in v3.0. Use a list instead.')
  2060. def __init__(
  2061. self, examples: dict[str, Any], mode: Literal['validation', 'serialization'] | None = None
  2062. ) -> None: ...
  2063. @overload
  2064. def __init__(self, examples: list[Any], mode: Literal['validation', 'serialization'] | None = None) -> None: ...
  2065. def __init__(
  2066. self, examples: dict[str, Any] | list[Any], mode: Literal['validation', 'serialization'] | None = None
  2067. ) -> None:
  2068. if isinstance(examples, dict):
  2069. warnings.warn(
  2070. 'Using a dict for `examples` is deprecated, use a list instead.',
  2071. PydanticDeprecatedSince29,
  2072. stacklevel=2,
  2073. )
  2074. self.examples = examples
  2075. self.mode = mode
  2076. def __get_pydantic_json_schema__(
  2077. self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
  2078. ) -> JsonSchemaValue:
  2079. mode = self.mode or handler.mode
  2080. json_schema = handler(core_schema)
  2081. if mode != handler.mode:
  2082. return json_schema
  2083. examples = json_schema.get('examples')
  2084. if examples is None:
  2085. json_schema['examples'] = to_jsonable_python(self.examples)
  2086. if isinstance(examples, dict):
  2087. if isinstance(self.examples, list):
  2088. warnings.warn(
  2089. 'Updating existing JSON Schema examples of type dict with examples of type list. '
  2090. 'Only the existing examples values will be retained. Note that dict support for '
  2091. 'examples is deprecated and will be removed in v3.0.',
  2092. UserWarning,
  2093. )
  2094. json_schema['examples'] = to_jsonable_python(
  2095. [ex for value in examples.values() for ex in value] + self.examples
  2096. )
  2097. else:
  2098. json_schema['examples'] = to_jsonable_python({**examples, **self.examples})
  2099. if isinstance(examples, list):
  2100. if isinstance(self.examples, list):
  2101. json_schema['examples'] = to_jsonable_python(examples + self.examples)
  2102. elif isinstance(self.examples, dict):
  2103. warnings.warn(
  2104. 'Updating existing JSON Schema examples of type list with examples of type dict. '
  2105. 'Only the examples values will be retained. Note that dict support for '
  2106. 'examples is deprecated and will be removed in v3.0.',
  2107. UserWarning,
  2108. )
  2109. json_schema['examples'] = to_jsonable_python(
  2110. examples + [ex for value in self.examples.values() for ex in value]
  2111. )
  2112. return json_schema
  2113. def __hash__(self) -> int:
  2114. return hash(type(self.mode))
  2115. def _get_all_json_refs(item: Any) -> set[JsonRef]:
  2116. """Get all the definitions references from a JSON schema."""
  2117. refs: set[JsonRef] = set()
  2118. stack = [item]
  2119. while stack:
  2120. current = stack.pop()
  2121. if isinstance(current, dict):
  2122. for key, value in current.items():
  2123. if key == 'examples' and isinstance(value, list):
  2124. # Skip examples that may contain arbitrary values and references
  2125. # (e.g. `{"examples": [{"$ref": "..."}]}`). Note: checking for value
  2126. # of type list is necessary to avoid skipping valid portions of the schema,
  2127. # for instance when "examples" is used as a property key. A more robust solution
  2128. # could be found, but would require more advanced JSON Schema parsing logic.
  2129. continue
  2130. if key == '$ref' and isinstance(value, str):
  2131. refs.add(JsonRef(value))
  2132. elif isinstance(value, dict):
  2133. stack.append(value)
  2134. elif isinstance(value, list):
  2135. stack.extend(value)
  2136. elif isinstance(current, list):
  2137. stack.extend(current)
  2138. return refs
  2139. AnyType = TypeVar('AnyType')
  2140. if TYPE_CHECKING:
  2141. SkipJsonSchema = Annotated[AnyType, ...]
  2142. else:
  2143. @dataclasses.dataclass(**_internal_dataclass.slots_true)
  2144. class SkipJsonSchema:
  2145. """!!! abstract "Usage Documentation"
  2146. [`SkipJsonSchema` Annotation](../concepts/json_schema.md#skipjsonschema-annotation)
  2147. Add this as an annotation on a field to skip generating a JSON schema for that field.
  2148. Example:
  2149. ```python
  2150. from pprint import pprint
  2151. from typing import Union
  2152. from pydantic import BaseModel
  2153. from pydantic.json_schema import SkipJsonSchema
  2154. class Model(BaseModel):
  2155. a: Union[int, None] = None # (1)!
  2156. b: Union[int, SkipJsonSchema[None]] = None # (2)!
  2157. c: SkipJsonSchema[Union[int, None]] = None # (3)!
  2158. pprint(Model.model_json_schema())
  2159. '''
  2160. {
  2161. 'properties': {
  2162. 'a': {
  2163. 'anyOf': [
  2164. {'type': 'integer'},
  2165. {'type': 'null'}
  2166. ],
  2167. 'default': None,
  2168. 'title': 'A'
  2169. },
  2170. 'b': {
  2171. 'default': None,
  2172. 'title': 'B',
  2173. 'type': 'integer'
  2174. }
  2175. },
  2176. 'title': 'Model',
  2177. 'type': 'object'
  2178. }
  2179. '''
  2180. ```
  2181. 1. The integer and null types are both included in the schema for `a`.
  2182. 2. The integer type is the only type included in the schema for `b`.
  2183. 3. The entirety of the `c` field is omitted from the schema.
  2184. """
  2185. def __class_getitem__(cls, item: AnyType) -> AnyType:
  2186. return Annotated[item, cls()]
  2187. def __get_pydantic_json_schema__(
  2188. self, core_schema: CoreSchema, handler: GetJsonSchemaHandler
  2189. ) -> JsonSchemaValue:
  2190. raise PydanticOmit
  2191. def __hash__(self) -> int:
  2192. return hash(type(self))
  2193. def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:
  2194. if cls is not None:
  2195. try:
  2196. return _decorators.get_attribute_from_bases(cls, '__pydantic_config__')
  2197. except AttributeError:
  2198. pass
  2199. return {}