0
0
FastapiHow-ToBeginner · 3 min read

How to Use Events in FastAPI: Startup and Shutdown Handlers

In FastAPI, you use @app.on_event('startup') and @app.on_event('shutdown') decorators to run code when the app starts or stops. These event handlers help initialize resources or clean up before the app shuts down.
📐

Syntax

FastAPI provides two main event types: startup and shutdown. You add functions decorated with @app.on_event('startup') to run code when the app starts, and @app.on_event('shutdown') for code when the app stops.

Each decorated function should be async or regular functions without parameters.

python
from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    print("App is starting up")

@app.on_event("shutdown")
async def shutdown_event():
    print("App is shutting down")
💻

Example

This example shows how to print messages when the FastAPI app starts and stops. It demonstrates initializing and cleaning up resources using event handlers.

python
from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    print("Starting up: connect to database or initialize resources")
    await asyncio.sleep(1)  # simulate async setup

@app.on_event("shutdown")
async def shutdown_event():
    print("Shutting down: close database connections or cleanup")
    await asyncio.sleep(1)  # simulate async cleanup

@app.get("/")
async def read_root():
    return {"message": "Hello World"}
Output
Starting up: connect to database or initialize resources Shutting down: close database connections or cleanup
⚠️

Common Pitfalls

  • Forgetting to use async on event functions when doing async operations can cause unexpected behavior.
  • Not awaiting async calls inside event handlers can lead to incomplete setup or cleanup.
  • Trying to pass parameters to event functions is not supported; they must be parameterless.
  • Using print statements for important startup tasks is not reliable in production; use proper logging.
python
from fastapi import FastAPI

app = FastAPI()

# Wrong: event function with parameters
@app.on_event("startup")
def startup_event(param):
    print("This will cause an error")

# Right: parameterless async function
@app.on_event("startup")
async def startup_event():
    print("Correct startup event")
📊

Quick Reference

Use these event decorators to manage app lifecycle tasks:

  • @app.on_event('startup'): Run code before the app starts serving requests.
  • @app.on_event('shutdown'): Run code before the app stops.

Event functions must be async or regular functions without parameters.

Key Takeaways

Use @app.on_event('startup') to run code when FastAPI starts.
Use @app.on_event('shutdown') to run cleanup code before FastAPI stops.
Event handler functions must be parameterless and can be async.
Always await async operations inside event handlers to ensure completion.
Avoid passing parameters to event functions; keep them simple.