Startup, Shutdown and a Health Check

FastAPI's lifespan function runs code once as the app starts, such as the migrations, and once as it stops, a TestClient used in a with block runs it in tests, and a /health route that asks the database a real question answers 200 when the API can do its job and 503 in the one error shape when it can't, which is what a host checks before it sends anyone to the app.

By

Updated

Cheat sheet: Startup, Shutdown and a Health Check
Category
FastAPI
Level
Freelancer
Tags
503 Service Unavailable, Context Manager, fastapi, Health Check (rest-api), Lifespan Events, rest-api