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=Falseto disable) dependency_overridesfor 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
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?