0
0
FastAPIframework~5 mins

Startup and shutdown events in FastAPI

Choose your learning style9 modes available
Introduction

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")
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
This prints a message when the app starts.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def 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")
async def 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")
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)
OutputSuccess
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.