Complete worked example
python
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
def inspect_example(requests):
app = FastAPI()
count = 0
def observe():
nonlocal count
count += 1
return count
@app.get("/observe")
def read(first: Annotated[int, Depends(observe)],
second: Annotated[int, Depends(observe)]):
return [first, second]
with TestClient(app) as client:
pairs = [client.get("/observe").json() for _ in range(requests)]
return {"pairs": pairs, "calls": count}- Reasoning
- Depends identifies the dependency callable in each parameter. The shared callable and its arguments participate in dependency resolution. The counter is enclosed in a fresh application fixture so its sequence is deterministic and unrelated tests cannot alter it. The helper sends one or more local requests and returns their observed pairs plus the number of actual dependency calls. This distinguishes two useful properties: reuse inside a request and freshness across requests. Returning just the final HTTP status would prove neither.