From ac4bfca4cf40ec42b29e3edcaefba93bb7a87807 Mon Sep 17 00:00:00 2001 From: niral Date: Mon, 24 Nov 2025 16:20:45 +0530 Subject: [PATCH] docs: add BackgroundTasks usage example --- docs/en/docs/tutorial/background-tasks.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index ab44f89c1..edf821fa2 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -19,6 +19,25 @@ First, import `BackgroundTasks` and define a parameter in your *path operation f **FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter. +### Example + +```python +from fastapi import FastAPI, BackgroundTasks + +app = FastAPI() + +def write_log(message: str): + with open("log.txt", "a") as file: + file.write(message + "\n") + +@app.post("/send-message/") +async def send_message(message: str, background_tasks: BackgroundTasks): + # This will run *after* sending the response + background_tasks.add_task(write_log, message) + return {"message": "Message received"} +``` + + ## Create a task function { #create-a-task-function } Create a function to be run as the background task.