@@ -62,24 +62,53 @@ class GenerateOpenAPI30Schema:
62
62
...
63
63
64
64
elif PYDANTIC_V2 :
65
+ from enum import Enum
66
+
65
67
from pydantic .json_schema import GenerateJsonSchema , JsonSchemaValue
66
68
from pydantic_core import core_schema
67
69
68
70
class GenerateOpenAPI30Schema (GenerateJsonSchema ):
69
- """Modify the schema generation for OpenAPI 3.0.
70
-
71
- In OpenAPI 3.0, types can not be None, but a special "nullable"
72
- field is available.
73
- """
71
+ """Modify the schema generation for OpenAPI 3.0."""
74
72
75
73
def nullable_schema (
76
74
self ,
77
75
schema : core_schema .NullableSchema ,
78
76
) -> JsonSchemaValue :
77
+ """Generates a JSON schema that matches a schema that allows null values.
78
+
79
+ In OpenAPI 3.0, types can not be None, but a special "nullable" field is
80
+ available.
81
+ """
79
82
inner_json_schema = self .generate_inner (schema ["schema" ])
80
83
inner_json_schema ["nullable" ] = True
81
84
return inner_json_schema
82
85
86
+ def literal_schema (self , schema : core_schema .LiteralSchema ) -> JsonSchemaValue :
87
+ """Generates a JSON schema that matches a literal value.
88
+
89
+ In OpenAPI 3.0, the "const" keyword is not supported, so this
90
+ version of this method skips that optimization.
91
+ """
92
+ expected = [
93
+ v .value if isinstance (v , Enum ) else v for v in schema ["expected" ]
94
+ ]
95
+
96
+ types = {type (e ) for e in expected }
97
+ if types == {str }:
98
+ return {"enum" : expected , "type" : "string" }
99
+ elif types == {int }:
100
+ return {"enum" : expected , "type" : "integer" }
101
+ elif types == {float }:
102
+ return {"enum" : expected , "type" : "number" }
103
+ elif types == {bool }:
104
+ return {"enum" : expected , "type" : "boolean" }
105
+ elif types == {list }:
106
+ return {"enum" : expected , "type" : "array" }
107
+ # there is not None case because if it's mixed it hits the final `else`
108
+ # if it's a single Literal[None] then it becomes a `const` schema above
109
+ else :
110
+ return {"enum" : expected }
111
+
83
112
else :
84
113
85
114
class GenerateOpenAPI30Schema :
0 commit comments