Skip to content

Commit e42ac0a

Browse files
authored
✨ Add support for combining unions of form models (#16596)
1 parent addd077 commit e42ac0a

7 files changed

Lines changed: 959 additions & 54 deletions

File tree

‎docs/en/docs/tutorial/request-form-models.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,22 @@ An optional model containing only unchecked checkboxes is omitted. Send a value
103103

104104
## Optional Unions of Form Models { #optional-unions-of-form-models }
105105

106-
For forms declared as a single parameter, you can also use an optional union of models.
106+
You can also use an optional union of models.
107107

108108
{* ../../docs_src/request_form_models/tutorial006_an_py310.py hl[9:16,21] *}
109109

110110
If no form fields are sent, `contact` is `None`. Send `kind=person` with `name`, or `kind=company` with `company_name`. The discriminator selects which model to validate.
111111

112+
## Combine Unions of Form Models { #combine-unions-of-form-models }
113+
114+
You can combine unions with other form models, individual `Form` parameters, and `File` parameters. Each union is validated independently.
115+
116+
{* ../../docs_src/request_form_models/tutorial007_an_py310.py hl[31:35] *}
117+
118+
Send all fields in the same form. For example, send `contact_type=person`, `name=Rick`, `notification_type=email`, `[email protected]`, and `token=secret`.
119+
120+
Omit the notification fields to leave `notification` as `None`.
121+
112122
## Form Models and Files { #form-models-and-files }
113123

114124
You can also combine a form model with [file parameters](request-files.md).
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import Annotated, Literal
2+
3+
from fastapi import FastAPI, Form
4+
from pydantic import BaseModel
5+
6+
app = FastAPI()
7+
8+
9+
class Person(BaseModel):
10+
contact_type: Literal["person"]
11+
name: str
12+
13+
14+
class Company(BaseModel):
15+
contact_type: Literal["company"]
16+
company_name: str
17+
18+
19+
class Email(BaseModel):
20+
notification_type: Literal["email"]
21+
email: str
22+
23+
24+
class SMS(BaseModel):
25+
notification_type: Literal["sms"]
26+
phone: str
27+
28+
29+
@app.post("/contacts/")
30+
async def create_contact(
31+
contact: Annotated[Person | Company, Form(discriminator="contact_type")],
32+
token: Annotated[str, Form()],
33+
notification: Annotated[
34+
Email | SMS | None, Form(discriminator="notification_type")
35+
] = None,
36+
):
37+
return {"contact": contact, "notification": notification, "token": token}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import Literal
2+
3+
from fastapi import FastAPI, Form
4+
from pydantic import BaseModel
5+
6+
app = FastAPI()
7+
8+
9+
class Person(BaseModel):
10+
contact_type: Literal["person"]
11+
name: str
12+
13+
14+
class Company(BaseModel):
15+
contact_type: Literal["company"]
16+
company_name: str
17+
18+
19+
class Email(BaseModel):
20+
notification_type: Literal["email"]
21+
email: str
22+
23+
24+
class SMS(BaseModel):
25+
notification_type: Literal["sms"]
26+
phone: str
27+
28+
29+
@app.post("/contacts/")
30+
async def create_contact(
31+
contact: Person | Company = Form(discriminator="contact_type"),
32+
token: str = Form(),
33+
notification: Email | SMS | None = Form(
34+
default=None, discriminator="notification_type"
35+
),
36+
):
37+
return {"contact": contact, "notification": notification, "token": token}

‎fastapi/dependencies/utils.py‎

Lines changed: 36 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,14 +1015,22 @@ def _normalize_form_model(value: Any, *, model: type[BaseModel]) -> Any:
10151015
return value
10161016

10171017

1018-
def _get_form_model(field: ModelField) -> type[BaseModel] | None:
1018+
def _get_form_models(field: ModelField) -> list[type[BaseModel]]:
10191019
if (
10201020
not isinstance(field.field_info, params.Form)
10211021
or field.field_info.embed
10221022
or _is_json_field(field)
10231023
):
1024-
return None
1025-
return _get_model_type(field.field_info.annotation)
1024+
return []
1025+
model = _get_model_type(field.field_info.annotation)
1026+
if model is not None:
1027+
return [model]
1028+
return _get_form_union_models(field.field_info.annotation)
1029+
1030+
1031+
def _get_form_model(field: ModelField) -> type[BaseModel] | None:
1032+
models = _get_form_models(field)
1033+
return models[0] if len(models) == 1 else None
10261034

10271035

10281036
def _should_embed_body_fields(fields: list[ModelField]) -> bool:
@@ -1036,8 +1044,8 @@ def _should_embed_body_fields(fields: list[ModelField]) -> bool:
10361044
return True
10371045
first_field = fields[0]
10381046
# Dependencies can use the same parameter name for different form models.
1039-
if _get_form_model(first_field) is not None and any(
1040-
_get_form_model(field) is None
1047+
if _get_form_models(first_field) and any(
1048+
not _get_form_models(field)
10411049
or field.field_info.annotation is not first_field.field_info.annotation
10421050
for field in fields[1:]
10431051
):
@@ -1050,8 +1058,7 @@ def _should_embed_body_fields(fields: list[ModelField]) -> bool:
10501058
if (
10511059
isinstance(first_field.field_info, params.Form)
10521060
and not lenient_issubclass(first_field.field_info.annotation, BaseModel)
1053-
and _get_form_model(first_field) is None
1054-
and not _get_form_union_models(first_field.field_info.annotation)
1061+
and not _get_form_models(first_field)
10551062
):
10561063
return True
10571064
return False
@@ -1148,18 +1155,18 @@ def _is_form_model_supplied(
11481155

11491156
async def _extract_form_model(
11501157
field: ModelField,
1151-
model: type[BaseModel],
1158+
models: list[type[BaseModel]],
11521159
received_body: FormData,
11531160
) -> Any:
1154-
if field.field_info.annotation is not model and not _is_form_model_supplied(
1155-
model, received_body
1161+
if type(None) in get_args(field.field_info.annotation) and not any(
1162+
_is_form_model_supplied(model, received_body) for model in models
11561163
):
11571164
return Undefined
1165+
# Union validators normalize each branch from the original form values.
1166+
model_fields = get_cached_model_fields(models[0]) if len(models) == 1 else []
11581167
return {
11591168
alias: item
1160-
async for alias, item, _ in _extract_form_body(
1161-
get_cached_model_fields(model), received_body
1162-
)
1169+
async for alias, item, _ in _extract_form_body(model_fields, received_body)
11631170
}
11641171

11651172

@@ -1175,49 +1182,31 @@ async def request_body_to_args(
11751182
len(body_fields) == 1
11761183
and not embed_body_fields
11771184
and not _should_embed_body_fields(body_fields)
1178-
and _get_form_model(body_fields[0]) is None
1185+
and not _get_form_models(body_fields[0])
11791186
)
11801187
first_field = body_fields[0]
11811188
body_to_process = received_body
11821189
form_values: dict[str, tuple[str, Any]] = {}
1183-
form_union_absent = False
11841190

11851191
if isinstance(received_body, FormData):
11861192
fields_to_extract = [
1187-
field for field in body_fields if _get_form_model(field) is None
1193+
field for field in body_fields if not _get_form_models(field)
11881194
]
1189-
union_models = (
1190-
_get_form_union_models(first_field.field_info.annotation)
1191-
if single_not_embedded_field
1192-
else []
1193-
)
1194-
if union_models:
1195-
# Preserve all form values for validators around the union.
1196-
# Each branch applies its own model field extraction afterward.
1197-
fields_to_extract = []
11981195
body_to_process = {}
11991196
async for alias, value, field in _extract_form_body(
12001197
fields_to_extract,
12011198
received_body,
12021199
):
1203-
if single_not_embedded_field:
1204-
body_to_process[alias] = value
1205-
elif field is not None:
1200+
body_to_process[alias] = value
1201+
if field is not None:
12061202
# Keep each parameter's selected alias and scalar/list shape.
12071203
form_values[field.name] = (alias, value)
1208-
form_union_absent = (
1209-
bool(union_models)
1210-
and type(None) in get_args(first_field.field_info.annotation)
1211-
and not any(
1212-
_is_form_model_supplied(model, received_body) for model in union_models
1213-
)
1214-
)
12151204

12161205
if single_not_embedded_field:
12171206
loc: tuple[str, ...] = ("body",)
12181207
v_, errors_ = _validate_value_with_model_field(
12191208
field=first_field,
1220-
value=Undefined if form_union_absent else body_to_process,
1209+
value=body_to_process,
12211210
values=values,
12221211
loc=loc,
12231212
)
@@ -1226,12 +1215,9 @@ async def request_body_to_args(
12261215
aliases = [alias for alias, _ in _get_param_aliases(field)]
12271216
loc = ("body", aliases[0])
12281217
value = Undefined
1229-
if (
1230-
isinstance(received_body, FormData)
1231-
and (model := _get_form_model(field)) is not None
1232-
):
1218+
if isinstance(received_body, FormData) and (models := _get_form_models(field)):
12331219
# Extract each model independently from the original form values.
1234-
value = await _extract_form_model(field, model, received_body)
1220+
value = await _extract_form_model(field, models, received_body)
12351221
loc = ("body",)
12361222
elif isinstance(received_body, FormData):
12371223
alias, value = form_values.get(field.name, (aliases[0], Undefined))
@@ -1313,8 +1299,8 @@ def _apply_form_body_schema(
13131299
conditions: list[dict[str, Any]] = []
13141300
for index, param in enumerate(body_params):
13151301
field_schema = parameter_schemas[f"field_{index}"]
1316-
model = _get_form_model(param)
1317-
if model is None:
1302+
models = _get_form_models(param)
1303+
if not models:
13181304
alias = _get_param_aliases(param)[0][0]
13191305
if alias in properties:
13201306
conditions.append({"properties": {alias: field_schema}})
@@ -1325,19 +1311,23 @@ def _apply_form_body_schema(
13251311
continue
13261312

13271313
field_schema.pop("default", None)
1328-
if param.field_info.annotation is not model:
1314+
if type(None) in get_args(param.field_info.annotation):
13291315
# A flat form group is omitted through absent fields, not a null body.
13301316
field_schema["anyOf"] = [
13311317
choice
13321318
for choice in field_schema["anyOf"]
13331319
if choice.get("type") != "null"
13341320
]
1335-
if model.model_config.get("extra") in ("allow", "forbid"):
1321+
if any(
1322+
model.model_config.get("extra") in ("allow", "forbid")
1323+
for model in models
1324+
):
13361325
absent: dict[str, Any] = {"maxProperties": 0}
13371326
else:
13381327
names = sorted(
13391328
{
13401329
alias
1330+
for model in models
13411331
for item in get_cached_model_fields(model)
13421332
for alias, _ in _get_param_aliases(item)
13431333
}
@@ -1385,7 +1375,7 @@ def _get_body_field(
13851375
model_name = "Body_" + name
13861376
fields = body_params
13871377
config: ConfigDict | None = None
1388-
if any(_get_form_model(field) is not None for field in body_params):
1378+
if any(_get_form_models(field) for field in body_params):
13891379
fields = []
13901380
for index, field in enumerate(body_params):
13911381
field_info = copy(field.field_info)

0 commit comments

Comments
 (0)