Bird
Raised Fist0
FastAPIframework~8 mins

Class-based dependencies in FastAPI - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: Class-based dependencies
MEDIUM IMPACT
This affects server response time and resource usage during request handling in FastAPI.
Injecting dependencies in FastAPI endpoints
FastAPI
from fastapi import Depends

from fastapi import FastAPI
app = FastAPI()

class DBSession:
    def __init__(self):
        self.db = create_db_session()
    def __enter__(self):
        return self.db
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.db.close()

def get_db(session: DBSession = Depends(DBSession)):
    with session as db:
        yield db

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return db.query(Item).all()
Encapsulates setup and teardown in a class, improving code reuse and clarity with slight overhead for instance creation.
📈 Performance GainSingle instance creation per request; better maintainability with negligible performance cost.
Injecting dependencies in FastAPI endpoints
FastAPI
from fastapi import Depends

from fastapi import FastAPI
app = FastAPI()

def get_db():
    db = create_db_session()
    try:
        yield db
    finally:
        db.close()

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return db.query(Item).all()
Using function-based dependencies can lead to repeated setup and teardown logic scattered across functions, making it harder to manage complex state.
📉 Performance CostTriggers setup and teardown per request; minimal overhead but can increase complexity and risk of errors.
Performance Comparison
PatternInstance CreationSetup/Teardown CallsMemory UsageVerdict
Function-based dependencyNo instance, function call onlySetup/teardown logic repeated per callLower memory per request[!] OK
Class-based dependencyOne instance per requestEncapsulated setup/teardown in classSlightly higher memory per request[OK] Good
Rendering Pipeline
Class-based dependencies are instantiated during request handling before endpoint execution. This affects the server's CPU and memory usage but does not impact browser rendering directly.
Request Handling
Dependency Injection
⚠️ BottleneckInstance creation and resource management per request
Optimization Tips
1Class-based dependencies add slight CPU and memory overhead per request due to instance creation.
2Encapsulate setup and teardown logic in classes to improve code clarity and maintainability.
3Reuse instances or minimize heavy initialization to optimize performance.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance impact of using class-based dependencies in FastAPI?
AIncreased browser rendering time
BSlight overhead due to instance creation per request
CTriggers multiple reflows in the browser
DBlocks CSS loading
DevTools: Network and Performance panels
How to check: Use Performance panel to record server response times; check Network panel for request durations.
What to look for: Look for consistent and low server response times; no spikes caused by dependency initialization.

Practice

(1/5)
1. What is the main purpose of using class-based dependencies in FastAPI?
easy
A. To automatically generate HTML forms
B. To replace all route functions with classes
C. To group related dependency logic in one reusable place
D. To handle database connections only

Solution

  1. Step 1: Understand the role of class-based dependencies

    Class-based dependencies allow grouping related logic inside a class, making code cleaner and reusable.
  2. Step 2: Compare options with this purpose

    Only To group related dependency logic in one reusable place correctly describes grouping related logic; others describe unrelated features.
  3. Final Answer:

    To group related dependency logic in one reusable place -> Option C
  4. Quick Check:

    Class-based dependencies = Group logic [OK]
Hint: Class-based dependencies group logic inside a class [OK]
Common Mistakes:
  • Thinking class dependencies replace route functions
  • Assuming they auto-generate HTML
  • Believing they only handle databases
2. Which method must a class implement to be used as a dependency in FastAPI?
easy
A. __init__
B. __call__
C. dependency
D. run

Solution

  1. Step 1: Recall FastAPI dependency requirements

    FastAPI requires the class to be callable, which means it must implement the __call__ method.
  2. Step 2: Match method names to this requirement

    Only __call__ makes the class instance callable; __init__ is for initialization, others are invalid.
  3. Final Answer:

    __call__ -> Option B
  4. Quick Check:

    Callable class = __call__ method [OK]
Hint: Class must be callable via __call__ method [OK]
Common Mistakes:
  • Choosing __init__ instead of __call__
  • Using random method names like 'run'
  • Confusing dependency with method name
3. Given this class-based dependency, what will be the output when accessing the endpoint?
from fastapi import FastAPI, Depends

app = FastAPI()

class Greeting:
    def __init__(self, name: str = "Guest"):
        self.name = name
    def __call__(self):
        return f"Hello, {self.name}!"

@app.get("/hello")
async def hello(greet: str = Depends(Greeting)):
    return {"message": greet}
medium
A. {"message": "Hello!"}
B. {"message": "Hello, name!"}
C. TypeError at runtime
D. {"message": "Hello, Guest!"}

Solution

  1. Step 1: Analyze the Greeting class behavior

    The class sets name to "Guest" by default and __call__ returns "Hello, Guest!" string.
  2. Step 2: Understand dependency injection in endpoint

    Depends(Greeting) creates an instance with default name, so greet is "Hello, Guest!" string.
  3. Final Answer:

    {"message": "Hello, Guest!"} -> Option D
  4. Quick Check:

    Default name used = Hello, Guest! [OK]
Hint: Default parameter used if no argument passed [OK]
Common Mistakes:
  • Expecting 'name' literal instead of variable value
  • Assuming runtime error without cause
  • Ignoring default parameter in __init__
4. Identify the error in this class-based dependency usage:
class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

@app.get("/count")
async def get_count(counter: Counter = Depends(Counter)):
    counter.increment()
    return {"count": counter.count}
medium
A. count attribute should be a class variable
B. Counter class lacks a __call__ method
C. increment method should be async
D. Depends() cannot accept classes

Solution

  1. Step 1: Trace the dependency execution flow

    Depends(Counter) creates a new instance each request; self.count = 0, increment() sets to 1, returns {"count": 1}. Count resets every request.
  2. Step 2: Pinpoint the logical error

    self.count is an instance attribute (per-request); for persistent counting across requests, count must be a class attribute.
  3. Final Answer:

    count attribute should be a class variable -> Option A
  4. Quick Check:

    Instance attr = resets per request [OK]
Hint: Use class variables for shared state across requests [OK]
Common Mistakes:
  • Thinking Depends can't accept classes
  • Assuming async needed for increment
  • Confusing instance and class variables
5. How can you modify this class-based dependency to accept a dynamic parameter from the request query?
class UserInfo:
    def __init__(self, user_id: int):
        self.user_id = user_id
    def __call__(self):
        return f"User ID is {self.user_id}"

@app.get("/user")
async def user(info: str = Depends(UserInfo)):
    return {"info": info}

Choose the correct way to pass user_id from query parameters.
hard
A. Use __init__(self, user_id: int = Query(...)) and import Query
B. Add user_id parameter to __call__ method instead
C. Pass user_id directly in Depends(UserInfo(user_id))
D. Use global variable for user_id inside UserInfo

Solution

  1. Step 1: Understand how FastAPI injects parameters

    FastAPI injects parameters into __init__ if they have default values with Query or Body.
  2. Step 2: Use Query to declare user_id in __init__

    Adding user_id: int = Query(...) in __init__ allows FastAPI to get it from query parameters.
  3. Final Answer:

    Use __init__(self, user_id: int = Query(...)) and import Query -> Option A
  4. Quick Check:

    Query param in __init__ = dynamic dependency [OK]
Hint: Use Query in __init__ to get query params [OK]
Common Mistakes:
  • Trying to pass parameters in __call__
  • Passing instance in Depends directly
  • Using global variables instead of parameters