Junior — Middle
Explain the dependency injection principle in FastAPI and its main features.
sobes.tech AI
Answer from AI
In FastAPI, dependency injection is implemented through the Dependency Injection mechanism, which allows automatically passing necessary objects or values to handlers (endpoints).
Main features:
- Uses the
Dependsfunction, which indicates to FastAPI that a parameter should be obtained from a dependency. - Dependencies can be simple functions that return the required object (e.g., database connection, current user).
- FastAPI automatically calls these functions and passes the result to the handler.
- Dependencies can be nested and reusable.
Example:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db():
db = create_db_session()
try:
yield db
finally:
db.close()
@app.get("/items/")
async def read_items(db = Depends(get_db)):
items = db.query(Item).all()
return items
Here, get_db is a dependency that creates a database session and passes it to the endpoint. FastAPI takes care of calling and managing the lifecycle of this dependency.
This approach simplifies testing, code reuse, and makes the application's architecture more modular.