Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 30: Application Startup, Lifespan, and Hosting

ASP.NET Core has host startup, dependency registration, and app lifetime events. FastAPI uses lifespan events for startup and shutdown.

from contextlib import asynccontextmanager

from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.settings = Settings()
    app.state.http_client = httpx.AsyncClient(timeout=5)
    yield
    await app.state.http_client.aclose()


app = FastAPI(lifespan=lifespan)

Use lifespan for:

Do not do slow, fragile work in startup unless the app truly cannot serve without it. For migrations, prefer deployment steps over app startup migrations in most production systems.