FastAPI/Docs/Tutorial/Background Tasks
Properties
- tags
- Diataxis/Tutorial, FastAPI/background_tasks
Background Tasks Tutorial
Overview
Core Concepts
Task Execution Model
Request Independence
Threading and AsyncIO
Using Background Tasks
Basic Example
- python
from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) 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"}
With Dependency Injection
- python
from typing import Annotated from fastapi import BackgroundTasks, Depends, FastAPI app = FastAPI() def write_log(message: str): with open("log.txt", mode="a") as log: log.write(message) def get_query(background_tasks: BackgroundTasks, q: str | None = None): if q: message = f"found query: {q}\n" background_tasks.add_task(write_log, message) return q post"/send-notification/{email}" async def send_notification( email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)] ): message = f"message to {email}\n" background_tasks.add_task(write_log, message) return {"message": "Message sent"}
Error Handling
When to Use What
Technical Details
- From the tutorial:
- From starlette/background/BackgroundTask Starlette Docs: