FastAPI Health

0.4.0 · active · verified Thu Apr 16

FastAPI Health is a Python library that provides a straightforward way to implement health check endpoints in FastAPI applications. It is currently at version 0.4.0 and offers dynamic health checks using custom conditions (callables) and handlers. The library is actively maintained with recent updates focusing on flexibility and dependency handling.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic health check endpoint using `fastapi-health`. It includes two simulated condition checks: one returning a dictionary for detailed status and another returning a boolean. The `health()` function dynamically creates a route that aggregates the results of these conditions.

from fastapi import FastAPI, Depends
from fastapi_health import health
import os

app = FastAPI()

def get_database_status():
    # Simulate a database check
    db_conn_string = os.environ.get('DATABASE_URL', 'sqlite:///./test.db')
    # In a real app, this would attempt a connection or query
    is_connected = db_conn_string is not None # Simplified check
    return {"database": "online" if is_connected else "offline"}

def get_cache_status():
    # Simulate a cache check
    cache_host = os.environ.get('REDIS_HOST', 'localhost')
    is_reachable = cache_host == 'localhost' # Simplified check
    return is_reachable # Returns a boolean

# Register the health endpoint with multiple conditions
app.add_api_route("/health", health([
    get_database_status,
    get_cache_status
]))

# To run this example, save it as main.py and run: uvicorn main:app --reload
# Then navigate to http://localhost:8000/health

view raw JSON →