Bird
0
0

Consider this FastAPI code snippet:

medium📝 component behavior Q5 of 15
FastAPI - Dependency Injection
Consider this FastAPI code snippet:
from fastapi import FastAPI, Depends

app = FastAPI()

class Accumulator:
    def __init__(self):
        self.total = 0
    def __call__(self, value: int):
        self.total += value
        return self.total

acc = Accumulator()

@app.get('/add/{value}')
async def add(value: int, total: int = Depends(acc)):
    return {'total': total}

What will be the response after calling GET /add/5 followed by GET /add/3?
A{'total': 8} on second call
B{'total': 3} on second call
C{'total': 5} on second call
DAn error occurs due to missing async __call__ method
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Accumulator class

    The class holds a total attribute and increments it on each call.
  2. Step 2: Understand FastAPI dependency lifecycle

    Here, acc is a singleton instance passed to Depends, so state is preserved across requests.
  3. Step 3: Evaluate the calls

    First call adds 5 (total=5), second call adds 3 (total=8), so second call returns 8.
  4. Final Answer:

    {'total': 8} on second call -> Option A
  5. Quick Check:

    State is preserved across requests with singleton instance [OK]
Quick Trick: Singleton instances preserve state across requests [OK]
Common Mistakes:
MISTAKES
  • Assuming state does not persist across requests
  • Expecting __call__ to be async always
  • Confusing instance variables with global state

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes