Skip to content
masterclass Buddy

FastAPI · Pipe

lifespan

Use FastAPI's lifespan parameter to run setup before requests and cleanup after the application stops. Put setup before yield and cleanup after yield in an async context manager.

Last updated

Syntax

@asynccontextmanager
async def lifespan(app: FastAPI):
    # setup
    yield
    # cleanup

app = FastAPI(lifespan=lifespan)

In-depth API docs are only for subscribers: parameters, examples, common mistakes and interview practice.

Subscribe
  • FastAPI
  • asynccontextmanager
  • TestClient
  • on_event
  • startup
  • shutdown

Source: Lifespan Events - FastAPI. Checked 2026-11-03.