Skip to main content
FastAPI Docs

Search documentation

Type to search this documentation.

On this pageOverview

Background Tasks - BackgroundTasks¶

You can declare a parameter in a path operation function or dependency function with the type BackgroundTasks, and then you can use it to schedule the execution of background tasks after the response is sent.

You can import it directly from fastapi:

from fastapi import BackgroundTasks
BackgroundTasks(tasks=None)

Bases: BackgroundTasks

A collection of background tasks that will be called after a response has been sent to the client.

Read more about it in the FastAPI docs for Background Tasks.

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}
Source code in starlette/background.py
def __init__(self, tasks: Sequence[BackgroundTask] | None = None):
    self.tasks = list(tasks) if tasks else []
func = func
args = args
kwargs = kwargs
is_async = is_async_callable(func)
tasks = list(tasks) if tasks else []
add_task(func, *args, **kwargs)

Add a function to be called in the background after the response is sent.

Read more about it in the FastAPI docs for Background Tasks.

PARAMETER DESCRIPTION
func The function to call after the response is sent. It can be a regular def function or an async def function. TYPE: Callable[P, Any]
Source code in fastapi/background.py
def add_task(
    self,
    func: Annotated[
        Callable[P, Any],
        Doc(
            """
            The function to call after the response is sent.

            It can be a regular `def` function or an `async def` function.
            """
        ),
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """
    Add a function to be called in the background after the response is sent.

    Read more about it in the
    [FastAPI docs for Background Tasks](../tutorial/background-tasks.md).
    """
    return super().add_task(func, *args, **kwargs)
Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu