FastAPI provides BackgroundTasks for running code after response is sent.
1from fastapi import FastAPI, BackgroundTasks2from typing import Optional34app = FastAPI()56def send_email(email: str, message: str):7 # This runs AFTER response is sent8 print(f"Sending email to {email}: {message}")9 # smtp.send(email, message)1011def log_action(action: str, user_id: int):12 print(f"User {user_id} performed {action}")1314@app.post("/users/")15async def create_user(16 name: str,17 email: str,18 background_tasks: BackgroundTasks19):20 user = User(name=name, email=email)21 db.add(user)22 await db.commit()2324 # Add background tasks25 background_tasks.add_task(26 send_email,27 email=email,28 message="Welcome!"29 )30 background_tasks.add_task(31 log_action,32 action="create_user",33 user_id=user.id34 )3536 return {"message": "User created"}3738# Task runs in same process, after response
Use cases:
Limitations: