Complete worked example
python
from fastapi import BackgroundTasks, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
class Submission(BaseModel):
id: int = Field(ge=1)
def inspect_example(ids):
app = FastAPI()
done = []
def record(role_id):
done.append(role_id)
@app.post("/collect", status_code=202)
def collect(item: Submission, tasks: BackgroundTasks):
tasks.add_task(record, item.id)
return {"accepted": item.id, "processed_at_return": len(done)}
with TestClient(app) as client:
responses = []
for role_id in ids:
response = client.post("/collect", json={"id": role_id})
responses.append({"status": response.status_code, "body": response.json()})
return {"responses": responses, "done": done}- Reasoning
- add_task receives the callable and its arguments instead of the already computed result of calling it. The task runs after response handling reaches the background phase. The local TestClient waits for this ASGI work before returning control to the inspection helper. For the first request, processed_at_return is zero even though the final done list contains the submitted ID. A second request sees the first completed item before preparing its own response. These observations illustrate ordering in this test runner, not a universal latency promise to a remote client.