FastAPI interview question · Most asked

How does dependency injection with `Depends` work in FastAPI?

Summary

You declare a parameter as Annotated[T, Depends(provider)]; FastAPI calls the provider per request (resolving its own dependencies recursively), caches the result within that request, and injects it.

Longer Answer

Dependencies can be functions, async functions, classes or generators (yield dependencies for setup/teardown like DB sessions). They can declare their own query params, headers or other dependencies, which appear in the OpenAPI docs. Override them in tests with app.dependency_overrides[provider] = fake. Router- or app-level dependencies=[Depends(verify_token)] run for all routes without injecting a value.

Code Example

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

async def get_api_key(x_api_key: Annotated[str, Header()]) -> str:
    if x_api_key != settings.api_key:
        raise HTTPException(status_code=401, detail="Invalid API key")
    return x_api_key

ApiKey = Annotated[str, Depends(get_api_key)]

@app.get("/reports")
async def reports(_: ApiKey):
    return {"ok": True}

Key Points

  • Declarative, per-request resolution
  • Sub-dependencies resolved recursively
  • Cached per request by default (use_cache=False to disable)
  • dependency_overrides for testing

Explanation

Follow-up questions

  • How do you write a dependency that needs cleanup?
  • How do you override dependencies in tests?

More most-asked FastAPI questions

← All FastAPI questions