Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Middleware📚 Background Tasks📚 WebSockets📚 CORS📚 Dependencies📚 Dependency Injection📚 Async Programming📚 Performance
Fastapi/Advanced Patterns/Dependencies

Dependencies

Learn essential concepts of dependencies in FastAPI.

What You'll Learn

This section covers dependency injection fundamentals, including:

  • Creating reusable dependencies with `Depends()`
  • Dependency functions and classes
  • Nested dependencies
  • Database session management
  • Authentication and authorization dependencies
  • Caching and performance optimization

Core Concepts

Dependency injection (DI) allows you to declare reusable logic that endpoints depend on. FastAPI automatically resolves and injects dependencies, promoting clean, testable code.

Key Ideas

Understanding dependencies helps you:

  • Avoid code duplication across endpoints
  • Centralize cross-cutting concerns (auth, logging, validation)
  • Make code more testable with injectable dependencies
  • Share state across endpoints (database sessions, caches)
  • Build scalable, maintainable APIs

Simple Dependency Example

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}

Database Session Dependency

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

Nested Dependencies

# 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": "..."}

Dependency Classes

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": []
    }

Real-World Usage

Dependencies enable:

  • **Database Access**: Share database sessions across endpoints
  • **Authentication**: Verify tokens and extract user info once, reuse everywhere
  • **Validation**: Centralize complex validation logic
  • **Logging**: Add request/response logging as a dependency
  • **Caching**: Implement caching layers transparently
  • **Rate Limiting**: Track and limit request rates per user/endpoint

🔑 Key Takeaways

  • ✅ Understand the purpose of dependencies
  • ✅ Know when to apply this pattern
  • ✅ Follow best practices consistently
  • ✅ Test thoroughly in production scenarios

Next step: Explore the advanced section for production patterns and optimization techniques.


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn