0
0
FastAPIframework~10 mins

Lifespan context manager in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lifespan context manager
Start Application
Enter Lifespan Context
Run Startup Code
Serve Requests
Receive Shutdown Signal
Run Shutdown Code
Exit Lifespan Context
Application Stops
The lifespan context manager runs startup code before serving requests and shutdown code when stopping the app.
Execution Sample
FastAPI
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
def lifespan(app: FastAPI):
    print('Starting up')
    yield
    print('Shutting down')

app = FastAPI(lifespan=lifespan)
Defines a lifespan context manager that prints messages on startup and shutdown of the FastAPI app.
Execution Table
StepActionOutputState
1Application startsNo output yetApp created, lifespan context ready
2Enter lifespan contextPrint 'Starting up'Startup code runs
3Yield controlApp ready to serve requestsServing requests
4Receive shutdown signalNo outputPreparing to shutdown
5Exit lifespan contextPrint 'Shutting down'Shutdown code runs
6Application stopsNo outputApp stopped
💡 Application stops after shutdown code runs and lifespan context exits
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5Final
app_stateinitializedstartup completeservingshutdown completestopped
Key Moments - 3 Insights
Why does the startup code run before serving requests?
Because the lifespan context manager runs the code before the yield statement first, as shown in step 2 of the execution table.
When does the shutdown code run?
The shutdown code runs after the app receives a shutdown signal and the lifespan context exits, as shown in step 5.
What happens between the yield and the shutdown code?
The app serves requests during this time, indicated by the state 'serving' after step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the app state after step 3?
Astartup complete
Bserving
Cshutdown complete
Dinitialized
💡 Hint
Check the 'State' column for step 3 in the execution table.
At which step does the shutdown code print 'Shutting down'?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look for the 'Print "Shutting down"' output in the execution table.
If the yield statement was removed, what would happen?
AStartup and shutdown code run immediately, no serving requests
BApp serves requests normally
CShutdown code never runs
DApp crashes on start
💡 Hint
Yield pauses startup to serve requests; without it, code runs all at once.
Concept Snapshot
Lifespan context manager in FastAPI:
- Use @asynccontextmanager to define startup and shutdown code.
- Code before yield runs on startup.
- Code after yield runs on shutdown.
- FastAPI app uses lifespan= parameter.
- Controls app lifecycle cleanly.
Full Transcript
The lifespan context manager in FastAPI controls what happens when the app starts and stops. When the app starts, it enters the lifespan context and runs the startup code before serving any requests. This is shown by the print statement 'Starting up'. Then the app serves requests while the code after yield is paused. When the app receives a shutdown signal, it exits the lifespan context and runs the shutdown code, printing 'Shutting down'. This cleanly manages resources and setup/teardown logic. The execution table shows each step and the app state changes from initialized to serving to stopped. The variable tracker follows the app state through these steps. Understanding this flow helps beginners see how FastAPI manages app lifecycle with the lifespan context manager.