0
0
FastapiHow-ToBeginner · 3 min read

How to Use Class as Dependency in FastAPI: Simple Guide

In FastAPI, you can use a class as a dependency by defining it with an __init__ method and using Depends to inject it into your path operation functions. FastAPI will create an instance of the class and pass it automatically where needed.
📐

Syntax

To use a class as a dependency in FastAPI, define a class with an __init__ method for setup. Then, use Depends() in your path operation function parameters to request an instance of that class.

FastAPI will create and manage the class instance for you.

python
from fastapi import FastAPI, Depends

class MyDependency:
    def __init__(self):
        self.value = "Hello from class dependency"

app = FastAPI()

@app.get("/")
async def read_root(dep: MyDependency = Depends()):
    return {"message": dep.value}
Output
{"message":"Hello from class dependency"}
💻

Example

This example shows a class Database used as a dependency. It simulates a connection setup in __init__. The get_data method returns sample data. The class instance is injected into the route handler using Depends().

python
from fastapi import FastAPI, Depends

class Database:
    def __init__(self):
        self.connected = True

    def get_data(self):
        return {"data": "Sample data from DB"}

app = FastAPI()

@app.get("/data")
async def read_data(db: Database = Depends()):
    if db.connected:
        return db.get_data()
    return {"error": "DB not connected"}
Output
{"data":"Sample data from DB"}
⚠️

Common Pitfalls

1. Forgetting to use Depends(): If you use the class type directly without Depends(), FastAPI won't treat it as a dependency and won't create an instance.

2. Using stateful classes without care: Class instances are created per request by default. If you want to share state, consider using singletons or other patterns.

3. Not defining __init__ properly: The class must have an __init__ method if you want to initialize attributes.

python
from fastapi import FastAPI

class WrongDependency:
    def __init__(self):
        self.value = "Won't work as dependency"

app = FastAPI()

@app.get("/wrong")
async def wrong_route(dep: WrongDependency):  # Missing Depends()
    return {"message": dep.value}

# Correct way:
from fastapi import Depends

@app.get("/right")
async def right_route(dep: WrongDependency = Depends()):
    return {"message": dep.value}
📊

Quick Reference

  • Define a class with __init__ for setup.
  • Use Depends() to inject the class instance.
  • Instances are created per request by default.
  • Use Depends() even if no parameters are needed.
  • Manage shared state carefully if needed.

Key Takeaways

Use Depends() to inject class dependencies in FastAPI routes.
Define an __init__ method in your class to initialize it properly.
FastAPI creates a new instance of the class for each request by default.
Always use Depends() even if the class has no parameters.
Be cautious with stateful classes to avoid unexpected behavior.