Tips and Tricks

FastAPI

FastAPI shutdown events


FastAPI tip:

You can register functions to run before the application shutdown using @app.on_event("shutdown").

https://fastapi.tiangolo.com/advanced/events/#shutdown-event

For example. to send a message to an SNS topic where you track your app health 👇

import boto3
from fastapi import FastAPI


app = FastAPI()


@app.on_event("shutdown")
def publish_message():
    client = boto3.client('sns')
    client.publish(
        TopicArn='arn:aws:sns:us-east-1:12345678910112:application-health',
        Message='Application is shutting down',
    )


@app.get("/ping")
async def ping():
    return {"message": "pong"}