Skip to content

Commit f90d036

Browse files
authored
🐛 Fix OpenAPI schemas for standalone nullable form unions (#16598)
1 parent 80c8742 commit f90d036

2 files changed

Lines changed: 84 additions & 19 deletions

File tree

‎fastapi/dependencies/utils.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1366,8 +1366,7 @@ def _get_body_field(
13661366
return None
13671367
first_param = body_params[0]
13681368
has_nullable_form_model = any(
1369-
(model := _get_form_model(field)) is not None
1370-
and field.field_info.annotation is not model
1369+
_get_form_models(field) and type(None) in get_args(field.field_info.annotation)
13711370
for field in body_params
13721371
)
13731372
if not embed_body_fields and not has_nullable_form_model:
@@ -1402,6 +1401,9 @@ def _get_body_field(
14021401
if not embed_body_fields:
14031402
field_info = copy(first_param.field_info)
14041403
field_info.annotation = BodyModel
1404+
# The original form field already carries the validation metadata.
1405+
field_info.metadata = []
1406+
field_info.discriminator = None
14051407
return ModelField(name=first_param.name, field_info=field_info)
14061408
required = any(True for f in body_params if f.field_info.is_required())
14071409
BodyFieldInfo_kwargs: dict[str, Any] = {

‎tests/test_forms_optional_unions.py‎

Lines changed: 80 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -125,15 +125,27 @@ def read(data: Annotated[Count | Label | None, Form()]):
125125
return data
126126

127127
client = TestClient(app)
128-
response = client.post("/")
129-
assert response.status_code == 422
130-
assert response.json()["detail"] == [
131-
{"type": "missing", "loc": ["body"], "msg": "Field required", "input": None}
132-
]
128+
for fields in ({}, {"unknown": "ignored"}):
129+
response = client.post("/", data=fields)
130+
assert response.status_code == 422
131+
assert response.json()["detail"] == [
132+
{"type": "missing", "loc": ["body"], "msg": "Field required", "input": None}
133+
]
133134
response = client.post("/", data={"count": "2"})
134135
assert response.status_code == 200, response.text
135136
assert response.json() == {"count": 2}
136-
assert app.openapi()["paths"]["/"]["post"]["requestBody"]["required"] is True
137+
schema = app.openapi()
138+
assert schema["paths"]["/"]["post"]["requestBody"]["required"] is True
139+
assert schema["components"]["schemas"]["Body_read__post"]["allOf"] == [
140+
{"not": {"not": {"anyOf": [{"required": ["count"]}, {"required": ["label"]}]}}},
141+
{
142+
"anyOf": [
143+
{"$ref": "#/components/schemas/Count"},
144+
{"$ref": "#/components/schemas/Label"},
145+
],
146+
"title": "Data",
147+
},
148+
]
137149

138150

139151
@pytest.mark.parametrize("extra", ["ignore", "allow", "forbid"])
@@ -173,6 +185,27 @@ def read(
173185
assert response.json() == (
174186
{"count": 1, "unknown": ["a", "b"]} if extra == "allow" else None
175187
)
188+
schema = app.openapi()
189+
assert "required" not in schema["paths"]["/"]["post"]["requestBody"]
190+
absent = (
191+
{"maxProperties": 0}
192+
if extra in ("allow", "forbid")
193+
else {"not": {"anyOf": [{"required": ["count"]}, {"required": ["label"]}]}}
194+
)
195+
assert schema["components"]["schemas"]["Body_read__post"]["allOf"] == [
196+
{
197+
"anyOf": [
198+
absent,
199+
{
200+
"anyOf": [
201+
{"$ref": "#/components/schemas/Count"},
202+
{"$ref": "#/components/schemas/Label"},
203+
],
204+
"title": "Data",
205+
},
206+
]
207+
}
208+
]
176209

177210

178211
def test_mixed_extra_configurations_activate_union():
@@ -345,6 +378,10 @@ def read_validated_default(
345378
response = client.post("/validated-default")
346379
assert response.status_code == 200, response.text
347380
assert calls == ["validated"]
381+
schema = app.openapi()
382+
for path in ("/default", "/factory", "/validated-default"):
383+
assert "required" not in schema["paths"][path]["post"]["requestBody"]
384+
assert calls == ["validated"]
348385

349386

350387
def test_optional_union_in_dependency():
@@ -370,24 +407,51 @@ def read(data: Annotated[TextForm | ListForm | None, Depends(get_form)]):
370407

371408
def test_openapi():
372409
schema = app.openapi()
410+
schemas = schema["components"]["schemas"]
411+
absent = {
412+
"not": {
413+
"anyOf": [
414+
{"required": ["enabled"]},
415+
{"required": ["kind"]},
416+
{"required": ["value"]},
417+
]
418+
}
419+
}
373420
assert schema["paths"]["/union"]["post"]["requestBody"] == {
374421
"content": {
375422
"application/x-www-form-urlencoded": {
376-
"schema": {
423+
"schema": {"$ref": "#/components/schemas/Body_read_union_union_post"}
424+
}
425+
}
426+
}
427+
assert schemas["Body_read_union_union_post"]["allOf"] == [
428+
{
429+
"anyOf": [
430+
absent,
431+
{
377432
"anyOf": [
378433
{"$ref": "#/components/schemas/TextForm"},
379434
{"$ref": "#/components/schemas/ListForm"},
380-
{"type": "null"},
381435
],
382436
"title": "Data",
383-
}
384-
}
437+
},
438+
]
385439
}
386-
}
440+
]
387441
assert schema["paths"]["/discriminated"]["post"]["requestBody"] == {
388442
"content": {
389443
"application/x-www-form-urlencoded": {
390444
"schema": {
445+
"$ref": "#/components/schemas/Body_read_discriminated_discriminated_post"
446+
}
447+
}
448+
}
449+
}
450+
assert schemas["Body_read_discriminated_discriminated_post"]["allOf"] == [
451+
{
452+
"anyOf": [
453+
absent,
454+
{
391455
"anyOf": [
392456
{
393457
"oneOf": [
@@ -402,12 +466,11 @@ def test_openapi():
402466
},
403467
},
404468
},
405-
{"type": "null"},
406469
],
407470
"title": "Data",
408-
}
409-
}
471+
},
472+
]
410473
}
411-
}
412-
assert schema["components"]["schemas"]["TextForm"]["required"] == ["kind", "value"]
413-
assert schema["components"]["schemas"]["ListForm"]["required"] == ["kind", "value"]
474+
]
475+
assert schemas["TextForm"] == TextForm.model_json_schema()
476+
assert schemas["ListForm"] == ListForm.model_json_schema()

0 commit comments

Comments
 (0)