BackgroundTasks Class — fastapi Architecture
Architecture documentation for the BackgroundTasks class in background.py from the fastapi codebase.
Entity Profile
Dependency Diagram
graph TD dc716d57_75c7_1136_7c80_2b5bb5ee95ab["BackgroundTasks"] 5bca856a_f0af_e71f_c4ca_cb6510fbc659["background.py"] dc716d57_75c7_1136_7c80_2b5bb5ee95ab -->|defined in| 5bca856a_f0af_e71f_c4ca_cb6510fbc659 6dae3f2e_5480_40c7_b356_110ad2700aeb["add_task()"] dc716d57_75c7_1136_7c80_2b5bb5ee95ab -->|method| 6dae3f2e_5480_40c7_b356_110ad2700aeb
Relationship Graph
Source Code
fastapi/background.py lines 10–60
class BackgroundTasks(StarletteBackgroundTasks):
"""
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](https://fastapi.tiangolo.com/tutorial/background-tasks/).
## Example
```python
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"}
```
"""
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](https://fastapi.tiangolo.com/tutorial/background-tasks/).
"""
return super().add_task(func, *args, **kwargs)
Domain
Defined In
Source
Frequently Asked Questions
What is the BackgroundTasks class?
BackgroundTasks is a class in the fastapi codebase, defined in fastapi/background.py.
Where is BackgroundTasks defined?
BackgroundTasks is defined in fastapi/background.py at line 10.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free