Router Level Dependencies are not injected #11527
-
First Check
Commit to Help
Example Code# in dependencies.py
def get_service_dependency(session: AsyncSession = Depends(get_db_session)):
return OwnerService(session)
# in router.py
owner_router = APIRouter(prefix="/owners", tags=["owners"], dependencies=[Depends(get_service_dependency)])
@owner_router.get("/", response_model=List[GetOwnerSchema])
async def get_owners():
try:
service: OwnerService = owner_router.dependencies[0].dependency()
result: List[GetOwnerSchema] = await service.get_owners()
return result
except Exception as e:
print(e)
raise HTTPException(status_code=500) DescriptionWhen i add dependency in router level and tried to use in handler function dependency is not injected and raise error But If i add dependecy in handler function parameter, dependency injected and i get successfull response. Am I wrong to use dependency in router level or it is a bug? Thanks for response. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.110.2 Pydantic Version2.7.1 Python Version3.11.6 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
FastAPI doesn't save solved results of router-level dependencies. So, you can't access these results. fastapi/fastapi/dependencies/utils.py Line 524 in 1c3e691 If you need to use the result of dependency, you should include this dependency as a parameter of endpoint function |
Beta Was this translation helpful? Give feedback.
FastAPI doesn't save solved results of router-level dependencies. So, you can't access these results.
Here is a related part of FastAPI sources:
fastapi/fastapi/dependencies/utils.py
Line 524 in 1c3e691
If you need to use the result of dependency, you should include this dependency as a parameter of endpoint function