FastAPI - FastAPI Event Handlers



Event handlers are the functions to be executed when a certain identified event occurs. In FastAPI, two such events are identified − startup and shutdown. FastAPI’s application object has on_event() decorator that uses one of these events as an argument. The function registered with this decorator is fired when the corresponding event occurs.

The startup event occurs before the development server starts and the registered function is typically used to perform certain initialization tasks, establishing connection with the database etc. The event handler of shutdown event is called just before the application shutdown.

Example

Here is a simple example of startup and shutdown event handlers. As the app starts, the starting time is echoed in the console log. Similarly, when the server is stopped by pressing ctrl+c, the shutdown time is also displayed.

main.py

from fastapi import FastAPI
import datetime
app = FastAPI()
@app.on_event("startup")
async def startup_event():
   print('Server started :', datetime.datetime.now())
@app.on_event("shutdown")
async def shutdown_event():
   print('server Shutdown :', datetime.datetime.now())

Output

It will produce the following output −

uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
Server started: 2021-11-23 23:51:45.907691
INFO: Application startup complete.
INFO: Shutting down
INFO: Waiting for application
server Shutdown: 2021-11-23 23:51:50.82955
INFO: Application shutdown com
INFO: Finished server process
Advertisements