Settings, Logs and Health

Make an API ready for real users: settings read and checked when it starts, logs that tell you what happened without leaking anything, and a health check plus a clean startup and shutdown a host can rely on. Then you'll get a campus shuttle API ready for riders.

Updated

Settings

  1. Settings Checked at Startup (Journeyman): An API reads every setting it needs from environment variables, or from a .env file on your own computer, through one pydantic-settings BaseSettings class that gives each setting a type and a default, so a missing or mistyped setting stops the app as it starts, with a message naming every problem, instead of crashing a later request.

Logs and Health

  1. Logging an API (Journeyman): A server's code reports what it does through Python's logging module instead of print, with a logger per module, levels from DEBUG to ERROR, a format with the time and level, one line for every request written by a middleware, and a logging.Filter that keeps passwords and tokens out of every line.
  2. Startup, Shutdown and a Health Check (Freelancer): 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.

Exercise: Shuttle Schedule API

  1. Exercise: Shuttle Schedule API (Journeyman): Get a campus shuttle's FastAPI app ready for real riders, with pydantic-settings that stop it at startup naming every missing setting, a request line for every request, a logging filter that hides passwords and tokens, a lifespan that runs the migrations, and a /health route that answers 200 or 503.