Thursday, 20 November 2025

#6 Dependency Injection

FastAPI Module 6 — Dependency Injection

Module 6 — Dependency Injection

FastAPI has a powerful and elegant Dependency Injection (DI) system. It allows you to extract shared logic (e.g., authentication, DB connections, validation).

In this module, you will learn:

  • Simple function dependencies
  • Class-based dependencies
  • Dependencies with parameters
  • Using dependencies in routers

1. Basic Dependency

A dependency is a function that FastAPI calls before the endpoint.

from fastapi import FastAPI, Depends app = FastAPI() def get_token(): return "sample-token" @app.get("/secure") def secure_route(token: str = Depends(get_token)): return {"token": token}

2. Dependency with Logic

You can place reusable validation or computation here.

from fastapi import FastAPI, Depends, HTTPException app = FastAPI() def validate_api_key(api_key: str = "secret123"): if api_key != "secret123": raise HTTPException(status_code=401, detail="Invalid API Key") return api_key @app.get("/protected") def protected_route(key: str = Depends(validate_api_key)): return {"status": "Access granted"}

3. Dependency with Parameters

from fastapi import FastAPI, Depends app = FastAPI() def pagination(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} @app.get("/items") def get_items(settings: dict = Depends(pagination)): return settings

4. Class-Based Dependencies

You can use classes as auto-initialized dependencies.

from fastapi import FastAPI, Depends app = FastAPI() class DbSession: def __init__(self): self.conn = "Connected to fake DB" def get_db(): return DbSession() @app.get("/db") def db_route(db: DbSession = Depends(get_db)): return {"db_status": db.conn}

5. Dependencies in Routers (Advanced)

from fastapi import FastAPI, APIRouter, Depends app = FastAPI() def auth_user(): return "Authorized User" router = APIRouter( prefix="/users", dependencies=[Depends(auth_user)] ) @router.get("/") def get_users(): return ["User1", "User2"] app.include_router(router)

Every endpoint inside the router now automatically uses auth_user().


6. Complete Dependency Demo (Copy & Run)

from fastapi import FastAPI, APIRouter, Depends, HTTPException app = FastAPI() # Simple dependency def get_token(): return "abc123" # Parameterized dependency def pagination(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} # Auth dependency def check_auth(api_key: str = "secret123"): if api_key != "secret123": raise HTTPException(status_code=401, detail="Unauthorized") return api_key # Router with dependency router = APIRouter(prefix="/users", dependencies=[Depends(check_auth)]) @router.get("/") def list_users(): return ["Alice", "Bob", "Charlie"] app.include_router(router) @app.get("/secure") def secure_route(token: str = Depends(get_token)): return {"token": token} @app.get("/items") def items(pagination_settings: dict = Depends(pagination)): return pagination_settings

No comments:

Post a Comment

Diagnosis for running all Scripts

 Great — here is the complete ready-to-run folder structure for all 12 FastAPI modules , including: ✅ __init__.py (so Python treats folder...