From e9e1080481ee00f67ca2e43c38c99f8eb7f8e224 Mon Sep 17 00:00:00 2001 From: Joost Sijm <joostsijm@gmail.com> Date: Fri, 18 Oct 2024 14:33:50 +0200 Subject: [PATCH] Update query parameter class --- clean_python/fastapi/request_query.py | 15 ++++++++++----- tests/fastapi/test_request_query.py | 4 +++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/clean_python/fastapi/request_query.py b/clean_python/fastapi/request_query.py index 1e7bd49..9d3c0f9 100644 --- a/clean_python/fastapi/request_query.py +++ b/clean_python/fastapi/request_query.py @@ -3,6 +3,7 @@ from inspect import signature from typing import ClassVar from typing import Literal +from warnings import warn from fastapi import Depends from fastapi import Query @@ -23,7 +24,7 @@ class RequestQuery(ValueObject): Example usage in a Resource: @get("/books") - def list_books(self, q: RequestQuery = RequestQuery.depends()): + def list_books(self, q: Annotated[RequestQuery, Query()]): return self.manage.filter(q.filters(), q.as_page_options()) """ @@ -85,15 +86,19 @@ def filters(self) -> list[Filter]: @classmethod def depends(cls) -> Depends: - """FastAPI does not directly support pydantic models for query parameters. - - Specifically, pydantic ValidationErrors lead to an internal server error. For this to work, - we wrap the RequestQuery, forwarding the type signature. + """DEPRECATED: FastAPI now does directly support pydantic models for query parameters. + See class docstring for usage. Source: + - https://fastapi.tiangolo.com/tutorial/query-param-models/ - https://github.com/tiangolo/fastapi/issues/1474 """ + warn( + "Deprecated: Pydantic models as query parameters are now supported, see class docstring.", + DeprecationWarning, + stacklevel=2, + ) def wrapper(*args, **kwargs): try: diff --git a/tests/fastapi/test_request_query.py b/tests/fastapi/test_request_query.py index 0ab83e9..e93e438 100644 --- a/tests/fastapi/test_request_query.py +++ b/tests/fastapi/test_request_query.py @@ -1,4 +1,5 @@ from http import HTTPStatus +from typing import Annotated from typing import List from typing import Literal from typing import Optional @@ -91,7 +92,8 @@ def test_filters_comparison(values, expected): class FooResource(Resource, version=v(1), name="testing"): @get("/query") - def query(self, q: SomeQuery = SomeQuery.depends()): + + def query(self, q: Annotated[SomeQuery, Query()]): return q.model_dump()