Skip to content

Interview PrepDependencies · Core

Dependency Injection and Lifespan ​

16. What is dependency injection in FastAPI, and how does Depends work? ​

The short answer

A dependency is a function that an endpoint declares it needs, with Annotated[Type, Depends(func)]. Before calling the endpoint, FastAPI calls the dependency, passing it any request data it declares, such as headers, query parameters or other dependencies, and gives the endpoint the result. Use dependencies for shared work: getting the current user, opening a database session, reading settings, checking permissions, or common pagination parameters. Define a reusable alias, CurrentUser = Annotated[User, Depends(get_current_user)], so endpoints stay short.

python
from typing import Annotated
from fastapi import Depends, Header, HTTPException, status

def get_current_user(authorization: Annotated[str | None, Header()] = None) -> dict:   # (1)
    if authorization != "Bearer good":
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Not authenticated",
                            headers={"WWW-Authenticate": "Bearer"})
    return {"id": 42, "role": "customer"}

CurrentUser = Annotated[dict, Depends(get_current_user)]                   # (2)

@app.get("/orders")
async def list_orders(user: CurrentUser):                                  # (3)
    return await orders.for_customer(user["id"])
  1. The dependency declares its own inputs, here the Authorization header, exactly like an endpoint.
  2. An alias that any endpoint can reuse.
  3. The endpoint just names what it needs. Without a valid token, FastAPI answers 401 and the endpoint never runs.

This is the same idea as constructor injection in TypeScript services (dependency injection), applied per request.

17. How do dependencies with yield work, and when does their cleanup run? ​

The short answer

A dependency written as a generator sets something up, yields the value to the endpoint, and runs the code after yield as cleanup: the classic case is opening a database session and closing it, committing or rolling back. Wrap the yield in try/finally so cleanup always runs. By default, scope "request", the cleanup runs after the response has been sent. With Depends(func, scope="function"), it runs after the endpoint returns but before the response is sent, which matters when the response must reflect the cleanup's outcome, such as a commit that might fail.

python
from sqlalchemy.ext.asyncio import AsyncSession

async def get_session() -> AsyncIterator[AsyncSession]:
    async with SessionLocal() as session:          # (1)
        try:
            yield session                          # (2)
            await session.commit()                 # (3)
        except Exception:
            await session.rollback()
            raise

Session = Annotated[AsyncSession, Depends(get_session, scope="function")]   # (4)

@app.post("/orders", status_code=201)
async def create_order(order: OrderIn, session: Session) -> OrderOut:
    row = Order(**order.model_dump())
    session.add(row)
    await session.flush()                          # assigns the ID
    return OrderOut.model_validate(row, from_attributes=True)
  1. Open a session for this request.
  2. Hand it to the endpoint.
  3. Commit if the endpoint succeeded; roll back if it raised.
  4. scope="function" so the commit happens before the 201 is sent. If the commit fails, the client gets an error instead of a success for data that was never saved.

Order, verified: with a dependency that logs, a request produces open, the endpoint, then close. With the default scope, close happens after the response is already on its way.

18. How do sub-dependencies and dependency caching work? ​

The short answer

Dependencies can depend on other dependencies, forming a tree: get_current_user may need get_session, and require_admin may need get_current_user. FastAPI resolves the whole tree for each request, and caches each dependency's result for that one request: if three dependencies all need get_session, it runs once and they all share the same session. Pass use_cache=False to force a fresh call. The cache never spans requests.

python
def get_db():
    print("open")
    try:
        yield "db"
    finally:
        print("close")

def get_user(db: Annotated[str, Depends(get_db)]):
    print("user"); return {"id": 1}

def get_audit(db: Annotated[str, Depends(get_db)], user: Annotated[dict, Depends(get_user)]):
    print("audit"); return "audit"

@app.get("/x")
def x(user: Annotated[dict, Depends(get_user)], audit: Annotated[str, Depends(get_audit)]):
    print("handler"); return "ok"

# GET /x prints: open, user, audit, handler, close

Reading it: get_db is needed by get_user, get_audit and indirectly by x, yet it opens once. get_user is needed twice and runs once. Everything shares one database session for the request, which is what makes a per-request transaction possible.

19. How do router-level dependencies work, and in what order do dependencies run? ​

The short answer

