[Python] How to inject a global httpx.AsyncClient session in FastAPI using dependency...

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using FastAPI and want to share an httpx.AsyncClient session across requests using dependency injection. I followed a pattern using FastAPI's lifespan function and storing the session in app.state as follows:

    # Standard library imports
    from contextlib import asynccontextmanager
    from typing import AsyncGenerator, cast, Dict

    # Third party library imports
    import httpx
    from fastapi import FastAPI, Request, Depends

    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    async with httpx.AsyncClient() as session:
    app.state.session = session
    yield

    async def get_session(request: Request) -> httpx.AsyncClient:
    return cast(httpx.AsyncClient, request.app.state.session)

    app = FastAPI(lifespan=lifespan)

    @app.get("/")
    async def root(session: httpx.AsyncClient = Depends(get_session)) -> Dict[str, int]:
    response = await session.get("https://www.stackoverflow.com")
    return {"status": response.status_code}

    if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app)


    This works well, but I’m wondering: are there alternative approaches to injecting a shared httpx.AsyncClient session in FastAPI? What are the potential drawbacks of this pattern?

    Continue reading...

Compartilhe esta Página