Junior — Middle
Explain what is meant by dependency in FastAPI and how it is implemented.
sobes.tech AI
Answer from AI
In FastAPI, a dependency is a way to inject components or resources (such as databases, configurations, authorization) into request handlers (endpoints) without explicitly creating them inside functions.
This is implemented using a function or class that returns the required object, along with the Depends decorator. FastAPI automatically calls this function, manages its lifecycle, and passes the result to the handler function.
Example:
from fastapi import FastAPI, Depends
app = FastAPI()
def get_db():
db = create_db_session() # create a database session
try:
yield db
finally:
db.close() # close the session after use
@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 and provides a database session. FastAPI calls it automatically and passes it to read_items. This simplifies testing, reusability, and resource management.