|
3 | 3 | from enum import Enum |
4 | 4 | from typing import Any, ClassVar |
5 | 5 |
|
| 6 | +import pydantic |
| 7 | +from packaging.version import Version |
6 | 8 | from pydantic.json_schema import GenerateJsonSchema, JsonSchemaMode |
7 | 9 | from typing_extensions import deprecated |
8 | 10 |
|
| 11 | +# Need to support the union_format parameter that was introduced in https://pydantic.dev/docs/validation/latest/get-started/changelog/#v2120-2025-10-07 |
| 12 | +PYDANTIC_HAS_UNION_FORMAT = Version(pydantic.__version__) >= Version("2.12.0") |
| 13 | + |
9 | 14 |
|
10 | 15 | class Maturity(str, Enum): |
11 | 16 | """Maturity levels for GA4GH product features.""" |
@@ -86,21 +91,29 @@ def model_json_schema( |
86 | 91 | ref_template: str = "#/$defs/{model}", |
87 | 92 | schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, |
88 | 93 | mode: JsonSchemaMode = "validation", |
| 94 | + *, |
| 95 | + union_format: str = "smart", |
89 | 96 | ) -> dict[str, Any]: |
90 | 97 | """Generate JSON Schema with GKM metadata. |
91 | 98 |
|
92 | 99 | :param by_alias: Whether to use field aliases. |
93 | 100 | :param ref_template: Template for schema references. |
94 | 101 | :param schema_generator: Pydantic schema generator class. |
95 | 102 | :param mode: Pydantic schema generation mode. |
| 103 | + :param union_format: How to represent unions in the generated schema. |
96 | 104 | :returns: JSON Schema annotated with GKM metadata. |
97 | 105 | """ |
98 | | - schema = super().model_json_schema( |
99 | | - by_alias=by_alias, |
100 | | - ref_template=ref_template, |
101 | | - schema_generator=schema_generator, |
102 | | - mode=mode, |
103 | | - ) |
| 106 | + schema_kwargs: dict[str, Any] = { |
| 107 | + "by_alias": by_alias, |
| 108 | + "ref_template": ref_template, |
| 109 | + "schema_generator": schema_generator, |
| 110 | + "mode": mode, |
| 111 | + } |
| 112 | + |
| 113 | + if PYDANTIC_HAS_UNION_FORMAT: |
| 114 | + schema_kwargs["union_format"] = union_format |
| 115 | + |
| 116 | + schema = super().model_json_schema(**schema_kwargs) # pyright: ignore[reportAttributeAccessIssue] |
104 | 117 |
|
105 | 118 | return cls.apply_schema_metadata(cls, schema) |
106 | 119 |
|
|
0 commit comments