Overview

FastAPI 0.110, released on January 24, 2024, improves lifespan events for application resource management.

Main Features

Lifespan events

The lifespan context manager replaces the old on_startup and on_shutdown events for cleaner resource management.

python
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: initialize resources
    print('Initializing...')
    yield
    # Shutdown: release resources
    print('Cleaning up...')

app = FastAPI(lifespan=lifespan)

@app.get('/')
async def home():
    return {'message': 'Hello'}

Sources