Skip to content

Commit 2f6d43c

Browse files
authored
✨ Add support for optional query, header, and cookie parameter models (#16584)
1 parent e4c5d02 commit 2f6d43c

16 files changed

Lines changed: 1254 additions & 19 deletions

File tree

‎docs/en/docs/tutorial/cookie-param-models.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,16 @@ You can combine multiple cookie parameter models with individual cookie paramete
7777

7878
Parameters declared elsewhere in the same operation or its dependencies are not treated as extra fields of a model. Undeclared cookie parameters still follow the model's `extra` configuration.
7979

80+
## Optional Cookie Parameter Models { #optional-cookie-parameter-models }
81+
82+
Declare a cookie parameter model with `| None` and a default of `None` to make the group optional.
83+
84+
{* ../../docs_src/cookie_param_models/tutorial003_an_py310.py hl[15] *}
85+
86+
If neither `theme` nor `locale` is sent, `preferences` is `None`. If either is sent, FastAPI validates the model and requires both fields.
87+
88+
The same rules for defaults, extra fields, and OpenAPI apply as for [optional query parameter models](query-param-models.md#optional-query-parameter-models).
89+
8090
## Summary { #summary }
8191

8292
You can use **Pydantic models** to declare <dfn title="Have a last cookie before you go. 🍪">**cookies**</dfn> in **FastAPI**. 😎

‎docs/en/docs/tutorial/header-param-models.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ Parameters declared elsewhere in the same operation or its dependencies are not
7575

7676
Each model uses its own `Header(convert_underscores=...)` setting, both when reading the request and when generating OpenAPI. Explicit field aliases remain literal header names.
7777

78+
## Optional Header Parameter Models { #optional-header-parameter-models }
79+
80+
Declare a header parameter model with `| None` and a default of `None` to make the group optional.
81+
82+
{* ../../docs_src/header_param_models/tutorial004_an_py310.py hl[15] *}
83+
84+
If neither `x-client-name` nor `x-client-version` is sent, `client` is `None`. If either is sent, FastAPI validates the model and requires both fields.
85+
86+
The same rules for defaults, extra fields, and OpenAPI apply as for [optional query parameter models](query-param-models.md#optional-query-parameter-models).
87+
88+
Headers such as `Host` also follow the model's `extra` configuration. With `extra="allow"`, they make the model present even if neither declared field is supplied.
89+
7890
## Summary { #summary }
7991

8092
You can use **Pydantic models** to declare **headers** in **FastAPI**. 😎

‎docs/en/docs/tutorial/query-param-models.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,22 @@ With `extra="forbid"`, parameters declared elsewhere in the same operation or it
7777

7878
This also works for `Header` and `Cookie` models.
7979

80+
## Optional Query Parameter Models { #optional-query-parameter-models }
81+
82+
Declare a query parameter model with `| None` and a default of `None` to make the group optional.
83+
84+
{* ../../docs_src/query_param_models/tutorial004_an_py310.py hl[18] *}
85+
86+
If neither `start` nor `end` is sent, `date_range` is `None`. If either is sent, FastAPI validates the model and requires both fields.
87+
88+
Using `| None` without a default still makes the parameter required.
89+
90+
Unknown parameters follow the model's `extra` configuration. Ignored extras do not make the model present.
91+
92+
OpenAPI lists the group's fields individually and marks them as optional.
93+
94+
You can also declare optional [header parameter models](header-param-models.md#optional-header-parameter-models) and [cookie parameter models](cookie-param-models.md#optional-cookie-parameter-models).
95+
8096
## Summary { #summary }
8197

8298
You can use **Pydantic models** to declare **query parameters** in **FastAPI**. 😎
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from typing import Annotated
2+
3+
from fastapi import Cookie, FastAPI
4+
from pydantic import BaseModel
5+
6+
app = FastAPI()
7+
8+
9+
class Preferences(BaseModel):
10+
theme: str
11+
locale: str
12+
13+
14+
@app.get("/items/")
15+
async def read_items(preferences: Annotated[Preferences | None, Cookie()] = None):
16+
return preferences
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from fastapi import Cookie, FastAPI
2+
from pydantic import BaseModel
3+
4+
app = FastAPI()
5+
6+
7+
class Preferences(BaseModel):
8+
theme: str
9+
locale: str
10+
11+
12+
@app.get("/items/")
13+
async def read_items(preferences: Preferences | None = Cookie(default=None)):
14+
return preferences
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from typing import Annotated
2+
3+
from fastapi import FastAPI, Header
4+
from pydantic import BaseModel
5+
6+
app = FastAPI()
7+
8+
9+
class ClientHeaders(BaseModel):
10+
x_client_name: str
11+
x_client_version: str
12+
13+
14+
@app.get("/items/")
15+
async def read_items(client: Annotated[ClientHeaders | None, Header()] = None):
16+
return client
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from fastapi import FastAPI, Header
2+
from pydantic import BaseModel
3+
4+
app = FastAPI()
5+
6+
7+
class ClientHeaders(BaseModel):
8+
x_client_name: str
9+
x_client_version: str
10+
11+
12+
@app.get("/items/")
13+
async def read_items(client: ClientHeaders | None = Header(default=None)):
14+
return client
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from datetime import date
2+
from typing import Annotated
3+
4+
from fastapi import FastAPI, Query
5+
from pydantic import BaseModel
6+
7+
app = FastAPI()
8+
9+
10+
class DateRange(BaseModel):
11+
start: date
12+
end: date
13+
14+
15+
@app.get("/items/")
16+
async def read_items(
17+
limit: int = 10,
18+
date_range: Annotated[DateRange | None, Query()] = None,
19+
):
20+
return {"limit": limit, "date_range": date_range}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from datetime import date
2+
3+
from fastapi import FastAPI, Query
4+
from pydantic import BaseModel
5+
6+
app = FastAPI()
7+
8+
9+
class DateRange(BaseModel):
10+
start: date
11+
end: date
12+
13+
14+
@app.get("/items/")
15+
async def read_items(
16+
limit: int = 10,
17+
date_range: DateRange | None = Query(default=None),
18+
):
19+
return {"limit": limit, "date_range": date_range}

‎fastapi/dependencies/utils.py‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -163,12 +163,31 @@ def _get_flat_body_params(dependant: Dependant) -> list[ModelField]:
163163
return body_params
164164

165165

166+
def _get_model_type(annotation: Any) -> type[BaseModel] | None:
167+
if get_origin(annotation) in (Union, UnionType):
168+
args = get_args(annotation)
169+
if len(args) == 2 and type(None) in args:
170+
annotation = next(arg for arg in args if arg is not type(None))
171+
if lenient_issubclass(annotation, BaseModel):
172+
return annotation
173+
return None
174+
175+
176+
def _get_param_model(field: ModelField) -> type[BaseModel] | None:
177+
annotation = field.field_info.annotation
178+
if isinstance(field.field_info, (params.Query, params.Header, params.Cookie)):
179+
annotation = _get_model_type(annotation)
180+
if lenient_issubclass(annotation, BaseModel) and not _is_json_field(field):
181+
return annotation
182+
return None
183+
184+
166185
def _get_flat_fields_from_params(fields: Sequence[ModelField]) -> list[ModelField]:
167186
flat_fields: list[ModelField] = []
168187
for field in fields:
169-
annotation = _get_form_model(field) or field.field_info.annotation
170-
if lenient_issubclass(annotation, BaseModel) and not _is_json_field(field):
171-
flat_fields.extend(get_cached_model_fields(annotation))
188+
model = _get_form_model(field) or _get_param_model(field)
189+
if model is not None:
190+
flat_fields.extend(get_cached_model_fields(model))
172191
else:
173192
flat_fields.append(field)
174193
return flat_fields
@@ -637,7 +656,7 @@ def analyze_param(
637656
assert (
638657
is_scalar_field(field)
639658
or field_annotation_is_scalar_sequence(field.field_info.annotation)
640-
or lenient_issubclass(field.field_info.annotation, BaseModel)
659+
or _get_model_type(field.field_info.annotation) is not None
641660
), f"Query parameter {param_name!r} must be one of the supported types"
642661

643662
return ParamDetails(type_annotation=type_annotation, depends=depends, field=field)
@@ -899,10 +918,10 @@ def _get_multidict_value(
899918

900919
def _request_param_model_to_args(
901920
model_field: ModelField,
921+
model: type[BaseModel],
902922
received_params: Mapping[str, Any],
903923
known_param_names: set[str],
904924
) -> tuple[Any, list[Any]]:
905-
model = cast(type[BaseModel], model_field.field_info.annotation)
906925
fields_to_extract = get_cached_model_fields(model)
907926
default_convert_underscores = getattr(
908927
model_field.field_info, "convert_underscores", True
@@ -959,8 +978,14 @@ def _request_param_model_to_args(
959978
field_info = model_field.field_info
960979
assert isinstance(field_info, params.Param), "Params must be subclasses of Param"
961980
loc: tuple[str, ...] = (field_info.in_.value,)
981+
value = params_to_process
982+
if field_info.annotation is not model and not (
983+
own_names.intersection(received_params)
984+
or (model.model_config.get("extra") in ("allow", "forbid") and value)
985+
):
986+
value = Undefined
962987
v_, errors_ = _validate_value_with_model_field(
963-
field=model_field, value=params_to_process, values={}, loc=loc
988+
field=model_field, value=value, values={}, loc=loc
964989
)
965990
if header_aliases and model.model_config.get("loc_by_alias", True):
966991
# Report the header names without changing model aliases or schema.
@@ -988,11 +1013,9 @@ def request_params_to_args(
9881013
if known_param_names is None:
9891014
known_param_names = set()
9901015
for field in fields:
991-
if lenient_issubclass(
992-
field.field_info.annotation, BaseModel
993-
) and not _is_json_field(field):
1016+
if (model := _get_param_model(field)) is not None:
9941017
v_, errors_ = _request_param_model_to_args(
995-
field, received_params, known_param_names
1018+
field, model, received_params, known_param_names
9961019
)
9971020
else:
9981021
aliases = _get_param_aliases(field)
@@ -1082,14 +1105,7 @@ def _get_form_model(field: ModelField) -> type[BaseModel] | None:
10821105
or _is_json_field(field)
10831106
):
10841107
return None
1085-
annotation = field.field_info.annotation
1086-
if get_origin(annotation) in (Union, UnionType):
1087-
args = get_args(annotation)
1088-
if len(args) == 2 and type(None) in args:
1089-
annotation = next(arg for arg in args if arg is not type(None))
1090-
if lenient_issubclass(annotation, BaseModel):
1091-
return annotation
1092-
return None
1108+
return _get_model_type(field.field_info.annotation)
10931109

10941110

10951111
def _should_embed_body_fields(fields: list[ModelField]) -> bool:

0 commit comments

Comments
 (0)