0
0
FastAPIframework~5 mins

Lifespan context manager in FastAPI

Choose your learning style9 modes available
Introduction

The lifespan context manager helps you run setup and cleanup code when your FastAPI app starts and stops. It keeps your app organized and efficient.

You want to connect to a database when the app starts and disconnect when it stops.
You need to load some data or configuration once before the app handles requests.
You want to start background tasks or services when the app launches and stop them on shutdown.
You want to clean up resources like files or network connections when the app closes.
Syntax
FastAPI
from fastapi import FastAPI
from contextlib import asynccontextmanager

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

app = FastAPI(lifespan=lifespan)

The @asynccontextmanager decorator marks the function as a lifespan manager.

The code before yield runs at startup, and the code after yield runs at shutdown.

Examples
This example prints messages when the app starts and stops.
FastAPI
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    print('Starting app')
    yield
    print('Stopping app')

app = FastAPI(lifespan=lifespan)
This example connects to a database on startup and disconnects on shutdown.
FastAPI
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = connect_to_db()
    yield
    app.state.db.disconnect()
Sample Program

This FastAPI app uses the lifespan context manager to print messages when starting and stopping. It also keeps a counter of visits stored in app.state. Each time you visit the root URL, the counter increases.

FastAPI
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    print('App is starting')
    app.state.counter = 0
    yield
    print('App is stopping')

app = FastAPI(lifespan=lifespan)

@app.get('/')
async def read_root():
    app.state.counter += 1
    return {"visits": app.state.counter}
OutputSuccess
Important Notes

Use app.state to store data you want to keep during the app's life.

The lifespan function must be async and use yield to separate startup and shutdown code.

FastAPI automatically calls the lifespan manager when the app runs with an ASGI server like Uvicorn.

Summary

The lifespan context manager runs code when your FastAPI app starts and stops.

Use it to set up and clean up resources like databases or background tasks.

It keeps your app organized and efficient by managing app-wide state.