0
0
FastAPIframework~5 mins

Class-based dependencies in FastAPI

Choose your learning style9 modes available
Introduction

Class-based dependencies help organize related logic in one place. They make your code cleaner and easier to reuse.

When you want to group multiple related dependency methods together.
When you need to maintain some state or configuration inside the dependency.
When you want to reuse the same dependency logic in many routes.
When your dependency requires initialization or setup steps.
When you want to keep your code modular and easier to test.
Syntax
FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

class MyDependency:
    def __init__(self, param: str):
        self.param = param

    def __call__(self):
        return f"Value is {self.param}"

@app.get("/items/")
async def read_items(dep=Depends(MyDependency("example"))):
    return {"result": dep}

The class must implement the __call__ method to be used as a dependency.

You can pass parameters to the class constructor to customize the dependency.

Examples
This example shows a class that stores a user agent string and returns it when called.
FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

class CommonHeaders:
    def __init__(self, user_agent: str = "unknown"):
        self.user_agent = user_agent

    def __call__(self):
        return {"User-Agent": self.user_agent}

@app.get("/headers")
async def get_headers(headers=Depends(CommonHeaders("my-agent"))):
    return headers
This example shows a class that counts how many times the dependency is called.
FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

class Counter:
    def __init__(self):
        self.count = 0

    def __call__(self):
        self.count += 1
        return self.count

@app.get("/count")
async def get_count(counter=Depends(Counter())):
    return {"count": counter}
Sample Program

This program defines a class-based dependency that returns a greeting message. The route uses this dependency to greet the user named Alice.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

class Greeting:
    def __init__(self, name: str):
        self.name = name

    def __call__(self):
        return f"Hello, {self.name}!"

@app.get("/greet")
async def greet(greeting=Depends(Greeting("Alice"))):
    return {"message": greeting}
OutputSuccess
Important Notes

Class-based dependencies can hold state, but be careful with mutable state in async environments.

FastAPI creates a new instance of the class for each request by default.

You can combine class-based dependencies with other dependencies for flexible designs.

Summary

Class-based dependencies group related logic in one place.

They require a __call__ method to work as dependencies.

They help keep your FastAPI code clean and reusable.