Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validation of pydantic models in query params #11243

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion fastapi/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
FrozenSet,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Expand All @@ -21,7 +22,7 @@
from fastapi.types import IncEx, ModelNameMap, UnionType
from pydantic import BaseModel, create_model
from pydantic.version import VERSION as PYDANTIC_VERSION
from starlette.datastructures import UploadFile
from starlette.datastructures import Headers, QueryParams, UploadFile
from typing_extensions import Annotated, Literal, get_args, get_origin

PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.")
Expand Down Expand Up @@ -632,3 +633,16 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation)
for sub_annotation in get_args(annotation)
)


def validate_model_with_config(
model_class: Optional[Callable[..., Any]],
received_params: Union[Mapping[str, Any], QueryParams, Headers],
) -> List[Any]:
errors = []
if isinstance(model_class, type) and issubclass(model_class, BaseModel):
try:
model_class(**dict(received_params))
except ValidationError as e:
errors.extend(_regenerate_error_with_loc(errors=e.errors(), loc_prefix=()))
return errors
10 changes: 9 additions & 1 deletion fastapi/dependencies/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
lenient_issubclass,
sequence_types,
serialize_sequence_value,
validate_model_with_config,
value_is_sequence,
)
from fastapi.background import BackgroundTasks
Expand Down Expand Up @@ -602,6 +603,11 @@ async def solve_dependencies(
values[sub_dependant.name] = solved
if sub_dependant.cache_key not in dependency_cache:
dependency_cache[sub_dependant.cache_key] = solved

params_model_errors = validate_model_with_config(
dependant.call, request.query_params
)

path_values, path_errors = request_params_to_args(
dependant.path_params, request.path_params
)
Expand All @@ -618,7 +624,9 @@ async def solve_dependencies(
values.update(query_values)
values.update(header_values)
values.update(cookie_values)
errors += path_errors + query_errors + header_errors + cookie_errors
errors += (
path_errors + query_errors + header_errors + cookie_errors + params_model_errors
)
if dependant.body_params:
(
body_values,
Expand Down
59 changes: 59 additions & 0 deletions tests/test_param_model_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from fastapi import Depends, FastAPI
from pydantic import BaseModel, ConfigDict
from starlette.testclient import TestClient

from tests.utils import needs_pydanticv1, needs_pydanticv2

app = FastAPI()


@needs_pydanticv1
class NoExtraFieldsV1(BaseModel, extra="forbid"):
a: int
b: int


@needs_pydanticv2
class NoExtraFieldsV2(BaseModel):
model_config = ConfigDict(extra="forbid")
a: int
b: int


@app.get("/v1")
def foov1(foo: NoExtraFieldsV1 = Depends()):
return foo


@app.get("/v2")
def foov2(foo: NoExtraFieldsV2 = Depends()):
return foo


client = TestClient(app)


@needs_pydanticv2
def test_validate_extra_field_config_pydantic_v2_additional_field():
response = client.get("/v2", params={"a": 1, "b": 2, "c": 2})
assert response.status_code == 422, response.text


@needs_pydanticv1
def test_validate_extra_field_conf_pydantic_v1_additional_field():
response = client.get("/v1", params={"a": 1, "b": 2, "c": 2})
assert response.status_code == 422, response.text


@needs_pydanticv2
def test_validate_extra_field_config_pydantic_v2():
response = client.get("/v2", params={"a": 1, "b": 2})
assert response.status_code == 200, response.text
assert response.json() == {"a": 1, "b": 2}


@needs_pydanticv1
def test_validate_extra_field_conf_pydantic_v1():
response = client.get("/v1", params={"a": 1, "b": 2})
assert response.status_code == 200, response.text
assert response.json() == {"a": 1, "b": 2}