pythonfastapidepends

How to use Depends and Path at the same time in FastAPI?


I have the following endpoint:

@router.get('/events/{base_id}')
def asd(base_id: common_input_types.event_id) -> None:
    do_something()

And this is common_input_types.event_id:

event_id = Annotated[
    int,
    fastapi.Depends(dependency_function),
    fastapi.Path(
        example=123,
        description="Lore",
        gt=5,
        le=100,
    ),
]

This does not trigger the dependency function. When I remove the fastapi.Path part, it works. But then I won't have the example and the min-max in swagger.

How do I specify both?


Solution

  • I don't think it's possible to annotate a parameter with Path and Depends at the same time.

    Depending on the logic you want to implement, you can move this logic to dependency_function:

    from typing import Annotated
    import fastapi
    
    app = fastapi.FastAPI()
    
    router = fastapi.APIRouter(prefix="")
    
    
    async def dependency_function(
        base_id: Annotated[
            int, fastapi.Path(example=123, description="Lore", gt=5, le=100)
        ]
    ):
        some_condition = True
        if some_condition:
            return 123
        else:
            return base_id
    
    
    @router.get('/events/{base_id}')
    def asd(base_id: Annotated[int, fastapi.Depends(dependency_function)]) -> None:
        print(base_id)
    
    app.include_router(router)