How to Use Lifespan in FastAPI for Startup and Shutdown Events
In FastAPI, use the
lifespan parameter to define startup and shutdown actions by passing an async context manager function to the FastAPI constructor. This lets you run code before the app starts and after it stops, such as connecting to or closing resources.Syntax
The lifespan parameter in FastAPI expects an async generator function that yields control once during startup and resumes after shutdown. This function is passed to the FastAPI constructor.
Inside the async generator, code before yield runs at startup, and code after yield runs at shutdown.
python
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager def lifespan(app: FastAPI): # Startup code here print("Starting up") yield # Shutdown code here print("Shutting down") app = FastAPI(lifespan=lifespan)
Example
This example shows how to use lifespan to print messages on startup and shutdown. It simulates resource setup and cleanup.
python
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager def lifespan(app: FastAPI): print("Connecting to database...") # Simulate resource setup yield print("Closing database connection...") # Simulate resource cleanup app = FastAPI(lifespan=lifespan) @app.get("/") async def read_root(): return {"message": "Hello, FastAPI lifespan!"}
Output
Connecting to database...
# (App runs, serving requests)
# On shutdown:
Closing database connection...
Common Pitfalls
- Not using an async context manager function for
lifespancauses errors. - Forgetting to
yieldinside the lifespan function prevents startup or shutdown code from running properly. - Placing blocking code without
awaitcan freeze the app during startup or shutdown.
python
from fastapi import FastAPI # Wrong: lifespan is not an async context manager async def lifespan(app: FastAPI): print("Starting up") # Missing yield app = FastAPI(lifespan=lifespan) # This will cause runtime errors # Correct way: from contextlib import asynccontextmanager @asynccontextmanager def lifespan(app: FastAPI): print("Starting up") yield print("Shutting down")
Quick Reference
- lifespan function: async generator with
yieldto separate startup and shutdown code. - Use @asynccontextmanager: Decorate the lifespan function for clarity and correctness.
- Pass lifespan to FastAPI:
app = FastAPI(lifespan=lifespan). - Startup code: Runs before
yield. - Shutdown code: Runs after
yield.
Key Takeaways
Use an async context manager function with yield to define lifespan in FastAPI.
Startup code runs before yield; shutdown code runs after yield in the lifespan function.
Pass the lifespan function to FastAPI via the lifespan parameter when creating the app.
Always decorate the lifespan function with @asynccontextmanager for proper behavior.
Avoid blocking code in lifespan to keep the app responsive during startup and shutdown.