Careeroza
Background Tasks
Run Work After Responding
Example
BackgroundTasks runs a function after the response is sent: good for sending emails or logging, so the user does not wait:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
outbox = []
def send_welcome_email(email: str):
outbox.append(f"Welcome email sent to {email}")
@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_welcome_email, email)
return {"status": "account created"}
@app.get("/outbox")
def read_outbox():
return outboxRequests and responses
POST /[email protected] → 200 {"status": "account created"} GET /outbox → 200 ["Welcome email sent to [email protected]"]
Tip: Background tasks run in the same process. For heavy or must-not-be-lost jobs, use a task queue (Celery, RQ, Cloud Tasks, Pub/Sub).