Background tasks¶
FastAPI's BackgroundTasks runs functions after the response has been sent. The binary runs them at the same
point.
A task added to BackgroundTasks runs after the response is sent; the second route shows
what it did. Like every example on this site, it is compiled and compared with FastAPI in CI (how).
docs_src/tutorial/background.py
from fastapi import APIRouter, BackgroundTasks
router = APIRouter(prefix="/background", tags=["background"])
NOTIFICATIONS: list[str] = []
def write_notification(email: str, message: str = ""):
NOTIFICATIONS.append(f"notification for {email}: {message}")
@router.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
@router.get("/notifications")
async def read_notifications():
return NOTIFICATIONS
What is native¶
BackgroundTasks: run after the response (an error is logged), not after an error response.
For work that outlives a request, asyncio.create_task, threads and event loops are described in
Python semantics § asyncio and threading.
What stays in Python¶
BackgroundTaskson a WebSocket route is refused (WebSockets).