In FastAPI, how do you make a sign-up endpoint send a welcome email only after the client has received its response?
answer
- a parameter FastAPI fills in
- a class imported from fastapi
- pass the function, not its result
- add_task with args and kwargs
basics
~10 sDeclare a parameter typed BackgroundTasks, call background_tasks.add_task(send_welcome_email, email) and return normally; FastAPI sends the response first, then calls the function with those arguments in the same process.
solid answer
~40 sAdd a parameter annotated `BackgroundTasks`, imported from `fastapi`, to the path operation; FastAPI creates one per request and injects it, the way it injects `Request`. Call `background_tasks.add_task(send_welcome_email, email, subject="Welcome")`: the first argument is the function itself, the rest are the positional and keyword arguments it will later be called with. Return your response as usual. Once the response has been sent, FastAPI calls each queued function in the order it was added, inside the same worker process: a `def` function through the thread pool, an `async def` function awaited on the event loop. Two slips to avoid: writing `add_task(send_welcome_email(email))`, which sends the email before the response and queues its return value, and reaching for Starlette's singular `BackgroundTask`, which FastAPI does not inject.
code
python · 21 linesfrom fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def send_welcome_email(email: str, subject: str = "Welcome") -> None:
# blocking mail-server call; a def task runs in the thread pool
print(f"sending {subject!r} to {email}")
async def write_audit_line(event: str, email: str) -> None:
# an async def task is awaited on the event loop
print(f"audit: {event} {email}")
@app.post("/signup", status_code=201)
async def signup(email: str, background_tasks: BackgroundTasks):
# ... create the account ...
background_tasks.add_task(send_welcome_email, email, subject="Welcome aboard")
background_tasks.add_task(write_audit_line, "signup", email)
return {"email": email, "status": "created"}go deeper
Recall the three pieces: a parameter typed BackgroundTasks, add_task with the function and its arguments, and a normal return. Say that the task runs after the response.
Explain the order of events after the return, why a def task goes through the thread pool while an async def task is awaited, and why passing a called function to add_task is a bug.
Point out that the tasks still belong to the request in the same worker: a restart, a failure or a slow task stays your problem, and nobody sees its outcome except the logs.
Treat BackgroundTasks as a convention to scope: which follow-ups a team may run in the web process, and which must be handed to a durable queue with retries.
## What the feature is for Some work triggered by a request does not have to finish before the client hears back. A sign-up endpoint has to create the account before it answers, but the welcome email can follow a moment later: the client should not sit waiting several seconds while a mail server is contacted. FastAPI's answer is **`BackgroundTasks`**, a small per-request list of function calls that it runs **after the response has been sent**, in the **same process** that served the request. `BackgroundTasks` is imported from `fastapi`. It is FastAPI's thin subclass of Starlette's class of the same name, offered from `fastapi` so you are not tempted to import Starlette's singular `BackgroundTask` by mistake. ## Declaring it and queuing work You never construct the object yourself. You declare a parameter whose type annotation is `BackgroundTasks`, and FastAPI recognises the type and passes in the request's instance, the same way it recognises `Request`: ```python from fastapi import BackgroundTasks, FastAPI app = FastAPI() def send_welcome_email(email: str, subject: str = "Welcome") -> None: ... # talk to the mail server @app.post("/signup", status_code=201) async def signup(email: str, background_tasks: BackgroundTasks): # ... create the account ... background_tasks.add_task(send_welcome_email, email, subject="Welcome aboard") return {"email": email, "status": "created"} ``` `add_task` takes: - **the function to call later**, passed as an object (`send_welcome_email`), not called; - **any positional arguments** for it, in order (`email`); - **any keyword arguments** for it (`subject="Welcome aboard"`). It returns `None` immediately. Nothing runs at that point; the call is only recorded. ## What happens after you return 1. Your path operation returns its value, and FastAPI builds the response from it. 2. The response's status line, headers and body are sent to the client. 3. FastAPI then calls each recorded function **one after another, in the order they were added**, awaiting each before starting the next. 4. A plain `def` task is run through Starlette's `run_in_threadpool`, on a worker thread, so a blocking mail-server call does not freeze the event loop. An `async def` task is awaited directly on the event loop. The client already has its full response by step 3. The tasks still belong to the request, though: the server's handling of that request is not finished until they are. ## Mistakes that show up in review - **Calling the function inside `add_task`.** `background_tasks.add_task(send_welcome_email(email))` runs the email send immediately, before the response, and queues its return value, usually `None`; after the response, FastAPI tries to call that value and the request fails with a `TypeError` that only the server log shows. - **Importing the wrong class.** `starlette.background.BackgroundTask` (no `s`) is a single task you attach yourself to a `Response` you return through its `background` argument. Used as a parameter type, FastAPI does not inject it; it rejects the route with a `FastAPIError` when the route is declared. - **Creating `BackgroundTasks()` yourself and dropping it.** An instance you build inside the endpoint runs nothing unless you attach it to a response you return. - **Expecting a result.** `add_task` gives you no handle, status or return value. If the client needs to know the outcome, the work does not belong after the response. ## Testing it `fastapi.testclient.TestClient` drives the app in process and returns from `client.post(...)` only after the request's background tasks have run. A test can therefore: - replace the mail sender with a fake, by patching the name the endpoint passes to `add_task` or by making the sender a dependency and swapping it in `app.dependency_overrides`, then assert it was called with the right address; - assert on any side effect directly after the call, without sleeping or polling. That convenience hides one production fact: in a real server the client has its answer long before the task finishes, so a test passing says nothing about how long the task holds the worker. ## Choosing the status code An endpoint that finishes its real work in the request and only sends a notification afterwards still answers `201` or `200`. When the request merely **accepts** work that will be done afterwards, such as processing an uploaded file, the FastAPI documentation suggests answering `202 Accepted`, set with `status_code=202` on the decorator. ## Where it stops being the right tool | Fits `BackgroundTasks` | Better elsewhere | |---|---| | a short call such as a notification email | long or CPU-heavy processing | | work that can use objects from the same app | work that must survive a restart or be retried | | best-effort follow-ups | work another machine should pick up | The FastAPI documentation itself points heavier, multi-process work at a separate task queue such as Celery; `BackgroundTasks` lives and dies with the worker process that served the request.
- Can a FastAPI dependency add tasks to the same BackgroundTasks object as the endpoint?Yes. Declare a `BackgroundTasks` parameter in the dependency, a sub-dependency or the endpoint, and FastAPI passes the same per-request object to all of them. Every `add_task` call lands on one list, and the whole list runs after the response, in the order the calls were made.
- In FastAPI, how do you attach work to a response you build and return yourself?Pass it through the response's `background` argument, for example `JSONResponse(content, background=background_tasks)`; `BackgroundTasks` is a subclass of Starlette's `BackgroundTask`, so the whole list fits there. If the returned response's `background` is left as `None`, FastAPI attaches the injected `BackgroundTasks` to it for you.
- Does the client wait for the background tasks to finish?No. The status, headers and body are sent before the first task starts, so the client has the complete response. The server is still busy with that request until the tasks end, which matters for shutdown and for tests: `TestClient` returns only after the tasks have run.
A waiter brings your bill first and clears your table afterwards: the clearing happens on the same shift, by the same staff, in the order the jobs were noted, and nobody comes back for it if the restaurant shuts suddenly.
- add_task starts a separate worker process for every queued function
- Pass send_welcome_email(email) to add_task so the argument is bound
- Only async def functions can be used as background tasks
- Background tasks run alongside sending the response, in no fixed order
- Creating BackgroundTasks() inside the endpoint is enough for its tasks to run