FastAPI runs startup and shutdown handlers for initialization/cleanup.
1from fastapi import FastAPI2from contextlib import asynccontextmanager34# Modern approach (FastAPI 0.93+)5@asynccontextmanager6async def lifespan(app: FastAPI):7 # Startup8 print("Starting up...")9 db = await create_db_connection()10 app.state.db = db1112 yield # Application runs here1314 # Shutdown15 print("Shutting down...")16 await db.close()1718app = FastAPI(lifespan=lifespan)1920@app.get("/items/")21async def get_items():22 db = app.state.db23 return await db.fetch_all("items")2425# Legacy approach26app = FastAPI()2728@app.on_event("startup")29async def startup():30 print("Starting up...")3132@app.on_event("shutdown")33async def shutdown():34 print("Shutting down...")
Common uses: