0
0
FastAPIframework~5 mins

Background tasks in FastAPI

Choose your learning style9 modes available
Introduction

Background tasks let your app do work after sending a response. This keeps the app fast and smooth for users.

Send a confirmation email after a user signs up.
Clean up temporary files after a request finishes.
Log user activity without slowing down the response.
Update a database record after responding to a client.
Syntax
FastAPI
from fastapi import BackgroundTasks
from fastapi import FastAPI

app = FastAPI()

async def some_task(param: str):
    # task code here
    pass

@app.post("/endpoint")
async def endpoint(background_tasks: BackgroundTasks):
    background_tasks.add_task(some_task, "value")
    return {"message": "Task started"}

Use BackgroundTasks parameter in your path operation function.

Add tasks with background_tasks.add_task(function, args).

Examples
This example writes a log message after responding to the client.
FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(message + "\n")

@app.post("/send")
async def send(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, "User sent data")
    return {"status": "Log task added"}
This example sends an email in the background after signup.
FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

async def send_email(email: str):
    # pretend to send email
    print(f"Email sent to {email}")

@app.post("/signup")
async def signup(background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email, "user@example.com")
    return {"message": "Signup complete"}
Sample Program

This FastAPI app has a POST endpoint '/process'. When called, it immediately returns a message. Meanwhile, it writes "Process started" to a file named 'log.txt' in the background.

FastAPI
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(message + "\n")

@app.post("/process")
async def process(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, "Process started")
    return {"message": "Processing started"}
OutputSuccess
Important Notes

Background tasks run after the response is sent, so they don't delay the user.

They are good for simple tasks, but not for heavy or long-running jobs.

For complex jobs, consider using a task queue like Celery.

Summary

Background tasks let you run code after sending a response.

Use BackgroundTasks and add_task to add tasks.

Great for sending emails, logging, or cleanup without slowing users.