0
0
FastAPIframework~3 mins

Why Class-based dependencies in FastAPI? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple class can save you from repeating the same setup code everywhere!

The Scenario

Imagine building a web app where you need to share the same setup code, like database connections or user authentication, across many routes. You write the same code again and again inside each route function.

The Problem

This manual repetition makes your code bulky and hard to maintain. If you want to change the setup, you must update every route. It's easy to make mistakes and forget some places, causing bugs and inconsistent behavior.

The Solution

Class-based dependencies let you wrap shared setup logic inside a class. FastAPI creates and reuses this class automatically for your routes. This keeps your code clean, reusable, and easy to update in one place.

Before vs After
Before
def get_db():
    db = connect_db()
    try:
        yield db
    finally:
        db.close()

@app.get('/items')
async def read_items(db=Depends(get_db)):
    return db.query_items()
After
class DBSession:
    def __init__(self):
        self.db = connect_db()
    def __call__(self):
        try:
            yield self.db
        finally:
            self.db.close()

@app.get('/items')
async def read_items(db=Depends(DBSession())):
    return db.query_items()
What It Enables

This lets you organize complex setup steps cleanly and reuse them effortlessly across your app's routes.

Real Life Example

Think of a library where every book needs a card catalog entry. Instead of writing the catalog entry steps for each book, you create a reusable card catalog class that handles it for all books automatically.

Key Takeaways

Manual setup code repetition is error-prone and hard to maintain.

Class-based dependencies wrap shared logic in one reusable place.

FastAPI manages these classes to keep your routes clean and consistent.