Google News
logo
FastAPI - Interview Questions
What is the purpose of the BackgroundTasks class in FastAPI?
The BackgroundTasks class in FastAPI is used to schedule background tasks that should be executed after a response has been sent to the client. This allows you to perform non-blocking or time-consuming operations without delaying the response to the client.

The purpose of the BackgroundTasks class can be summarized as follows :

Non-blocking Operations : When handling a request, there are situations where you want to perform additional operations in the background without blocking the response to the client. For example, you might want to log information, send emails, or perform other tasks that do not need to be completed before responding to the client.


Usage in Route Functions : In a FastAPI route function, you can declare a parameter of type BackgroundTasks. FastAPI will automatically create an instance of the BackgroundTasks class and inject it into your route function.
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    # Simulate a time-consuming task (e.g., writing to a log file)
    with open("log.txt", mode="a") as log:
        log.write(message)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    message = f"message to {email}"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent in the background"}?

In this example, the send_notification route function takes an email parameter and a background_tasks parameter of type BackgroundTasks. The function sends a message and schedules the write_log function to run in the background.

Adding Tasks to the Background : You can add tasks to the background using the add_task method of the BackgroundTasks instance. Each task added will be executed asynchronously after the response has been sent to the client.


Execution After Response : The tasks scheduled with BackgroundTasks are executed in the order they are added, and they are executed after the response to the client has been sent. This ensures that the client receives a quick response, and any additional, potentially time-consuming tasks are performed in the background.


Here's an overview of how it works :
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

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

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    message = f"message to {email}"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent in the background"}?

In this example, when a POST request is made to /send-notification/{email}, the response is sent immediately with the message "Message sent in the background", and the write_log function is executed in the background to write to a log file. This ensures a responsive API while still allowing for additional background processing.
Advertisement