The lifespan context manager helps you run setup and cleanup code when your FastAPI app starts and stops. It keeps your app organized and efficient.
Lifespan context manager in FastAPI
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): # setup code here yield # cleanup code here app = FastAPI(lifespan=lifespan)
The @asynccontextmanager decorator marks the function as a lifespan manager.
The code before yield runs at startup, and the code after yield runs at shutdown.
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): print('Starting app') yield print('Stopping app') app = FastAPI(lifespan=lifespan)
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): app.state.db = connect_to_db() yield app.state.db.disconnect()
This FastAPI app uses the lifespan context manager to print messages when starting and stopping. It also keeps a counter of visits stored in app.state. Each time you visit the root URL, the counter increases.
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): print('App is starting') app.state.counter = 0 yield print('App is stopping') app = FastAPI(lifespan=lifespan) @app.get('/') async def read_root(): app.state.counter += 1 return {"visits": app.state.counter}
Use app.state to store data you want to keep during the app's life.
The lifespan function must be async and use yield to separate startup and shutdown code.
FastAPI automatically calls the lifespan manager when the app runs with an ASGI server like Uvicorn.
The lifespan context manager runs code when your FastAPI app starts and stops.
Use it to set up and clean up resources like databases or background tasks.
It keeps your app organized and efficient by managing app-wide state.