0
0
FastapiHow-ToBeginner · 3 min read

How to Use BackgroundTasks in FastAPI for Async Tasks

In FastAPI, use BackgroundTasks to run functions after sending a response without blocking the client. Inject BackgroundTasks into your path operation and add tasks with background_tasks.add_task(your_function, args).
📐

Syntax

The BackgroundTasks class is imported from fastapi. You add it as a parameter to your path operation function. Use background_tasks.add_task(function, *args) to schedule a function to run after the response is sent.

  • background_tasks: The parameter to receive the BackgroundTasks instance.
  • add_task: Method to add a function and its arguments to run in the background.
  • function: The function you want to run after response.
  • args: Arguments passed to the function.
python
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

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

@app.post("/send-notification/")
async def send_notification(background_tasks: BackgroundTasks, email: str):
    background_tasks.add_task(write_log, f"Notification sent to {email}")
    return {"message": "Notification sent"}
💻

Example

This example shows how to send a notification and log the event in the background without delaying the response. The write_log function writes a message to a file after the response is returned.

python
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

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

@app.post("/send-notification/")
async def send_notification(background_tasks: BackgroundTasks, email: str):
    background_tasks.add_task(write_log, f"Notification sent to {email}")
    return {"message": "Notification sent"}
Output
{"message": "Notification sent"}
⚠️

Common Pitfalls

Not adding BackgroundTasks as a parameter: Forgetting to include background_tasks: BackgroundTasks in your function means you cannot schedule background tasks.

Running blocking code in background tasks: Background tasks should be fast and non-blocking; heavy tasks should use other async workers.

Expecting immediate task completion: Background tasks run after the response, so do not rely on their immediate result.

python
from fastapi import FastAPI

app = FastAPI()

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

# Wrong: missing BackgroundTasks parameter
@app.post("/wrong/")
async def wrong_send_notification(email: str):
    # This will not work because background_tasks is not defined
    # background_tasks.add_task(write_log, f"Notification sent to {email}")
    return {"message": "Notification sent"}

# Right way
from fastapi import BackgroundTasks

@app.post("/right/")
async def right_send_notification(background_tasks: BackgroundTasks, email: str):
    background_tasks.add_task(write_log, f"Notification sent to {email}")
    return {"message": "Notification sent"}
📊

Quick Reference

Use this quick guide to remember how to use BackgroundTasks in FastAPI:

ActionDescription
Import BackgroundTasksfrom fastapi import BackgroundTasks
Add BackgroundTasks parameterInclude background_tasks: BackgroundTasks in your path function
Schedule a taskbackground_tasks.add_task(your_function, args)
Task runs after responseFunction runs after response is sent to client
Use for quick background jobsAvoid heavy or blocking tasks here

Key Takeaways

Add BackgroundTasks as a parameter to your path operation function to use it.
Use background_tasks.add_task() to schedule functions that run after the response.
Background tasks run asynchronously after the response, so they don't delay the client.
Avoid heavy or blocking operations in background tasks to keep your app responsive.
BackgroundTasks is ideal for quick jobs like logging, sending emails, or notifications.