link
fastapi/background-task

Background Tasks

Run tasks after response

background
async

Command

Examples

Background email sending

from fastapi import BackgroundTasks
  
  def write_notification(email: str, message=""):
      # Send email in background
      send_email(email, message)
  
  @app.post("/send-notification/{email}")
  async def send_notification(email: str, background_tasks: BackgroundTasks):
      background_tasks.add_task(write_notification, email, message="Hello!")
      return {"message": "Notification sent in background"}