Discover how a simple class can save you from repeating the same setup code everywhere!
Why Class-based dependencies in FastAPI? - Purpose & Use Cases
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.
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.
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.
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()
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()
This lets you organize complex setup steps cleanly and reuse them effortlessly across your app's routes.
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.
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.