Python Health Check Server
A standard-library HTTP server with health and JSON 404 endpoints, plus unittest coverage that starts the server on an ephemeral port.
Project
python-health-server
Entry point: health.py
Install
python --versionRun
python health.pyTest
python -m unittest -v test_health.pyExpected output
GET /healthz returns {"status":"ok"}, GET / returns the service name, and unknown paths return 404 JSON.Dependencies
- python >=3.10
Verification evidence
Python 3.11.7: python -m unittest -v test_health.py -> 2 tests passed, covering 200 health and 404 unknown path.
Security note
The example binds to localhost and has no authentication; put it behind a proxy and restrict access before exposing diagnostics.
What it does
Starts a threaded HTTP server with two JSON endpoints. The handler suppresses access logs and returns JSON for every path.
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
self._json(200, {"status": "ok"})
elif self.path == "/":
self._json(200, {"service": "health-server"})
else:
self._json(404, {"error": "not found"})
def _json(self, status, body):
data = json.dumps(body).encode("utf-8")
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
def create_server(host="127.0.0.1", port=0):
return ThreadingHTTPServer((host, port), Handler)
if __name__ == "__main__":
server = create_server(port=8000)
print("listening on 8000")
server.serve_forever()
Test
import json
import threading
import unittest
import urllib.request
from health import create_server
class HealthServerTest(unittest.TestCase):
def setUp(self):
self.server = create_server()
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.base = f"http://127.0.0.1:{self.server.server_port}"
def tearDown(self):
self.server.shutdown()
self.server.server_close()
def test_health(self):
with urllib.request.urlopen(self.base + "/healthz") as response:
self.assertEqual(response.status, 200)
self.assertEqual(json.load(response), {"status": "ok"})
def test_not_found(self):
with self.assertRaises(urllib.error.HTTPError) as context:
urllib.request.urlopen(self.base + "/missing")
self.assertEqual(context.exception.code, 404)
if __name__ == "__main__":
unittest.main()
Run and verify
python -m unittest -v test_health.py
python health.py
curl -s http://127.0.0.1:8000/healthz
Expected output: GET /healthz returns {"status":"ok"}, GET / returns the service name, and unknown paths return 404 JSON. Verified with Python 3.11.7: both unittest tests passed.
Limitations
ThreadingHTTPServer is suitable for small internal services, not high-throughput production workloads. It has no graceful shutdown, TLS, or readiness dependency checks.