Junior — Middle
What are the advantages of using Depends for dependency injection in FastAPI?
sobes.tech AI
Answer from AI
In FastAPI, Depends is used for dependency injection, which provides several advantages:
- Code reuse: common dependencies (e.g., database connection, authorization check) can be defined and used across different endpoints.
- Cleanliness and readability of code: dependencies are explicitly specified in function parameters, making it easier to understand and maintain.
- Automatic lifecycle management: FastAPI automatically creates and destroys dependency objects if they are defined as generators.
- Integration with Python's type system: allows for autocomplete and type checking.
Example of usage:
from fastapi import Depends, FastAPI
def get_token_header(token: str):
if token != "secret-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"}]