diff --git a/docs/main/changelog.rst b/docs/main/changelog.rst index 81ece652..0b4b6da1 100644 --- a/docs/main/changelog.rst +++ b/docs/main/changelog.rst @@ -10,6 +10,7 @@ follows `Semantic versioning`_ Develop ------- - Improve ``FastAPI`` integration: handle ``Depends(Provide[...])``. +- Update ``FastAPI`` example. 4.4.0 ----- diff --git a/examples/miniapps/fastapi/README.rst b/examples/miniapps/fastapi/README.rst index 20dbf7e5..96291ae9 100644 --- a/examples/miniapps/fastapi/README.rst +++ b/examples/miniapps/fastapi/README.rst @@ -113,9 +113,9 @@ The output should be something like: giphynavigator/__init__.py 0 0 100% giphynavigator/application.py 13 0 100% giphynavigator/containers.py 6 0 100% - giphynavigator/endpoints.py 6 0 100% + giphynavigator/endpoints.py 20 0 100% giphynavigator/giphy.py 14 9 36% giphynavigator/services.py 9 1 89% giphynavigator/tests.py 38 0 100% --------------------------------------------------- - TOTAL 86 10 88% + TOTAL 100 10 90% diff --git a/examples/miniapps/fastapi/giphynavigator/application.py b/examples/miniapps/fastapi/giphynavigator/application.py index 805f4868..8a8f8a52 100644 --- a/examples/miniapps/fastapi/giphynavigator/application.py +++ b/examples/miniapps/fastapi/giphynavigator/application.py @@ -14,7 +14,7 @@ def create_app() -> FastAPI: app = FastAPI() app.container = container - app.add_api_route('/', endpoints.index) + app.include_router(endpoints.router) return app diff --git a/examples/miniapps/fastapi/giphynavigator/endpoints.py b/examples/miniapps/fastapi/giphynavigator/endpoints.py index 1d52b2f8..ab4f1b88 100644 --- a/examples/miniapps/fastapi/giphynavigator/endpoints.py +++ b/examples/miniapps/fastapi/giphynavigator/endpoints.py @@ -1,17 +1,42 @@ """Endpoints module.""" +from typing import Optional, List + +from fastapi import APIRouter, Depends +from pydantic import BaseModel from dependency_injector.wiring import inject, Provide +from .services import SearchService from .containers import Container +class Gif(BaseModel): + url: str + + +class Response(BaseModel): + query: str + limit: int + gifs: List[Gif] + + +router = APIRouter() + + +@router.get('/', response_model=Response) @inject async def index( - query: str = Provide[Container.config.default.query], - limit: int = Provide[Container.config.default.limit.as_int()], - search_service=Provide[Container.search_service], + query: Optional[str] = None, + limit: Optional[str] = None, + default_query: str = Depends(Provide[Container.config.default.query]), + default_limit: int = Depends(Provide[Container.config.default.limit.as_int()]), + search_service: SearchService = Depends(Provide[Container.search_service]), ): + query = query or default_query + limit = limit or default_limit + gifs = await search_service.search(query, limit) + return { 'query': query, 'limit': limit,