Startup and shutdown events let your app run code when it starts or stops. This helps prepare or clean up resources.
Startup and shutdown events in FastAPI
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
FastAPI
from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_event(): # code to run on startup @app.on_event("shutdown") async def 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
FastAPI
from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def startup_event(): print("App is starting")
FastAPI
from fastapi import FastAPI app = FastAPI() @app.on_event("shutdown") async def shutdown_event(): print("App is stopping")
FastAPI
from fastapi import FastAPI app = FastAPI() @app.on_event("startup") async def connect_db(): print("Connecting to database...") @app.on_event("shutdown") async def 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.
FastAPI
from fastapi import FastAPI import uvicorn app = FastAPI() @app.on_event("startup") async def startup_event(): print("Starting up: preparing resources") @app.on_event("shutdown") async def shutdown_event(): print("Shutting down: cleaning up resources") @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"} if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000)
Important Notes
Startup and shutdown functions should be async for best performance.
These events run once when the app starts or stops, not on every request.
Use these events to manage resources like database connections or caches.
Summary
Startup and shutdown events run code when the app starts or stops.
Use @app.on_event("startup") and @app.on_event("shutdown") decorators.
They help prepare and clean up resources for your app.
Practice
1. What is the main purpose of using
@app.on_event("startup") in a FastAPI application?easy
Solution
Step 1: Understand the startup event role
The@app.on_event("startup")decorator marks a function to run when the app starts, useful for setup tasks.Step 2: Differentiate from other app parts
Handling requests or shutting down are different concerns; startup is specifically for initialization.Final Answer:
To run code when the application starts, like initializing resources. -> Option DQuick Check:
Startup event = run code at app start [OK]
Hint: Startup event runs code once when app launches [OK]
Common Mistakes:
- Confusing startup with request handling
- Thinking startup runs multiple times per request
- Mixing startup with shutdown event
2. Which of the following is the correct syntax to define a shutdown event handler in FastAPI?
easy
Solution
Step 1: Recall correct decorator for shutdown
The correct decorator is@app.on_event("shutdown")to run code when the app stops.Step 2: Check syntax correctness
Options A, B, and D use incorrect decorator names or syntax.Final Answer:
@app.on_event("shutdown")\ndef cleanup():\n print("Cleaning up") -> Option CQuick Check:
Shutdown event decorator = @app.on_event("shutdown") [OK]
Hint: Shutdown event uses @app.on_event("shutdown") exactly [OK]
Common Mistakes:
- Using wrong event name like "start" instead of "shutdown"
- Missing @app.on_event decorator
- Using non-existent decorators like @app.shutdown_event
3. Consider this FastAPI code snippet:
What will be printed when the server starts and then stops?
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print("Starting app")
@app.on_event("shutdown")
async def shutdown_event():
print("Stopping app")
@app.get("/")
async def read_root():
return {"message": "Hello"}What will be printed when the server starts and then stops?
medium
Solution
Step 1: Identify startup and shutdown prints
Thestartup_eventprints "Starting app" when the app starts, andshutdown_eventprints "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 BQuick 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:
What is the problem?
from fastapi import FastAPI
app = FastAPI()
def shutdown_event():
print("App is stopping")
app.on_event("shutdown", shutdown_event)What is the problem?
medium
Solution
Step 1: Check decorator usage
The code usesapp.on_event("shutdown", shutdown_event)which incorrectly passes two arguments toon_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 AQuick 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
Solution
Step 1: Understand global variable usage
Sincedbis defined outside functions, to modify it inside functions,global dbis needed.Step 2: Check startup and shutdown logic
The correct version usesglobal dbin both async event handlers, settingdb = "Connected"on startup anddb = Noneon shutdown. Versions withoutglobal dbcreate 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 AQuick 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
