Background tasks let your app do work after sending a response. This keeps the app fast and smooth for users.
Background tasks in FastAPI
from fastapi import BackgroundTasks from fastapi import FastAPI app = FastAPI() async def some_task(param: str): # task code here pass @app.post("/endpoint") async def endpoint(background_tasks: BackgroundTasks): background_tasks.add_task(some_task, "value") return {"message": "Task started"}
Use BackgroundTasks parameter in your path operation function.
Add tasks with background_tasks.add_task(function, args).
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as f: f.write(message + "\n") @app.post("/send") async def send(background_tasks: BackgroundTasks): background_tasks.add_task(write_log, "User sent data") return {"status": "Log task added"}
from fastapi import FastAPI, BackgroundTasks app = FastAPI() async def send_email(email: str): # pretend to send email print(f"Email sent to {email}") @app.post("/signup") async def signup(background_tasks: BackgroundTasks): background_tasks.add_task(send_email, "user@example.com") return {"message": "Signup complete"}
This FastAPI app has a POST endpoint '/process'. When called, it immediately returns a message. Meanwhile, it writes "Process started" to a file named 'log.txt' in the background.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as f: f.write(message + "\n") @app.post("/process") async def process(background_tasks: BackgroundTasks): background_tasks.add_task(write_log, "Process started") return {"message": "Processing started"}
Background tasks run after the response is sent, so they don't delay the user.
They are good for simple tasks, but not for heavy or long-running jobs.
For complex jobs, consider using a task queue like Celery.
Background tasks let you run code after sending a response.
Use BackgroundTasks and add_task to add tasks.
Great for sending emails, logging, or cleanup without slowing users.
Practice
BackgroundTasks in FastAPI?Solution
Step 1: Understand what BackgroundTasks do
BackgroundTasks allow running code after the response is sent, so the user is not delayed.Step 2: Compare options with this behavior
Only To run code after sending the response without delaying the user describes running code after response without delay; others describe blocking or unrelated tasks.Final Answer:
To run code after sending the response without delaying the user -> Option DQuick Check:
BackgroundTasks run code after response = B [OK]
- Thinking BackgroundTasks block the response
- Confusing BackgroundTasks with synchronous code
- Assuming BackgroundTasks replace main event loop
Solution
Step 1: Recall how to add background tasks in FastAPI
You add tasks by callingbackground_tasks.add_task(function, args)inside the endpoint function.Step 2: Check each option
Usebackground_tasks.add_task(your_function, arg1, arg2)inside the endpoint correctly usesadd_task. Callyour_function()directly inside the endpoint calls function immediately, blocking. Useawait your_function()inside the endpoint awaits function, blocking. ImportBackgroundTasksbut do not use it does nothing.Final Answer:
Use background_tasks.add_task(your_function, arg1, arg2) inside the endpoint -> Option CQuick Check:
Use add_task to schedule background work = D [OK]
- Calling the function directly instead of scheduling
- Awaiting the function which blocks response
- Importing BackgroundTasks but not using it
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
print(f"Log: {message}")
@app.get("/items/{item_id}")
async def read_item(item_id: int, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"Item {item_id} accessed")
return {"item_id": item_id}Solution
Step 1: Understand background task behavior
The functionwrite_logis scheduled as a background task, so it runs after the response is sent.Step 2: Analyze print timing
Print insidewrite_logwill execute after response, printing the log message with the item_id value.Final Answer:
Log: Item {item_id} accessed is printed after response -> Option AQuick Check:
Background task runs after response = C [OK]
- Thinking print runs before response
- Assuming print won't run without await
- Missing import of BackgroundTasks (actually imported here)
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def send_email(email: str):
print(f"Sending email to {email}")
@app.post("/send")
async def send(background_tasks: BackgroundTasks, email: str):
background_tasks.add_task(send_email)
return {"message": "Email scheduled"}Solution
Step 1: Check how add_task is called
The functionsend_emailrequires an argumentemail, butadd_taskis called without arguments.Step 2: Identify the missing argument
The call should bebackground_tasks.add_task(send_email, email)to pass the email parameter.Final Answer:
Missing argument when adding task to background_tasks -> Option AQuick Check:
add_task needs function arguments = A [OK]
- Forgetting to pass required arguments to add_task
- Thinking BackgroundTasks can't be a parameter
- Assuming send_email must be async
Solution
Step 1: Understand the goal
We want to run both logging and sending email after response without delaying user.Step 2: Evaluate options
Add two background tasks: one for logging, one for sending email, both added viabackground_tasks.add_taskschedules both tasks as background tasks, so they run after response. Options B and C block response. Run logging in background task but send email synchronously delays sending email.Final Answer:
Add two background tasks: one for logging, one for sending email, both added via background_tasks.add_task -> Option BQuick Check:
Schedule all post-response tasks with add_task = A [OK]
- Running tasks synchronously blocking response
- Mixing sync and async incorrectly
- Scheduling only one task in background
Ready to prove it?
Pass the test and this pattern moves unknown
