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:

  1. from fastapi import BackgroundTasks

fastapi.BackgroundTasks

  1. 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.

Example

  1. from fastapi import BackgroundTasks, FastAPI
  2. app = FastAPI()
  3. def write_notification(email: str, message=""):
  4. with open("log.txt", mode="w") as email_file:
  5. content = f"notification for {email}: {message}"
  6. email_file.write(content)
  7. @app.post("/send-notification/{email}")
  8. async def send_notification(email: str, background_tasks: BackgroundTasks):
  9. background_tasks.add_task(write_notification, email, message="some notification")
  10. return {"message": "Notification sent in the background"}
PARAMETERDESCRIPTION
tasks

TYPE: Optional[Sequence[BackgroundTask]] DEFAULT: None

Source code in starlette/background.py

  1. 32
  2. 33
  1. def init(self, tasks: typing.Optional[typing.Sequence[BackgroundTask]] = None):
  2. self.tasks = list(tasks) if tasks else []

func instance-attribute

  1. func = func

args instance-attribute

  1. args = args

kwargs instance-attribute

  1. kwargs = kwargs

is_async instance-attribute

  1. is_async = is_async_callable(func)

tasks instance-attribute

  1. tasks = list(tasks) if tasks else []

add_task

  1. 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.

PARAMETERDESCRIPTION
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]

args

TYPE: args DEFAULT: ()

*kwargs

TYPE: kwargs DEFAULT: {}

Source code in fastapi/background.py

  1. 38
  2. 39
  3. 40
  4. 41
  5. 42
  6. 43
  7. 44
  8. 45
  9. 46
  10. 47
  11. 48
  12. 49
  13. 50
  14. 51
  15. 52
  16. 53
  17. 54
  18. 55
  19. 56
  20. 57
  21. 58
  22. 59
  1. def add_task(
  2. self,
  3. func: Annotated[
  4. Callable[P, Any],
  5. Doc(
  6. “””
  7. The function to call after the response is sent.
  8. It can be a regular def function or an async def function.
  9. “””
  10. ),
  11. ],
  12. args: P.args,
  13. **kwargs: P.kwargs,
  14. ) -> None:
  15. “””
  16. Add a function to be called in the background after the response is sent.
  17. Read more about it in the
  18. FastAPI docs for Background Tasks.
  19. “””
  20. return super().add_task(func, args, **kwargs)