FastAPI background tasks + dependency overrides: working versions (tested 2026-10-15)
FastAPI BackgroundTasks for post-response work, with dependency_overrides to swap services in tests.
passed1 passed · 0 failed2026-10-15 13:07 UTC- Status
- passed
- Last passed
- 2026-10-15 13:07 UTC
- Tests
- 1 / 1
- Language
- Python
- Runtime
- Python 3.13.16
uv venv -q .venv && uv pip install -q --python .venv/bin/python -r requirements.txt .venv/bin/python -m pytest -q
Python 3.13.16 linux 6.17.0-1022-azure x64 runner: github-actions 38738874208
The code
Exactly the files that passed. Your agent can pull them with get_recipe("fastapi-pydantic-background-tasks") (install), or see them on GitHub.
fastapi==0.143.1 httpx==0.28.1 pydantic==2.14.1 pytest==9.1.1
from fastapi import BackgroundTasks, Depends, FastAPI
from pydantic import BaseModel
class Mailer:
def send(self, to: str, subject: str) -> None: # real SMTP/API call goes here
raise RuntimeError("configure a real mailer")
def get_mailer() -> Mailer:
return Mailer()
class Signup(BaseModel):
email: str
app = FastAPI()
@app.post("/signup", status_code=202)
def signup(data: Signup, tasks: BackgroundTasks, mailer: Mailer = Depends(get_mailer)):
tasks.add_task(mailer.send, data.email, "Welcome!")
return {"queued": True}
from fastapi.testclient import TestClient
from app.main import Mailer, app, get_mailer
class FakeMailer(Mailer):
def __init__(self):
self.sent = []
def send(self, to, subject):
self.sent.append((to, subject))
def test_background_task_runs_after_response():
fake = FakeMailer()
app.dependency_overrides[get_mailer] = lambda: fake
try:
r = TestClient(app).post("/signup", json={"email": "[email protected]"})
assert r.status_code == 202
assert fake.sent == [("[email protected]", "Welcome!")]
finally:
app.dependency_overrides.clear()
[pytest] pythonpath = .
Connect to ProvenPin
Add the free MCP server so your agent can pull this recipe and others like it. Same setup as the docs.
claude mcp add --transport http provenpin https://mcp.provenpin.com/mcp
{ "mcpServers": { "provenpin": { "url": "https://mcp.provenpin.com/mcp" } } }{ "servers": { "provenpin": { "type": "http", "url": "https://mcp.provenpin.com/mcp" } } }{ "mcpServers": { "provenpin": { "serverUrl": "https://mcp.provenpin.com/mcp" } } }{ "mcpServers": { "provenpin": { "type": "streamableHttp", "url": "https://mcp.provenpin.com/mcp" } } }Any other MCP client: Streamable HTTP at https://mcp.provenpin.com/mcp. No API key, no signup.
Related stacks
FastAPI + Pydantic v2 validators, discriminated unions and serializers
Pydantic v2 patterns in FastAPI that agents often get wrong: field_validator, model_validator, discriminated unions, computed_field and response_model filtering.
FastAPI endpoint with Pydantic v2 discriminated unions and Annotated validators
Accept a tagged union of payment methods with Field(discriminator), add Annotated validators, and test the exact 422 error shapes offline with TestClient.
FastAPI + PyJWT bearer auth
OAuth2 password flow in FastAPI issuing PyJWT tokens, with a current-user dependency guarding routes.
FastAPI + SQLAlchemy 2 CRUD with dependency-injected sessions
FastAPI routes backed by SQLAlchemy 2.x typed models, a per-request session dependency, and TestClient tests on SQLite.