
FastAPI
Learn essential concepts of dependencies in FastAPI.
This section covers dependency injection fundamentals, including:
Dependency injection (DI) allows you to declare reusable logic that endpoints depend on. FastAPI automatically resolves and injects dependencies, promoting clean, testable code.
Understanding dependencies helps you:
from fastapi import FastAPI, Depends
app = FastAPI()
# Dependency function
async def get_query(q: str = ""):
return q
@app.get("/search")
async def search(query: str = Depends(get_query)):
return {"search": query}from fastapi import Depends
from sqlalchemy.orm import Session
# Dependency for database connections
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{user_id}")
async def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
return user# Low-level dependency
async def verify_token(token: str) -> str:
if not token.startswith("Bearer "):
raise HTTPException(status_code=401)
return token.replace("Bearer ", "")
# Higher-level dependency using the first one
async def get_current_user(token: str = Depends(verify_token)):
# Verify token and return user
return {"user_id": 1, "token": token}
@app.get("/profile")
async def profile(user: dict = Depends(get_current_user)):
return {"user": user, "profile_data": "..."}class CommonQueryParams:
def __init__(self, skip: int = 0, limit: int = 10):
self.skip = skip
self.limit = limit
@app.get("/items")
async def list_items(commons: CommonQueryParams = Depends()):
return {
"skip": commons.skip,
"limit": commons.limit,
"items": []
}Dependencies enable:
Next step: Explore the advanced section for production patterns and optimization techniques.
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