Skip to content

Commit

Permalink
Update query parameter class
Browse files Browse the repository at this point in the history
  • Loading branch information
joostsijm committed Oct 18, 2024
1 parent 204ec43 commit e9e1080
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
15 changes: 10 additions & 5 deletions clean_python/fastapi/request_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
"""

Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion tests/fastapi/test_request_query.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from http import HTTPStatus
from typing import Annotated
from typing import List
from typing import Literal
from typing import Optional
Expand Down Expand Up @@ -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()


Expand Down

0 comments on commit e9e1080

Please sign in to comment.