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.
fromfastapiimportBackgroundTasks,FastAPIapp=FastAPI()defwrite_notification(email:str,message=""):withopen("log.txt",mode="w")asemail_file:content=f"notification for {email}: {message}"email_file.write(content)@app.post("/send-notification/{email}")asyncdefsend_notification(email:str,background_tasks:BackgroundTasks):background_tasks.add_task(write_notification,email,message="some notification")return{"message":"Notification sent in the background"}
It can be a regular def function or an async def function.
TYPE:Callable[P, Any]
*args
TYPE:argsDEFAULT:()
**kwargs
TYPE:kwargsDEFAULT:{}
Source code in fastapi/background.py
38394041424344454647484950515253545556575859
defadd_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/). """returnsuper().add_task(func,*args,**kwargs)