Repaso
EspaƱol
Backend & APIsIntermediateAPI-15

What does Depends(get_db) in a FastAPI endpoint signature do?

Options

  1. It declares a Python import that the function needs in order to run
  2. It calls get_db and injects the result, with cleanup after yield (Correct option)
  3. It creates a background task that runs after the response
  4. 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.

Key terms

Practice this question in Repaso