Junior — Middle
Have you had practical experience using Depends and dependency injection in FastAPI?
sobes.tech AI
Answer from AI
In FastAPI, Depends is used for dependency injection — it is a way to pass necessary objects or functions to request handlers, such as database connections, configurations, or the current user. This allows for easy code reuse and centralized dependency management.
Example of using Depends:
from fastapi import FastAPI, Depends
def get_db():
db = "db_connection"
try:
yield db
finally:
pass # close connection
app = FastAPI()
@app.get("/items/")
async def read_items(db=Depends(get_db)):
return {"db": db}
Here, get_db is a dependency function that passes the database connection to the read_items handler.