Junior — Middle
How to implement the dependency inversion principle in FastAPI?
sobes.tech AI
Answer from AI
In FastAPI, the principle of dependency inversion is implemented through the Dependency Injection mechanism using the Depends function. This allows separating the creation and management of dependencies from the business logic, which simplifies testing and maintaining the code.
Example:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db():
db = "Database connection"
try:
yield db
finally:
print("Closing connection")
@app.get("/items/")
async def read_items(db=Depends(get_db)):
return {"db_connection": db}
Here, get_db is a dependency injected into the read_items handler. This way, the database logic is separated from the main route code, which aligns with the dependency inversion principle.