Junior — Middle
What is the role of the Depends class in FastAPI and what tasks is it used for?
sobes.tech AI
Answer from AI
In FastAPI, the Depends class is used for dependency injection into request handlers. It allows you to define functions or classes that FastAPI will automatically call and pass the result into route parameters.
This is useful for:
- Reusing code (e.g., authentication checks, database session retrieval)
- Managing dependencies and their initialization
- Improving code readability and testability
Example of usage:
from fastapi import Depends, FastAPI
def get_token_header(token: str):
if token != "expected_token":
raise HTTPException(status_code=400, detail="Invalid Token")
app = FastAPI()
@app.get("/items/")
async def read_items(token: str = Depends(get_token_header)):
return [{"item": "Foo"}]
Here, Depends tells FastAPI to call the get_token_header function and pass its result into the token parameter.