docs: warn about BackgroundTasks + Response background interaction by ChunkyTortoise · Pull Request #15217 · fastapi/fastapi
Summary
Closes #11215
Adds a warning to the "Return a Response Directly" docs page explaining that returning a Response with a background parameter silently overrides any BackgroundTasks added via dependency injection.
Problem
When an endpoint uses both BackgroundTasks dependency injection and returns a Response(background=BackgroundTask(...)), the injected tasks are silently dropped. This happens because fastapi/routing.py only assigns injected background tasks when response.background is None:
if raw_response.background is None: raw_response.background = solved_result.background_tasks
This is a common footgun with no runtime warning -- tasks simply don't execute.
Changes
- Added a
/// warningblock todocs/en/docs/advanced/response-directly.mdexplaining the interaction - Created
docs_src/response_directly/tutorial003.pywith correct and incorrect patterns - Follows existing callout conventions used in
docs/en/docs/tutorial/background-tasks.md
Motivation
I use FastAPI BackgroundTasks across 5 production APIs and nearly hit this exact issue when refactoring webhook delivery to return custom Response objects. The current docs don't mention this interaction anywhere.
Test plan
- Warning uses
/// warningblock syntax (FastAPI convention) - Example file follows existing tutorial naming pattern
- Example is importable Python
🤖 Generated with Claude Code