What is a FastAPI health check endpoint? A health check endpoint is a dedicated API route (typically /health) that returns the status of your application and its dependencies. In FastAPI, you can create health check endpoints using a simple @app.get("/health") decorator that returns JSON indicating whether your service is healthy.
Here's a basic FastAPI health check example:
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
async def health_check():
return {"status": "healthy"}This guide covers everything from basic health check implementation to advanced patterns including database checks, Kubernetes probes (/live and /ready), Docker integration, and production best practices.
Join the Index.dev talent network and get matched with impactful Python projects across the US, UK, and EU.
FastAPI Health Check: Quick Reference
Pattern | Endpoint | Purpose | HTTP Status |
|---|---|---|---|
Basic Health | /health | Simple alive check | 200 OK / 503 Unavailable |
Liveness Probe | /live or /livez | Is the app running? | 200 OK |
Readiness Probe | /ready or /readyz | Can app handle traffic? | 200 OK / 503 Unavailable |
Deep Health | /health/detailed | Check all dependencies | 200 OK with JSON status |
Common Response Formats:
python
# Minimal response
{"status": "healthy"}
# Detailed response
{
"status": "healthy",
"checks": {
"database": "connected",
"redis": "connected",
"disk_space": "ok"
},
"timestamp": "2025-01-15T10:30:00Z"
}
FastAPI Health Check Endpoint Example
The following examples show progressively more sophisticated health check implementations in FastAPI.
Example 1: Basic Health Check Endpoint
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/health")
async def health_check():
return JSONResponse(
content={"status": "healthy"},
status_code=200
)Example 2: Health Check with Database Connection
python
from fastapi import FastAPI, Depends
from fastapi.responses import JSONResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
import asyncio
app = FastAPI()
async def check_database(session: AsyncSession) -> bool:
try:
await asyncio.wait_for(
session.execute(text("SELECT 1")),
timeout=5.0
)
return True
except Exception:
return False
@app.get("/health")
async def health_check(db: AsyncSession = Depends(get_db)):
db_healthy = await check_database(db)
if db_healthy:
return JSONResponse(
content={"status": "healthy", "database": "connected"},
status_code=200
)
else:
return JSONResponse(
content={"status": "unhealthy", "database": "disconnected"},
status_code=503
)Example 3: Health Check with Multiple Dependencies
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import asyncio
import aioredis
from datetime import datetime
app = FastAPI()
async def check_database() -> dict:
try:
# Your database check logic
return {"status": "healthy", "latency_ms": 5}
except Exception as e:
return {"status": "unhealthy", "error": str(e)}
async def check_redis() -> dict:
try:
redis = aioredis.from_url("redis://localhost")
await redis.ping()
return {"status": "healthy"}
except Exception as e:
return {"status": "unhealthy", "error": str(e)}
async def check_external_api() -> dict:
try:
# Your external API check
return {"status": "healthy"}
except Exception as e:
return {"status": "unhealthy", "error": str(e)}
@app.get("/health")
async def health_check():
# Run all checks in parallel
db_check, redis_check, api_check = await asyncio.gather(
check_database(),
check_redis(),
check_external_api()
)
checks = {
"database": db_check,
"redis": redis_check,
"external_api": api_check
}
all_healthy = all(
check["status"] == "healthy"
for check in checks.values()
)
return JSONResponse(
content={
"status": "healthy" if all_healthy else "unhealthy",
"timestamp": datetime.utcnow().isoformat(),
"checks": checks
},
status_code=200 if all_healthy else 503
)
Basic Health Check Using Built-in Tools
Let's begin with a basic system health check utilizing Python's built-in modules, such as os and subprocess, before moving on to web apps.
System Resource Check with os Module
Basic system resources like CPU, memory, and disk use may be checked. This will help us determine the general health of the computer that is executing our application.
import os
import psutil # You need to install psutil
def check_system_health():
# CPU usage
cpu_usage = psutil.cpu_percent(interval=1)
# Memory usage
memory_info = psutil.virtual_memory()
# Disk usage
disk_usage = psutil.disk_usage('/')
return {
'cpu_usage': f'{cpu_usage}%',
'memory_usage': f'{memory_info.percent}%',
'disk_usage': f'{disk_usage.percent}%'
}
if __name__ == "__main__":
print(check_system_health())In this example, the CPU, RAM, and disk utilization are checked using the psutil library. It offers insightful information about the machine's general state of health.
Service Availability Check with subprocess
We occasionally need to confirm that a certain service is operational. For instance, to see if a service is available, we can ping it with subprocess.
import subprocess
def ping_service(service_url):
response = subprocess.run(['ping', '-c', '1', service_url], stdout=subprocess.PIPE)
return response.returncode == 0
if __name__ == "__main__":
print(ping_service('google.com'))This straightforward ping function determines if a service (such a database or an external API) can be reached. The service is up if the result is True.
Need FastAPI expertise for your project? See our guide to hiring Python developers through Index.dev.
Implementing Health Checks in Web Applications
Web applications frequently use a variety of resources and services. An application may depend on external APIs, databases, and third-party authentication services, for instance. With frameworks like Flask and FastAPI, you may define health check endpoints to verify the overall health of the system.
Flask Health Check
This tutorial explains how to set up a basic Flask health check endpoint that verifies the functionality of an external API and database.
from flask import Flask, jsonify
import requests
import psycopg2
app = Flask(__name__)
def check_database():
try:
connection = psycopg2.connect(database="mydb", user="myuser", password="mypassword")
return True
except:
return False
def check_external_service():
try:
response = requests.get('https://jsonplaceholder.typicode.com/posts')
return response.status_code == 200
except:
return False
@app.route('/health', methods=['GET'])
def health_check():
db_status = check_database()
api_status = check_external_service()
return jsonify({
'database': 'up' if db_status else 'down',
'external_api': 'up' if api_status else 'down'
})
if __name__ == "__main__":
app.run(debug=True)The /health endpoint in this example performs database and external API checks. If each service is up and running, it provides a JSON answer.
FastAPI Health Check
FastAPI is a fantastic option for large-scale applications with numerous concurrent requests since it provides an asynchronous alternative to Flask. Here is an example of a basic FastAPI health check.
from fastapi import FastAPI
import httpx
import asyncpg
app = FastAPI()
async def check_database():
try:
connection = await asyncpg.connect(user='myuser', password='mypassword', database='mydb', host='127.0.0.1')
await connection.close()
return True
except:
return False
async def check_external_service():
try:
async with httpx.AsyncClient() as client:
response = await client.get('https://jsonplaceholder.typicode.com/posts')
return response.status_code == 200
except:
return False
@app.get("/health")
async def health_check():
db_status = await check_database()
api_status = await check_external_service()
return {
"database": "up" if db_status else "down",
"external_api": "up" if api_status else "down"
}This example demonstrates an asynchronous technique that is very scalable by using httpx for the API request and asyncpg for the database.
Read Also: How to Use Regex for String Replacement in Python
Monitoring Database Connections
It's critical to make sure the database connection is stable for programs that depend on databases. This is how to use Python to check database connection.
import sqlite3
def check_db_connection():
try:
connection = sqlite3.connect('example.db')
connection.execute("SELECT 1")
connection.close()
return True
except sqlite3.Error:
return False
if __name__ == "__main__":
print("Database is healthy" if check_db_connection() else "Database connection failed")In this example, the connection's status is checked using a straightforward SQL query.
Monitoring External Dependencies
A lot of applications rely on third-party APIs. Keeping an eye on these dependencies guarantees that your program runs properly. This is an example of how to verify the health of an external API.
import requests
def check_api_status():
try:
response = requests.get('https://api.github.com')
if response.status_code == 200:
return True
else:
return False
except requests.RequestException:
return False
if __name__ == "__main__":
print("API is up" if check_api_status() else "API is down")
Using Python Libraries for Advanced Health Checks
You may use the health check library to do more thorough health checks. It supports third-party APIs, caching mechanisms, and intricate database checks.
pip install healthcheck
from healthcheck import HealthCheck, EnvironmentDump
from flask import Flask
app = Flask(__name__)
health = HealthCheck(app, "/healthcheck")
def database_available():
# Imagine a function that checks if your database is up
return True, "Database is up"
def api_available():
# Imagine a function that checks if external API is up
return True, "API is up"
health.add_check(database_available)
health.add_check(api_available)
if __name__ == "__main__":
app.run(debug=True)It's simple to integrate several health checks into a single endpoint using healthcheck.
Logging and Alerting with Health Checks
Maintaining a record of health check findings is crucial for tracking problems over time. Here, the logging package in Python is helpful.
import logging
logging.basicConfig(filename='healthcheck.log', level=logging.INFO)
def log_health_status(status):
if status:
logging.info("System is healthy")
else:
logging.error("System is down")You may use technologies like Prometheus or Grafana to view and notify on health check findings for monitoring big applications.
Automating Health Checks in CI/CD Pipelines
A crucial component of continuous integration and continuous delivery (CI/CD) is automating health checks. To make sure that every new deployment is healthy, you may incorporate health checks into your pipelines using technologies like Jenkins or GitLab CI.
This is a little script for a health check that you can add to a Jenkins pipeline:
python health_check.py
if [ $? -ne 0 ]; then
echo "Health check failed!"
exit 1
fi
Kubernetes Health Check Endpoints: Liveness & Readiness Probes
When deploying FastAPI to Kubernetes, you need separate endpoints for liveness and readiness probes:
Liveness Probe (/live): Checks if the application is running. If this fails, Kubernetes restarts the container.
Readiness Probe (/ready): Checks if the application can handle traffic. If this fails, Kubernetes removes the pod from load balancer.
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import asyncio
app = FastAPI()
# Track application state
app_ready = False
@app.on_event("startup")
async def startup_event():
global app_ready
# Perform initialization (DB connections, cache warm-up, etc.)
await initialize_dependencies()
app_ready = True
@app.get("/live")
async def liveness():
"""Liveness probe - is the app process running?"""
return {"status": "alive"}
@app.get("/ready")
async def readiness():
"""Readiness probe - can the app handle requests?"""
if not app_ready:
return JSONResponse(
content={"status": "not ready", "reason": "initializing"},
status_code=503
)
# Check critical dependencies
db_ok = await check_database()
if db_ok:
return {"status": "ready"}
else:
return JSONResponse(
content={"status": "not ready", "reason": "database unavailable"},
status_code=503
)
@app.get("/health")
async def health():
"""Combined health check with details"""
checks = await run_all_health_checks()
return {
"status": "healthy" if all_checks_pass(checks) else "unhealthy",
"checks": checks
}Kubernetes Deployment Configuration:
yaml
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: fastapi-app
livenessProbe:
httpGet:
path: /live
port: 8000
initialDelaySeconds: 10
periodSeconds: 15
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 10For container orchestration fundamentals, read our Kubernetes vs Docker comparison.
FastAPI Health Check Endpoint Best Practices
Follow these best practices to implement production-ready health checks:
1. Keep Health Checks Fast
python
# ✅ Good: Use timeouts
async def check_database():
try:
await asyncio.wait_for(db.execute("SELECT 1"), timeout=5.0)
return True
except asyncio.TimeoutError:
return False
# ❌ Bad: No timeout (can hang indefinitely)
async def check_database():
await db.execute("SELECT 1") # May never return
return True2. Run Checks in Parallel
python
# ✅ Good: Parallel execution
checks = await asyncio.gather(
check_database(),
check_redis(),
check_external_api()
)
# ❌ Bad: Sequential execution (slow)
db = await check_database()
redis = await check_redis()
api = await check_external_api()3. Return Appropriate HTTP Status Codes
Status | When to Use |
200 OK | All checks pass |
503 Service Unavailable | Critical dependency failed |
500 Internal Server Error | Health check itself failed |
4. Include Useful Metadata
python
return {
"status": "healthy",
"version": "1.2.3",
"timestamp": datetime.utcnow().isoformat(),
"uptime_seconds": get_uptime(),
"checks": {
"database": {"status": "healthy", "latency_ms": 5},
"redis": {"status": "healthy", "latency_ms": 2}
}
}5. Don't Expose Sensitive Information
python
# ✅ Good: Safe response
{"database": {"status": "healthy"}}
# ❌ Bad: Exposes internals
{"database": {"status": "healthy", "host": "db.internal.com", "password": "***"}}6. Separate Liveness from Readiness
- Liveness: Simple "is process alive" check (fast, no dependencies)
- Readiness: Full dependency check (slower, validates traffic capability)
7. Use Health Check Libraries for Complex Apps
python
# Using fastapi-health library
from fastapi_health import health
app.add_api_route("/health", health([
is_database_online,
is_redis_alive,
is_disk_space_ok
]))
Python Health Check Libraries for FastAPI
Several libraries simplify health check implementation:
1. fastapi-health
bash
pip install fastapi-health
python
from fastapi import FastAPI
from fastapi_health import health
def database_check():
return {"database": "online"}
def redis_check():
return {"redis": "online"}
app = FastAPI()
app.add_api_route("/health", health([database_check, redis_check]))2. fastapi-healthchecks
bash
pip install fastapi-healthchecks
python
from fastapi import FastAPI
from fastapi_healthchecks import HealthcheckRouter, Probe
from fastapi_healthchecks.checks import PostgreSqlCheck, RedisCheck
app = FastAPI()
app.include_router(
HealthcheckRouter(
Probe(
name="readiness",
checks=[
PostgreSqlCheck(host="db.example.com", ...),
RedisCheck(host="redis.example.com", ...),
],
),
Probe(name="liveness", checks=[]),
),
prefix="/health",
)3. py-healthcheck
bash
pip install py-healthcheck
python
from healthcheck import HealthCheck
from fastapi import FastAPI
from fastapi.responses import JSONResponse
health = HealthCheck()
def database_available():
return True, "database ok"
health.add_check(database_available)
app = FastAPI()
@app.get("/health")
async def healthcheck():
message, status_code, headers = health.run()
return JSONResponse(content=message, status_code=status_code)Library Comparison:
Library | Best For | Async Support | Built-in Checks |
|---|---|---|---|
fastapi-health | Simple apps | Yes | No |
fastapi-healthchecks | K8s deployments | Yes | PostgreSQL, Redis, RabbitMQ |
py-healthcheck | Flask migration | No | No |
Looking for Python developers experienced in building production microservices? Hire from Index.dev's talent network.
Docker Health Check with FastAPI
Configure Docker to monitor your FastAPI application's health:
Dockerfile with Health Check:
dockerfile
FROM python:3.11-slim
# Install curl for health checks
RUN apt-get update && apt-get install -y curl
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Health check configuration
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Docker Compose with Health Check:
yaml
version: '3.8'
services:
fastapi-app:
build: .
ports:
- "8000:8000"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
restart: unless-stopped
depends_on:
db:
condition: service_healthy
db:
image: postgres:15
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5Health Check Parameters:
Parameter | Description | Recommended Value |
|---|---|---|
interval | Time between checks | 30s |
timeout | Max time for check | 10s |
retries | Failures before unhealthy | 3 |
start_period | Startup grace period | 10-60s |
Conclusion
Health check endpoints are essential for running FastAPI applications in production. Whether you're deploying to Kubernetes, Docker, or traditional infrastructure, properly implemented health checks ensure your application remains reliable and recoverable.
Quick Implementation Summary:
Use Case | Implementation |
Basic health check | @app.get("/health") returning {"status": "healthy"} |
Kubernetes deployment | Separate /live and /ready endpoints |
Docker containers | HEALTHCHECK instruction with curl |
Complex applications | Use fastapi-health or fastapi-healthchecks library |
Key Takeaways:
- Always include timeouts on dependency checks (5-10 seconds)
- Run multiple checks in parallel with asyncio.gather()
- Return HTTP 503 for unhealthy states, not 500
- Separate liveness (is process alive?) from readiness (can handle traffic?)
- Include version and timestamp in health check responses
Building production Python applications? Hire senior Python developers through Index.dev — our talent network includes engineers experienced in FastAPI, microservices architecture, and cloud deployments.
Read Also: How to Right-Justify Objects in Python Graphics
For Python Developers:
Join Index.dev, the remote work platform connecting senior Python developers with remote tech companies. Begin working remotely on innovative projects across the US, UK, and EU!
For Employers:
Looking to hire experienced Python developers for your next project? Index.dev can connect you with top Python developers ready to implement robust solutions like health checks and more. Post a job description and receive 3 to 5 interview-ready candidates today!