
FastAPI
Learn the fundamentals of background tasks in FastAPI.
Background tasks allow you to queue work that runs after returning a response to the client. This keeps response times fast while handling long-running operations like email, PDF generation, or log processing asynchronously.
In this section, you'll understand:
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(filename: str, message: str):
# This runs in background after response sent
with open(filename, "a") as f:
f.write(f"{message}\n")
@app.post("/send-notification")
async def send_notification(
email: str,
background_tasks: BackgroundTasks
):
# Send response immediately
background_tasks.add_task(write_log, "log.txt", f"Notified: {email}")
return {"status": "notification queued"}def send_email(email: str, subject: str, body: str):
# Slow operation, doesn't block response
smtp_server = smtplib.SMTP(host="localhost", port=2525)
message = EmailMessage()
message["Subject"] = subject
message["From"] = "noreply@example.com"
message["To"] = email
message.set_content(body)
smtp_server.send_message(message)
smtp_server.quit()
@app.post("/register")
async def register(user: User, background_tasks: BackgroundTasks):
# Save user to database
db.add(user)
db.commit()
# Queue email - response sent while this runs
background_tasks.add_task(
send_email,
user.email,
"Welcome!",
f"Welcome {user.name}!"
)
return {"status": "registered"}@app.post("/order-checkout")
async def checkout(
order: Order,
background_tasks: BackgroundTasks
):
# Save order
saved_order = db.add(order)
db.commit()
# Queue multiple tasks
background_tasks.add_task(
send_email,
order.customer_email,
"Order Confirmed",
f"Order {saved_order.id} confirmed"
)
background_tasks.add_task(
notify_warehouse,
saved_order.id
)
background_tasks.add_task(
update_inventory,
order.items
)
return {"order_id": saved_order.id, "status": "processing"}async def process_image(image_path: str):
# Async operation in background
async with aiohttp.ClientSession() as session:
async with session.post(
"https://ai-api.example.com/process",
files={"image": open(image_path, "rb")}
) as response:
result = await response.json()
# Store result in database
db.save_processed_image(image_path, result)
@app.post("/upload-image")
async def upload_image(file: UploadFile, background_tasks: BackgroundTasks):
filename = f"uploads/{file.filename}"
with open(filename, "wb") as f:
f.write(file.file.read())
background_tasks.add_task(process_image, filename)
return {"filename": filename}Background tasks are essential for:
Ready to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward