
FastAPI
Learn the fundamentals of dependency injection in FastAPI.
Dependency Injection (DI) decouples your code by injecting required objects rather than creating them inside functions. FastAPI's `Depends()` enables powerful, reusable dependency chains that automatically resolve and inject parameters.
In this section, you'll understand:
from fastapi import FastAPI, Depends
app = FastAPI()
# Simple dependency
def get_db_connection():
connection = SomeDatabase()
try:
yield connection
finally:
connection.close()
# Injected into endpoint
@app.get("/data")
async def get_data(db = Depends(get_db_connection)):
data = db.query("SELECT * FROM items")
return datadef get_current_user(token: str = Header(...)):
# Dependency receives parameters from request
user = verify_token(token)
if not user:
raise HTTPException(status_code=401)
return user
def get_admin_user(user = Depends(get_current_user)):
# Sub-dependency: depends on another dependency
if user.role != "admin":
raise HTTPException(status_code=403)
return user
@app.delete("/users/{user_id}")
async def delete_user(user_id: int, admin = Depends(get_admin_user)):
# Only accessible to admins
return {"deleted": user_id}class UserService:
def __init__(self, db: Session):
self.db = db
def get_user(self, user_id: int):
return self.db.query(User).filter(User.id == user_id).first()
def get_user_service(db = Depends(get_db)):
return UserService(db)
@app.get("/users/{user_id}")
async def get_user(user_id: int, service = Depends(get_user_service)):
user = service.get_user(user_id)
return user# Production
def get_db():
return ProductionDatabase()
# Test setup
from fastapi.testclient import TestClient
def override_get_db():
return MockDatabase()
app.dependency_overrides[get_db] = override_get_db
# Now tests use mock database
client = TestClient(app)
response = client.get("/data")DI enables:
Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward