Can you explain the principle of dependency injection in FastAPI and how it is implemented in this framework?
sobes.tech AI
Answer from AI
In FastAPI, dependency injection is implemented through a mechanism that allows for the automatic creation and passing of objects or values to request handlers (endpoints).
The principle is that you describe a function or class that provides the required resource (for example, a database connection, a service, or configuration), and FastAPI automatically calls this function and passes the result to your handler.
This is achieved using the Depends parameter from the fastapi module. For example:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db():
db = create_db_session()
try:
yield db
finally:
db.close()
@app.get("/items/")
def read_items(db = Depends(get_db)):
items = db.query_items()
return items
Here, get_db is a dependency function that creates a database session and ensures its closure after use. FastAPI automatically calls get_db and passes the result to the db parameter of the read_items function.
Thus, dependency injection in FastAPI simplifies resource management, enhances testability, and modularity of the code.