Introduction to Lifespan Events in FastAPI
New implementation for startup and shutdown logic
By reading this piece, you will learn to implement lifespan events in your FastAPI for startup and shutdown logic. From version 0.93.0
onward, the fastapi
module officially supports the lifespan
event, which replaces the startup
and shutdown
events.
startup and shutdown events will be deprecated in the future release.
One main advantage of lifespan event is that all the logic can be implemented in a single function. Also, the code for the startup
and shutdown
events has to be implemented after the initialization of the FastAPI
instance.
The lifespan
event simplify the entire process by having only a single function which has to be declared before the FastAPI
instantiation.
Let’s proceed to the next section to learn more about the differences.
Old Method
Have a look at the following example server which uses the startup
and shutdown
events for model initialization:
import random
from fastapi import FastAPI
sentiments = ["positive", "neutral", "negative"]
def fake_answer(text: str):
return random.choice(sentiments)
app = FastAPI()
@app.on_event("startup")
async def startup_event():
app.state.models = {}…