python 27 lines · 6 steps

Building a health check endpoint in Flask

A /healthz route probes the database and reports overall service health with the right HTTP status code.

Explained by highlit
1from flask import Blueprint, jsonify
2from sqlalchemy import text
3from sqlalchemy.exc import SQLAlchemyError
4 
5from .extensions import db
6 
7health_bp = Blueprint("health", __name__)
8 
9 
10@health_bp.get("/healthz")
11def healthz():
12 checks = {"database": _check_database()}
13 healthy = all(component["ok"] for component in checks.values())
14 payload = {
15 "status": "ok" if healthy else "degraded",
16 "checks": checks,
17 }
18 return jsonify(payload), 200 if healthy else 503
19 
20 
21def _check_database():
22 try:
23 db.session.execute(text("SELECT 1"))
24 except SQLAlchemyError as exc:
25 db.session.rollback()
26 return {"ok": False, "error": str(exc.__cause__ or exc)}
27 return {"ok": True}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A liveness endpoint should actually exercise dependencies, not just return a static 200.
  2. 2Return 503 when a component is degraded so load balancers and orchestrators can react correctly.
  3. 3Catch dependency exceptions and roll back so one failed probe doesn't poison the session.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a health check endpoint in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code