Add dependencies=[Depends(require_user)] to an APIRouter, or to the whole app, and every route under it runs that dependency first, even if the route does not use its value, which is ideal for authentication, tenant checks or rate limits. Router and decorator dependencies run before the endpoint's own parameters, and an endpoint's parameters are resolved in the order they are declared. Put authentication first: if a database dependency is declared before the auth check, an unauthenticated request still opens a database session.

python
def require_user(user: CurrentUser) -> None: ...                    # raises 401 if not logged in

def require_role(role: str):
    def check(user: CurrentUser) -> None:
        if role not in user["roles"]:
            raise HTTPException(status.HTTP_403_FORBIDDEN, "Not allowed")
    return check                                                     # (1)

admin = APIRouter(
    prefix="/admin",
    dependencies=[Depends(require_user), Depends(require_role("admin"))],   # (2)
)

@admin.post("/refunds")
async def refund(body: RefundIn, session: Session): ...             # (3)
  1. A dependency factory: require_role("admin") returns a dependency for that role.
  2. Every /admin route requires a logged-in admin.
  3. The endpoint's own parameters are resolved only after the router's checks pass.

Verified ordering: an endpoint declared as (_: Depends(require_auth), db: Depends(get_db)) that fails authentication returns 401 without opening the database. Swap the two parameters and the session is opened and closed for nothing on every rejected request.

20. Should dependencies be functions or classes? ​

The short answer

Prefer function dependencies that return whatever object you need, including an instance of a class or dataclass. They are explicit, easy to read, and their parameters are what FastAPI reads from the request. FastAPI can use a class itself as a dependency, Depends(Paginator), calling its constructor with request data, but that ties the class's constructor to HTTP parameters and surprises readers. For services that need configuration, write a small function that builds and returns the service.

python
from dataclasses import dataclass

@dataclass
class Page:
    offset: int = 0
    limit: int = 50

def get_page(offset: Annotated[int, Query(ge=0)] = 0,
             limit: Annotated[int, Query(ge=1, le=100)] = 50) -> Page:     # (1)
    return Page(offset=offset, limit=limit)

PageDep = Annotated[Page, Depends(get_page)]

def get_order_service(session: Session, settings: SettingsDep) -> OrderService:   # (2)
    return OrderService(OrderRepository(session), StripeGateway(settings.stripe_key))

OrderServiceDep = Annotated[OrderService, Depends(get_order_service)]

@app.get("/orders")
async def list_orders(page: PageDep, svc: OrderServiceDep, user: CurrentUser):
    return await svc.list_for(user["id"], page)
  1. The function declares the query parameters, with limits, and returns a plain object.
  2. A factory for a service, wiring its repository and gateway: FastAPI's dependencies act as the composition root.

21. What are lifespan events, and how do you share resources across requests? ​

The short answer

Lifespan is an async context manager passed to FastAPI(lifespan=...). Code before yield runs once at startup, such as creating a database engine, an HTTP client pool or loading a model; code after yield runs once at shutdown, closing them. Store the shared objects on app.state, or yield a dict that becomes request state, and reach them in dependencies through request.app.state. It replaces the older @app.on_event("startup") handlers. Do not create a new HTTP client or engine per request.

python
from contextlib import asynccontextmanager
import httpx
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

@asynccontextmanager
async def lifespan(app: FastAPI):
    engine = create_async_engine(get_settings().database_url, pool_size=10)     # (1)
    app.state.sessions = async_sessionmaker(engine, expire_on_commit=False)
    app.state.http = httpx.AsyncClient(timeout=5.0)                            # (2)
    yield                                                                      # (3)
    await app.state.http.aclose()                                              # (4)
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

def get_http(request: Request) -> httpx.AsyncClient:
    return request.app.state.http                                              # (5)
  1. One engine with a connection pool for the whole process.
  2. One shared HTTP client, so connections to partners are reused.
  3. The app serves requests while paused here.
  4. Clean shutdown: close the client, release database connections.
  5. A dependency exposes the shared object to endpoints.

With several workers, each worker process runs its own lifespan, so the pool size is per worker; size it so workers × pool size stays under the database's connection limit (connection pooling).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
FastAPI
Basics
Pydantic
Dependencies
Async
Data and security
Production
Other topics
Nothing picked yet