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.


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.

from fastapi import FastAPI
import datetime
app = FastAPI()
async def startup_event():
   print('Server started :',
async def shutdown_event():
   print('server Shutdown :',


It will produce the following output −

uvicorn main:app --reload
INFO: Uvicorn running on (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