What are Dependencies?

Dependencies in FastAPI allow you to inject shared code (like database connections, authentication) into your route functions. They're reusable and testable.

Basic Dependency

Create a simple dependency:

from fastapi import Depends

def get_db():
    db = "database_connection"
    try:
        yield db
    finally:
        # Close connection
        pass

@app.get("/items/")
def read_items(db = Depends(get_db)):
    return {"db": db}

Dependency Classes

Use classes as dependencies:

class Database:
    def __init__(self):
        self.connection = "connected"
    
    def query(self, sql):
        return f"Results from {sql}"

def get_database():
    return Database()

@app.get("/items/")
def read_items(db: Database = Depends(get_database)):
    return db.query("SELECT * FROM items")

Authentication Dependency

Use dependencies for authentication:

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer

security = HTTPBearer()

def get_current_user(token: str = Depends(security)):
    if token.credentials != "valid_token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token"
        )
    return {"username": "alice"}

@app.get("/protected")
def protected_route(user = Depends(get_current_user)):
    return {"message": f"Hello {user['username']}"}

Nested Dependencies

Dependencies can depend on other dependencies:

def get_db():
    return "database"

def get_user(db = Depends(get_db)):
    return {"user": "alice", "db": db}

@app.get("/items/")
def read_items(user = Depends(get_user)):
    return user

Best Practices

  • Use for shared code: Database, auth, etc.
  • Keep dependencies simple: Single responsibility
  • Use yield for cleanup: For resources that need closing
  • Test dependencies: Easy to mock for testing

Next Steps

Learn about FastAPI routes or Pydantic models.