What does Depends(get_db) in a FastAPI endpoint signature do?
Options
- It declares a Python import that the function needs in order to run
- It calls
get_dband injects the result, with cleanup after yield (Correct option) - It creates a background task that runs after the response
- It validates the response of the endpoint before it is sent
Answer
Tells FastAPI to call get_db and inject its result (dependency injection), including generator cleanup
Why
FastAPI sees db = Depends(get_db), calls get_db() for each request and passes the result into your function.
If get_db uses yield, the code after yield (e.g. closing the DB session) runs after the response.
In tests you can replace it: app.dependency_overrides[get_db] = fake_db.
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{uid}")
def read_user(uid: int, db = Depends(get_db)):
return db.get(User, uid)Remember
Depends = FastAPI's dependency injection.