FastAPI Health
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
-
NameError: name 'HealthRoute' is not defined
cause Attempting to import or use the `HealthRoute` class after upgrading to `fastapi-health` version 0.2.0 or later, where it was removed/deprecated.fixUpdate your code to use the `health()` function instead: `from fastapi_health import health`, and then `app.add_api_route("/health", health([your_condition_callable]))`. -
TypeError: 'bool' object is not callable
cause Passing a boolean value directly to the `conditions` list instead of a callable (function) that returns a boolean or dictionary.fixEnsure all items in the `conditions` list passed to `health()` are actual callable functions, not their return values. For example, use `health([check_db_status])` instead of `health([check_db_status()])`. -
Status code 503 instead of 200, even when some services are reported as 'online' in the health check response.
cause This often happens when `conditions` list contains a mix of callables where at least one returns `False` (boolean) while others return dictionaries indicating 'online' status. The presence of any `False` condition defaults the HTTP status to `503`.fixIf all services are critical, accept the `503`. If partial failures should yield a `200` with detailed info, ensure all conditions return dictionaries, or implement custom `success_handler` and `failure_handler` to control the status code and response body more precisely. Alternatively, set `failure_status=200` if you always want a 200 response.
Warnings
- breaking The `HealthRoute` class was removed/deprecated in version 0.2.0. Users on older versions upgrading to 0.2.0 or newer must migrate to using the `health()` function.
- gotcha When using a mix of conditions that return `bool` and `dict`, if any condition returns `False`, the overall response status will default to `503` (Service Unavailable), even if other conditions return detailed 'online' dictionaries. The JSON body will still contain the results from all conditions.
- gotcha Performing synchronous I/O operations (e.g., blocking database calls, network requests) directly within `health` condition callables can block FastAPI's event loop, degrading performance and responsiveness for all other API endpoints.
Install
-
pip install fastapi-health
Imports
- health
from fastapi_health import health
- HealthRoute
from fastapi_health import HealthRoute
This class is deprecated and should not be used.
Quickstart
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