Junior — Middle
What is the role of dependency injection in FastAPI and why is it necessary?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in FastAPI is used to manage dependencies between application components, such as connecting to a database, obtaining the current user, configuring caching, etc. This allows:
- To eliminate tight coupling of components.
- To improve testability of the code, as dependencies can be easily replaced.
- To centrally manage the creation and lifecycle of objects.
FastAPI implements DI through parameterization of handler functions using Depends. For example:
from fastapi import FastAPI, Depends
def get_db():
db = create_db_session()
try:
yield db
finally:
db.close()
app = FastAPI()
@app.get("/items/")
def read_items(db=Depends(get_db)):
items = db.query(Item).all()
return items
Here, get_db is a dependency that is automatically injected into the handler. This simplifies resource management and enhances the modularity of the application.