FastAPI Startup Event
The Startup is the event triggered whenever the user starts the FastAPI app using the following command:
uvicorn main:app --reload
This event is basically handled to declare the variables that should be up at the start of the app. It uses the on_event function available in FastAPI to judge the event trigger.
Syntax:
@app.on_event(“startup”)
async def function_name():
print(Statement_startup)
Here,
- function_name: It is the function which you want to call while the startup event is triggered.
- Statement_startup: It is the statement under the startup function that will be executed.
Example: In this example, we have created a function event_startup, that gets triggered on the start of the FastAPI app and prints the date and time when the app has started.
Python3
from fastapi import FastAPI import datetime as dt app = FastAPI() # Handle the startup event @app .on_event( "startup" ) async def event_startup(): print ( 'FastAPI Server started :' , dt.datetime.now()) |
Output:
FastAPI – FastAPI Event Handlers
A Python framework that is used for building APIs is called FastAPI. There are some circumstances when the user needs to identify a certain event that happened in the API. This can be done using event handlers in FastAPI. In this article, we will study the various event handlers available in FastAPI.