Build a Basic Health Check Route
Add a GET /health route to the FastAPI app in main.py. The route must return a JSON response with two fields: status (always the string "ok") and uptime_seconds (the number of whole seconds since the app started, as an integer).
Health checks are how load balancers, container orchestrators, and monitoring systems know whether your service is alive. The response shape needs to be exact — anything that polls /health compares against a hardcoded schema, so misspellings or wrong types break the integration.
The uptime field forces you to capture a reference timestamp at module-load time. Don't compute a fresh start time inside the handler — that would give you 0 on every request.
- Register a
GET /healthroute on the existing FastAPIappinstance inmain.py. - The route must respond with HTTP status code 200.
- The response body must be JSON with exactly two keys:
statusanduptime_seconds. statusmust always be the string"ok".uptime_secondsmust be a Pythonint(not afloat, not abool).uptime_secondsmust reflect whole seconds since the process started — it must grow monotonically across requests, never reset to 0 on a fresh request.
GET /health (immediately after the app starts)
200 OK
{"status": "ok", "uptime_seconds": 0}Right at boot, uptime hasn't accumulated a full second yet.
GET /health (10 seconds after the app starts)
200 OK
{"status": "ok", "uptime_seconds": 10}Uptime grows as the process keeps running. Always returns whole seconds, never fractional.
- Use FastAPI for route definition (the app object is already created in
main.py). - Response body must be valid JSON.
uptime_secondsmust be a Pythonint, not afloat.
How would you extend `/health` to also report the status of each external dependency (database, Redis, etc.) without making the route slow under normal traffic?
Keep moving through related backend basics problems and build a stronger search-friendly practice loop around this topic.
View track →