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
#[derive(Debug, Clone, PartialEq)] pub enum Token { Number(f64), Plus,
How a tokenizer turns text into tokens
lexing
enums
iterators
Intermediate
8 steps
python
import pandas as pd import numpy as np
Cleaning a customer DataFrame with pandas
data-cleaning
regex
normalization
Intermediate
9 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
typescript
import { ArgumentsHost, Catch, ConflictException,
Turning TypeORM lock errors into 409s in NestJS
exception-handling
optimistic-locking
http-status
Intermediate
6 steps
python
from collections.abc import MutableMapping class CaseInsensitiveDict(MutableMapping):
Building a case-insensitive dict in Python
data structures
abstract base classes
dunder methods
Intermediate
8 steps
go
package middleware import ( "net/http"
Role-based access control middleware in Gin
middleware
authorization
closures
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.