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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A liveness endpoint should actually exercise dependencies, not just return a static 200.
- 2Return 503 when a component is degraded so load balancers and orchestrators can react correctly.
- 3Catch dependency exceptions and roll back so one failed probe doesn't poison the session.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-health-check-endpoint-in-flask-explained-python-1ad6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.