Startup and shutdown events let your app run code when it starts or stops. This helps prepare or clean up resources.
Connect to a database when the app starts
Load configuration or cache data before handling requests
Close database connections or files when the app stops
Log messages to track app start and stop times
Syntax
FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
asyncdef startup_event():
# code to run on startup
@app.on_event("shutdown")
asyncdef shutdown_event():
# code to run on shutdown
Use @app.on_event("startup") to run code when the app starts.
Use @app.on_event("shutdown") to run code when the app stops.
Examples
This prints a message when the app starts.
FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
asyncdef startup_event():
print("App is starting")
This prints a message when the app stops.
FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.on_event("shutdown")
asyncdef shutdown_event():
print("App is stopping")
This simulates connecting and closing a database on startup and shutdown.
FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
asyncdef connect_db():
print("Connecting to database...")
@app.on_event("shutdown")
asyncdef close_db():
print("Closing database connection...")
Sample Program
This FastAPI app prints messages when it starts and stops. It also has a simple route that returns a greeting.
What will be printed when the server starts and then stops?
medium
A. Stopping app (on start), Starting app (on shutdown)
B. Starting app (on start), Stopping app (on shutdown)
C. Only Starting app when server starts
D. No output printed at all
Solution
Step 1: Identify startup and shutdown prints
The startup_event prints "Starting app" when the app starts, and shutdown_event prints "Stopping app" when the app stops.
Step 2: Understand event timing
These events run once each: startup at launch, shutdown at server stop.
Final Answer:
Starting app (on start), Stopping app (on shutdown) -> Option B
Quick Check:
Startup prints "Starting app", shutdown prints "Stopping app" [OK]
Hint: Startup prints on launch, shutdown prints on stop [OK]
Common Mistakes:
Swapping startup and shutdown outputs
Expecting prints on every request
Thinking no output occurs without explicit call
4. This FastAPI code is intended to print a message on shutdown but does not work:
from fastapi import FastAPI
app = FastAPI()
def shutdown_event():
print("App is stopping")
app.on_event("shutdown", shutdown_event)
What is the problem?
medium
A. The decorator syntax is incorrect; should use @app.on_event("shutdown") above the function.
B. FastAPI does not support shutdown events.
C. The function name must be shutdown_handler, not shutdown_event.
D. The function must be async to work as an event handler.
Solution
Step 1: Check decorator usage
The code uses app.on_event("shutdown", shutdown_event) which incorrectly passes two arguments to on_event; it expects only the event name and returns a decorator to apply to a function.
Step 2: Identify common mistake
FastAPI expects the decorator syntax @app.on_event("shutdown") placed above the function definition for clarity and proper registration.
Final Answer:
The decorator syntax is incorrect; should use @app.on_event("shutdown") above the function. -> Option A
Quick Check:
Use @app.on_event("shutdown") decorator syntax [OK]
Hint: Always use @app.on_event("shutdown") decorator syntax [OK]
Common Mistakes:
Assuming function must be async (it can be sync)
Using wrong function names
Believing FastAPI lacks shutdown support
5. You want to open a database connection when your FastAPI app starts and close it when it stops. Which code correctly uses startup and shutdown events to do this?
from fastapi import FastAPI
app = FastAPI()
db = None
# Option A
@app.on_event("startup")
async def connect_db():
global db
db = "Connected"
@app.on_event("shutdown")
async def close_db():
global db
db = None
# Option B
@app.on_event("startup")
def connect_db():
db = "Connected"
@app.on_event("shutdown")
def close_db():
db = None
# Option C
@app.on_event("startup")
async def connect_db():
db = "Connected"
@app.on_event("shutdown")
async def close_db():
db = None
# Option D
@app.on_event("startup")
async def connect_db():
global db
db = None
@app.on_event("shutdown")
async def close_db():
global db
db = "Connected"
hard
A. Option A correctly manages the global db connection on startup and shutdown.
B. Option B correctly manages db without global keyword.
C. Option C correctly manages db asynchronously without global keyword.
D. Option D reverses connection and disconnection logic.
Solution
Step 1: Understand global variable usage
Since db is defined outside functions, to modify it inside functions, global db is needed.
Step 2: Check startup and shutdown logic
The correct version uses global db in both async event handlers, setting db = "Connected" on startup and db = None on shutdown. Versions without global db create local variables. One version reverses the connection and disconnection logic.
Final Answer:
Option A correctly manages the global db connection on startup and shutdown. -> Option A
Quick Check:
Use global to modify external variables in event handlers [OK]
Hint: Use global keyword to modify external variables inside event functions [OK]
Common Mistakes:
Forgetting global keyword causes local variable shadowing
Reversing startup and shutdown logic
Assuming async is required for all event handlers
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.