Lifespan Events

noun

say it: “LYFE-span ih-VENTS” /ˈlaɪfˌspæn ɪˈvɛnts/

FastAPI's startup and shutdown code, written in one lifespan function: the part before yield runs once when the app starts, the part after when it stops.

What is Lifespan Events?

A lifespan function runs setup code before the app starts serving (open connections, load models) and cleanup code when it shuts down.

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = await connect()
    yield
    await app.state.db.close()

app = FastAPI(lifespan=lifespan)

In a sentence

  • “The lifespan events close the database connection when the app stops.”
  • “Migrations run in the app's lifespan events, before the first request arrives.”

Level: Freelancer · More FastAPI terms at this level

Updated