I have a FastAPI app that mostly calls external apis. In some instances, a path operation will make several calls to the same host. For that reason, I want to use a single httpx AsyncClient for each request.
The correct way to do this seems to be yielding the client within a depepdency:
async def get_client(token: str):
client = httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"})
try:
yield client
finally:
await client.aclose()
I do not want to add this dependency to every path operation though, purely for the sake of not repeating myself throughout the code. However, having read https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/, it seems global dependencies are only applicable if that dependency is doing something, rather than returning something. I cannot see how each path operation accesses the yielded client unless the dependency is specified explicitly for that particular path operation. I also cannot see how to pass the token to the dependency.
i.e. this will not allow my path operations to use the client:
app.include_router(
router,
prefix="/api",
dependencies=Depends(get_client)
)
but this will:
@router.get("/", status_code=status.HTTP_200_OK)
async def get_something(request: Request, client: httpx.AsyncClient = Depends(get_client)):
client.get('www.google.com')
Is it possible to use global dependencies if that dependency returns something that is required by the path operation?