Tips and Tricks

FastAPI

FastAPI startup events


FastAPI tip:

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

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

For example, to send a message to an AWS SNS topic where you track your app health:

import boto3
from fastapi import FastAPI


app = FastAPI()


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


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