API Reference¶
The root package __all__ is the single source for stable root-level exports and loads those exports lazily. Prefer from fast_healthchecks import Probe, ProbeRunner, RunPolicy, HealthCheckReport, HealthCheckResult, Check, FunctionConfig and the exception hierarchy (HealthCheckError, HealthCheckTimeoutError, HealthCheckSSRFError). Standalone run_probe and close_probes are available from fast_healthchecks.execution; framework shutdown callbacks are exported by their corresponding integration modules. Check classes (e.g. RedisHealthCheck) and other configs are loaded lazily from fast_healthchecks.checks or imported from their submodules (e.g. fast_healthchecks.checks.redis). See fast_healthchecks.__all__ and fast_healthchecks.checks.__all__.
Config types (e.g. RedisConfig, UrlConfig) in fast_healthchecks.checks.configs are part of the supported API for passing config=... to check constructors. The to_dict() methods on check classes are for internal test use only and are not part of the supported public API; do not rely on them in production code.
Secrets and redaction: Check and config to_dict(redact_secrets=True) redacts credential-style keys (same set as in fast_healthchecks.utils). The structured logging layer used by run_probe does not log config or secrets; see fast_healthchecks.logging and the run_probe docs.
Exception hierarchy (public)¶
The following exceptions are part of the public API and are documented for callers who want to handle them explicitly. Existing code that catches asyncio.TimeoutError or ValueError continues to work, because the new types subclass those.
- HealthCheckError — Base for health-check-related exceptions.
- HealthCheckTimeoutError — Raised when a probe or check run times out. Subclass of
HealthCheckErrorandasyncio.TimeoutError. - HealthCheckSSRFError — Raised when URL/host SSRF validation fails (e.g.
validate_url_ssrf,validate_host_ssrf_async). Subclass ofHealthCheckErrorandValueError. See SSRF documentation for behaviour and edge cases.
Structured Error Reporting with HealthError¶
For programmatic error handling and detailed diagnostics, use the HealthError dataclass which provides structured error information:
Machine-readable error details for failed health checks.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Machine-readable error code (e.g., "PROBE_TIMEOUT", "CHECK_EXCEPTION"). |
message |
str
|
Human-readable error message describing what went wrong. |
duration_ms |
int
|
Time in milliseconds that the probe took to execute. |
timeout_ms |
int | None
|
Timeout limit in milliseconds that was applied to the probe. |
meta |
dict[str, object]
|
Additional metadata about the error (e.g., exception type, URL). Secrets are automatically redacted from this field. |
Source code in fast_healthchecks/models.py
__post_init__()
¶
Store a redacted copy so secrets are safe before serialization or logging.
Error Codes:
| Code | Description |
|---|---|
CHECK_TIMEOUT |
Overall check execution exceeded timeout |
PROBE_TIMEOUT |
Individual probe exceeded its timeout |
CHECK_EXCEPTION |
Check raised an unexpected exception |
DEPENDENCY_UNHEALTHY |
A dependency was marked unhealthy |
Troubleshooting: Legacy Exception Mapping¶
The following table maps legacy exception classes to their corresponding ErrorCode values:
| Legacy Exception | ErrorCode | Notes |
|---|---|---|
HealthCheckTimeoutError |
CHECK_TIMEOUT |
Overall check execution timeout |
asyncio.TimeoutError |
CHECK_TIMEOUT |
Caught at runner level |
HealthCheckSSRFError |
CHECK_EXCEPTION |
SSRF validation failure |
HealthCheckError |
CHECK_EXCEPTION |
General check failure |
Other Exception |
CHECK_EXCEPTION |
Unexpected errors |
Automatic mapping: The map_exception_to_health_error() function automatically converts legacy exceptions to HealthError with the appropriate error code:
from fast_healthchecks.errors import map_exception_to_health_error
# These are equivalent:
result.error = map_exception_to_health_error(exc)
result.error = HealthError(code="CHECK_EXCEPTION", message=str(exc), ...)
Migration guide:
- Replace
except HealthCheckTimeoutErrorwithif result.error.code == "CHECK_TIMEOUT" - Replace
except HealthCheckErrorwithif result.error.code == "CHECK_EXCEPTION" - Access structured error info via
result.error.code,result.error.message,result.error.meta
Migration from legacy exceptions:
The old exception-based approach (HealthCheckError, HealthCheckTimeoutError) is still supported for backward compatibility. However, the new HealthError model provides more structured information:
# Old way (still works)
try:
await runner.run(probe)
except asyncio.TimeoutError as e:
logger.error(f"Timeout: {e}")
# New way (recommended) - use map_exception_to_health_error
from fast_healthchecks.errors import map_exception_to_health_error
report = await runner.run(probe)
for result in report.results:
if not result.healthy and result.error:
print(f"Error code: {result.error.code}")
print(f"Message: {result.error.message}")
print(f"Duration: {result.error.duration_ms}ms")
print(f"Meta: {result.error.meta}")
The map_exception_to_health_error function in fast_healthchecks.errors converts exceptions to structured HealthError instances with official error codes.
Models for healthchecks.
HealthCheckError
¶
Bases: Exception
Base exception for health-check-related failures.
Raised or used as a base for timeouts, SSRF validation, and other health-check errors. Subclasses preserve the original exception type (e.g. HealthCheckTimeoutError is also an asyncio.TimeoutError) so existing code that catches TimeoutError or ValueError continues to work.
Source code in fast_healthchecks/models.py
HealthCheckReport
dataclass
¶
Report of healthchecks.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list[HealthCheckResult]
|
List of healthcheck results. |
allow_partial_failure |
bool
|
If True, report is healthy when at least one check passes. |
Source code in fast_healthchecks/models.py
healthy
property
¶
Whether all health checks passed or partial failure was allowed.
HealthCheckResult
dataclass
¶
Result of a healthcheck.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the healthcheck. |
healthy |
bool
|
Whether the healthcheck passed. |
error |
HealthError | None
|
Structured error details if the healthcheck failed. |
Source code in fast_healthchecks/models.py
error_details
property
¶
Backward-compatible error message accessor.
__init__(name, healthy, error=None, *, error_details=None)
¶
Create a health check result.
The error_details keyword is accepted for backward compatibility
and is converted into error.message.
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
Source code in fast_healthchecks/models.py
HealthCheckSSRFError
¶
Bases: HealthCheckError, ValueError
Raised when URL or host validation fails (SSRF / block_private_hosts).
Subclass of both HealthCheckError and ValueError so that
except ValueError still catches it.
HealthCheckTimeoutError
¶
Bases: HealthCheckError, TimeoutError
Raised when a probe or check run exceeds its timeout.
Subclass of both HealthCheckError and asyncio.TimeoutError so that
except asyncio.TimeoutError or except TimeoutError still catch it.
Source code in fast_healthchecks/models.py
__init__(message='Probe timed out', *, code='PROBE_TIMEOUT')
¶
Create timeout error with machine-readable timeout code.
HealthError
dataclass
¶
Machine-readable error details for failed health checks.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Machine-readable error code (e.g., "PROBE_TIMEOUT", "CHECK_EXCEPTION"). |
message |
str
|
Human-readable error message describing what went wrong. |
duration_ms |
int
|
Time in milliseconds that the probe took to execute. |
timeout_ms |
int | None
|
Timeout limit in milliseconds that was applied to the probe. |
meta |
dict[str, object]
|
Additional metadata about the error (e.g., exception type, URL). Secrets are automatically redacted from this field. |
Source code in fast_healthchecks/models.py
__post_init__()
¶
Store a redacted copy so secrets are safe before serialization or logging.
Framework-neutral probe execution and lifecycle primitives.
Probe
¶
Bases: NamedTuple
A named sequence of health checks executed as one probe.
Source code in fast_healthchecks/execution.py
endpoint_summary
property
¶
The explicit summary or a readable summary derived from the route.
ProbeRunner
dataclass
¶
Execute probes and close only resource-owning checks seen by the runner.
The runner owns the lifecycle of resource checks it has seen: close()
and resource tracking are serialized by an internal lock so a concurrent
close() cannot race registration. Probe execution itself is not
locked; concurrent run() calls proceed in parallel.
Source code in fast_healthchecks/execution.py
__aenter__()
async
¶
__aexit__(_exc_type, _exc, _tb)
async
¶
Always close managed checks on context exit.
close()
async
¶
Close resource-owning checks observed by this runner.
Source code in fast_healthchecks/execution.py
run(probe)
async
¶
Run probe checks and return a report.
Returns:
| Type | Description |
|---|---|
HealthCheckReport
|
The evaluated health-check report. |
Source code in fast_healthchecks/execution.py
RunPolicy
dataclass
¶
Immutable policy controlling probe execution behavior.
max_concurrency caps how many checks run at once in parallel mode
(default 8); None removes the cap.
Source code in fast_healthchecks/execution.py
__post_init__()
¶
Validate policy values.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a mode is unknown, the timeout is not positive, or max_concurrency is not positive. |
Source code in fast_healthchecks/execution.py
close_probes(probes)
async
¶
Close unique check resources and give transports one cleanup grace period.
Source code in fast_healthchecks/execution.py
run_probe(probe, *, timeout=None, execution='parallel', max_concurrency=DEFAULT_MAX_CONCURRENCY, on_check_start=None, on_check_end=None, on_timeout_return_failure=False)
async
¶
Run a probe without importing an HTTP or framework integration.
max_concurrency caps how many checks run at once in parallel mode
(default 8); None removes the cap. Sequential mode ignores it.
Returns:
| Type | Description |
|---|---|
HealthCheckReport
|
A report containing results in input order. |
Raises:
| Type | Description |
|---|---|
HealthCheckTimeoutError
|
If the probe times out in strict mode. |
Source code in fast_healthchecks/execution.py
DSN NewTypes for type hints only.
These types annotate DSN strings (e.g. AmqpDsn, RedisDsn) but are not used at runtime by check classes. Each HealthCheckDSN subclass implements its own parse_dsn() and validate_dsn(); dsn.py provides no parsing or validation logic. Use these types to annotate configuration or function parameters.
Checks¶
Immutable configuration dataclasses for health checks.
Encapsulates connection parameters to avoid long parameter lists (PLR0913) and centralize serialization for to_dict().
FunctionConfig
dataclass
¶
Configuration for function health check.
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
KafkaConfig
dataclass
¶
Configuration for Kafka health check.
Source code in fast_healthchecks/checks/configs.py
__post_init__()
¶
Validate security_protocol and sasl_mechanism.
Raises:
| Type | Description |
|---|---|
ValueError
|
If security_protocol or sasl_mechanism is invalid. |
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
Source code in fast_healthchecks/checks/configs.py
MongoConfig
dataclass
¶
Configuration for MongoDB health check.
tls=None leaves the driver default untouched; tls_ca_file is
forwarded as tlsCAFile when set.
Source code in fast_healthchecks/checks/configs.py
OpenSearchConfig
dataclass
¶
Configuration for OpenSearch health check.
verify_certs defaults to True: TLS connections verify the server
certificate unless explicitly disabled. It only applies when
use_ssl=True.
Source code in fast_healthchecks/checks/configs.py
PostgresAsyncPGConfig
dataclass
¶
Configuration for PostgreSQL health check (asyncpg driver).
Source code in fast_healthchecks/checks/configs.py
to_dict()
¶
Return config as a dict for serialization.
Source code in fast_healthchecks/checks/configs.py
PostgresPsycopgConfig
dataclass
¶
Configuration for PostgreSQL health check (psycopg driver).
Source code in fast_healthchecks/checks/configs.py
RabbitMQConfig
dataclass
¶
Configuration for RabbitMQ health check.
Security: The default user and password ("guest") match
RabbitMQ's default credentials and are accepted only for loopback hosts
(localhost, 127.0.0.1, ::1). Configuring them for any other
host raises ValueError; set explicit credentials or use a secrets
manager. See SECURITY.md.
Source code in fast_healthchecks/checks/configs.py
__post_init__()
¶
Reject RabbitMQ default credentials for non-loopback brokers.
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
Source code in fast_healthchecks/checks/configs.py
RedisConfig
dataclass
¶
Configuration for Redis health check.
Source code in fast_healthchecks/checks/configs.py
UrlConfig
dataclass
¶
Configuration for URL health check.
Use only trusted URLs from application configuration; do not pass
user-controlled input to avoid SSRF. Validation and behaviour are
provided by :func:~fast_healthchecks.utils.validate_url_ssrf and
:func:~fast_healthchecks.utils.validate_host_ssrf_async. See the
SSRF documentation in the docs.
Source code in fast_healthchecks/checks/configs.py
Type aliases for health checks.
HealthCheck
¶
HealthCheckDSN
¶
Bases: ConfigDictMixin, HealthCheck[T_co], Generic[T_co, T_parsed]
Base class for health checks that can be created from a DSN.
Contract: subclasses must define _allowed_schemes(), _default_name(), parse_dsn(), and _from_parsed_dsn(). The check stores its display name in _name (used in HealthCheckResult and error reporting). DSN validation uses validate_dsn(); fast_healthchecks.dsn NewTypes are typing-only, not runtime.
Type parameters: T_co is the result type (e.g. HealthCheckResult); T_parsed is the type returned by parse_dsn() and accepted by _from_parsed_dsn().
Source code in fast_healthchecks/checks/_base.py
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
from_dsn(dsn, *, name=None, timeout=DEFAULT_HC_TIMEOUT, **kwargs)
classmethod
¶
Create a check instance from a DSN string.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckDSN |
HealthCheckDSN[T_co, T_parsed]
|
Configured check instance. |
Source code in fast_healthchecks/checks/_base.py
parse_dsn(dsn)
abstractmethod
classmethod
¶
validate_dsn(dsn, *, allowed_schemes)
classmethod
¶
Validate the DSN has an allowed scheme.
Allows compound schemes (e.g. postgresql+asyncpg) when the base part before '+' is in allowed_schemes. Scheme comparison is case-insensitive.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The DSN string (stripped of leading/trailing whitespace). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If dsn is not a string. |
ValueError
|
If DSN is empty or scheme is not in allowed_schemes. |
Source code in fast_healthchecks/checks/_base.py
Health check that runs a user-provided callable (sync or async).
FunctionHealthCheck runs the callable each time the check is executed; sync functions are run in a thread pool via run_in_executor.
FunctionHealthCheck
¶
Bases: ConfigDictMixin, HealthCheck[HealthCheckResult]
Health check that runs a callable (sync or async) each time it is executed.
Async callables are detected via inspect.iscoroutinefunction on the
callable itself and on its __call__ method, so instances of classes
with async def __call__ run on the event loop. Exotic wrappers that
hide the coroutine function may still be misdetected as sync.
Synchronous functions are run via loop.run_in_executor(executor, ...).
The default executor is None (shared thread pool). Long-running blocking
sync checks can exhaust the pool; pass a dedicated :class:Executor if
needed. A timeout abandons the worker thread rather than cancelling it —
Python offers no way to kill a running thread — so the blocking call may
keep running in the background after the check fails.
Source code in fast_healthchecks/checks/function.py
__call__()
async
¶
Perform the health check on the function.
Sync functions run in the given executor (default: shared thread pool).
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/function.py
__init__(*, config=None, func=None, name='Function', executor=None, **kwargs)
¶
Initialize the FunctionHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
FunctionConfig | None
|
Config (args, kwargs, timeout). If None, built from kwargs. |
None
|
func
|
Callable[..., Any] | None
|
The function to perform the health check on (required if config is None). |
None
|
name
|
str
|
The name of the health check. |
'Function'
|
executor
|
Executor | None
|
Executor for sync functions. Defaults to None (thread pool). |
None
|
**kwargs
|
Any
|
Passed to FunctionConfig when config is None (args, kwargs, timeout). |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
When func is not provided. |
Source code in fast_healthchecks/checks/function.py
This module provides a health check class for Redis.
Classes:
| Name | Description |
|---|---|
RedisHealthCheck |
A class to perform health checks on Redis. |
Usage
The RedisHealthCheck class can be used to perform health checks on Redis by calling it.
Example
health_check = RedisHealthCheck( host="localhost", port=6379, ) result = await health_check() print(result.healthy)
RedisHealthCheck
¶
Bases: ClientCachingMixin['Redis'], HealthCheckDSN[HealthCheckResult, RedisParseDsnResult]
A class to perform health checks on Redis.
Attributes:
| Name | Type | Description |
|---|---|---|
_database |
The database to connect to. |
|
_host |
The host to connect to. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The password to authenticate with. |
_port |
str
|
The port to connect to. |
_timeout |
str
|
The timeout for the connection. |
_user |
str
|
The user to authenticate with. |
_ssl |
str
|
Whether to use SSL or not. |
_ssl_ca_certs |
str
|
The path to the CA certificate. |
Source code in fast_healthchecks/checks/redis.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
__call__()
async
¶
Perform a health check on Redis.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/redis.py
__init__(*, config=None, name='Redis', close_client_fn=_close_redis_client, **kwargs)
¶
Initialize the RedisHealthCheck class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RedisConfig | None
|
Connection config. If None, built from kwargs (host, port, database, etc.). |
None
|
name
|
str
|
The name of the health check. |
'Redis'
|
close_client_fn
|
Callable[[Redis], Awaitable[None]]
|
Callable to close the cached client. Defaults to the standard Redis aclose. |
_close_redis_client
|
**kwargs
|
Any
|
Passed to RedisConfig when config is None (host, port, database, user, password, ssl, ssl_ca_certs, timeout). |
{}
|
Source code in fast_healthchecks/checks/redis.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RedisParseDsnResult |
RedisParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/redis.py
This module provides a health check class for Kafka.
Classes:
| Name | Description |
|---|---|
KafkaHealthCheck |
A class to perform health checks on Kafka. |
Usage
The KafkaHealthCheck class can be used to perform health checks on Kafka by calling it.
Example
health_check = KafkaHealthCheck( bootstrap_servers="localhost:9092", security_protocol="PLAINTEXT", ) result = await health_check() print(result.healthy)
KafkaHealthCheck
¶
Bases: ClientCachingMixin['AIOKafkaAdminClient'], HealthCheckDSN[HealthCheckResult, KafkaParseDsnResult]
A class to perform health checks on Kafka.
Attributes:
| Name | Type | Description |
|---|---|---|
_bootstrap_servers |
The Kafka bootstrap servers. |
|
_name |
str
|
The name of the health check. |
_sasl_mechanism |
str
|
The SASL mechanism to use. |
_sasl_plain_password |
str
|
The SASL plain password. |
_sasl_plain_username |
str
|
The SASL plain username. |
_security_protocol |
str
|
The security protocol to use. |
_ssl_context |
str
|
The SSL context to use. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/kafka.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
__call__()
async
¶
Perform the health check on Kafka.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/kafka.py
__init__(*, config=None, name='Kafka', close_client_fn=_close_kafka_client, **kwargs)
¶
Initialize the KafkaHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
KafkaConfig | None
|
Connection config. If None, built from kwargs (bootstrap_servers, etc.). |
None
|
name
|
str
|
The name of the health check. |
'Kafka'
|
close_client_fn
|
Callable[[AIOKafkaAdminClient], Awaitable[None]]
|
Callable to close the cached client. |
_close_kafka_client
|
**kwargs
|
Any
|
Passed to KafkaConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/kafka.py
parse_dsn(dsn)
classmethod
¶
Parse the Kafka DSN and return the results.
Scheme kafkas implies SSL (SASL_SSL when credentials present).
Scheme kafka implies PLAINTEXT (SASL_PLAINTEXT when credentials present).
Kwargs to from_dsn override DSN-derived values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
KafkaParseDsnResult |
KafkaParseDsnResult
|
The results of parsing the DSN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If bootstrap servers are missing. |
Source code in fast_healthchecks/checks/kafka.py
This module provides a health check class for MongoDB.
Classes:
| Name | Description |
|---|---|
MongoHealthCheck |
A class to perform health checks on MongoDB. |
Usage
The MongoHealthCheck class can be used to perform health checks on MongoDB by calling it.
Example
health_check = MongoHealthCheck( hosts=["host1:27017", "host2:27017"], # or hosts="localhost", port=27017, user="myuser", password="mypassword", database="mydatabase" ) result = await health_check() print(result.healthy)
MongoHealthCheck
¶
Bases: ClientCachingMixin['AsyncIOMotorClient[dict[str, Any]]'], HealthCheckDSN[HealthCheckResult, MongoParseDsnResult]
A class to perform health checks on MongoDB.
Attributes:
| Name | Type | Description |
|---|---|---|
_auth_source |
The MongoDB authentication source. |
|
_database |
The MongoDB database to use. |
|
_hosts |
The MongoDB host or a list of hosts. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The MongoDB password. |
_port |
str
|
The MongoDB port. |
_timeout |
str
|
The timeout for the health check. |
_user |
str
|
The MongoDB user. |
Source code in fast_healthchecks/checks/mongo.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
__call__()
async
¶
Perform the health check on MongoDB.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/mongo.py
__init__(*, config=None, name='MongoDB', close_client_fn=_close_mongo_client, **kwargs)
¶
Initialize the MongoHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
MongoConfig | None
|
Connection config. If None, built from kwargs (hosts, port, etc.). |
None
|
name
|
str
|
The name of the health check. |
'MongoDB'
|
close_client_fn
|
Callable[[AsyncIOMotorClient[dict[str, Any]]], Awaitable[None]]
|
Callable to close the cached client. |
_close_mongo_client
|
**kwargs
|
Any
|
Passed to MongoConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/mongo.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
TLS follows the driver semantics: an explicit tls/ssl query
option wins; without one, mongodb+srv enables TLS (as PyMongo
does) and plain mongodb leaves the driver default (tls=None).
tlsCAFile (or legacy ssl_ca_certs) sets the CA bundle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MongoParseDsnResult |
MongoParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/mongo.py
This module provides a health check class for OpenSearch.
Classes:
| Name | Description |
|---|---|
OpenSearchHealthCheck |
A class to perform health checks on OpenSearch. |
Usage
The OpenSearchHealthCheck class can be used to perform health checks on OpenSearch by calling it.
Example
health_check = OpenSearchHealthCheck( hosts=["localhost:9200"], http_auth=("username", "password"), use_ssl=True, verify_certs=True, ssl_show_warn=False, ca_certs="/path/to/ca.pem", ) result = await health_check() print(result.healthy)
OpenSearchHealthCheck
¶
Bases: ClientCachingMixin['AsyncOpenSearch'], HealthCheckDSN[HealthCheckResult, OpenSearchParseDsnResult]
A class to perform health checks on OpenSearch.
Attributes:
| Name | Type | Description |
|---|---|---|
_hosts |
The OpenSearch hosts. |
|
_name |
str
|
The name of the health check. |
_http_auth |
str
|
The HTTP authentication. |
_use_ssl |
str
|
Whether to use SSL or not. |
_verify_certs |
str
|
Whether to verify certificates or not. |
_ssl_show_warn |
str
|
Whether to show SSL warnings or not. |
_ca_certs |
str
|
The CA certificates. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/opensearch.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
__call__()
async
¶
Perform the health check on OpenSearch.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/opensearch.py
__init__(*, config=None, name='OpenSearch', close_client_fn=_close_opensearch_client, **kwargs)
¶
Initialize the OpenSearchHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
OpenSearchConfig | None
|
Connection config. If None, built from kwargs (hosts, http_auth, etc.). |
None
|
name
|
str
|
The name of the health check. |
'OpenSearch'
|
close_client_fn
|
Callable[[AsyncOpenSearch], Awaitable[None]]
|
Callable to close the cached client. |
_close_opensearch_client
|
**kwargs
|
Any
|
Passed to OpenSearchConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/opensearch.py
parse_dsn(dsn)
classmethod
¶
Parse the OpenSearch DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
An https scheme enables TLS with certificate verification
(verify_certs=True); pass verify_certs=False to from_dsn
to explicitly opt out.
Returns:
| Name | Type | Description |
|---|---|---|
OpenSearchParseDsnResult |
OpenSearchParseDsnResult
|
The results of parsing the DSN. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If DSN has missing host. |
Source code in fast_healthchecks/checks/opensearch.py
This module provides a health check class for RabbitMQ.
Classes:
| Name | Description |
|---|---|
RabbitMQHealthCheck |
A class to perform health checks on RabbitMQ. |
Security: When using DSN or config without credentials, the library falls
back to user="guest" and password="guest". This fallback is accepted
only for loopback hosts; RabbitMQConfig raises ValueError when the
default credentials target any other host. See SECURITY.md and
:class:RabbitMQConfig docstring.
Usage
The RabbitMQHealthCheck class can be used to perform health checks on RabbitMQ by calling it.
Example
health_check = RabbitMQHealthCheck( host="localhost", port=5672, username="guest", password="guest", ) result = await health_check() print(result.healthy)
RabbitMQHealthCheck
¶
Bases: ClientCachingMixin['AbstractRobustConnection'], HealthCheckDSN[HealthCheckResult, RabbitMQParseDsnResult]
A class to perform health checks on RabbitMQ.
Uses ClientCachingMixin to reuse a single connection instead of opening a new one on every check.
Attributes:
| Name | Type | Description |
|---|---|---|
_host |
The RabbitMQ host. |
|
_name |
str
|
The name of the health check. |
_password |
str
|
The RabbitMQ password. |
_port |
str
|
The RabbitMQ port. |
_secure |
str
|
Whether to use a secure connection. |
_timeout |
str
|
The timeout for the health check. |
_user |
str
|
The RabbitMQ user. |
_vhost |
str
|
The RabbitMQ virtual host. |
Source code in fast_healthchecks/checks/rabbitmq.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
__call__()
async
¶
Perform the health check on RabbitMQ.
A cached connection is reused only while it is open; each check then opens and closes a channel so the broker actually answers — a robust connection object alone does not prove broker liveness.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/rabbitmq.py
__init__(*, config=None, name='RabbitMQ', close_client_fn=_close_rabbitmq_client, **kwargs)
¶
Initialize the RabbitMQHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
RabbitMQConfig | None
|
Connection config. If None, built from kwargs (host, user, password, etc.). |
None
|
name
|
str
|
The name of the health check. |
'RabbitMQ'
|
close_client_fn
|
Callable[[AbstractRobustConnection], Awaitable[None]]
|
Callable to close the cached connection. |
_close_rabbitmq_client
|
**kwargs
|
Any
|
Passed to RabbitMQConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/rabbitmq.py
parse_dsn(dsn)
classmethod
¶
Parse the DSN and return the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dsn
|
str
|
The DSN to parse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RabbitMQParseDsnResult |
RabbitMQParseDsnResult
|
The results of parsing the DSN. |
Source code in fast_healthchecks/checks/rabbitmq.py
Health check that performs an HTTP GET to a URL.
UrlHealthCheck caches an httpx AsyncClient and supports optional basic auth, SSL verification, and SSRF protection (block_private_hosts).
UrlHealthCheck
¶
Bases: ClientCachingMixin['AsyncClient'], ConfigDictMixin, HealthCheck[HealthCheckResult]
Health check that performs an HTTP GET to a configurable URL.
Supports basic auth, custom timeout, SSL verification, and optional
SSRF protection via block_private_hosts (see config).
Source code in fast_healthchecks/checks/url.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
__call__()
async
¶
Perform the health check.
When block_private_hosts is True, resolves the URL host before the request and rejects if it resolves to loopback/private (SSRF/DNS rebinding protection).
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
Result with healthy=True if response is success. |
Source code in fast_healthchecks/checks/url.py
__init__(*, config=None, name='HTTP', close_client_fn=_close_url_client, **kwargs)
¶
Initialize the health check.
Warning
Pass only trusted URLs from application configuration. Do not use
user-controlled input for url to avoid SSRF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
UrlConfig | None
|
Connection config. If None, built from kwargs (url, username, etc.). |
None
|
name
|
str
|
The name of the health check. |
'HTTP'
|
close_client_fn
|
Callable[[AsyncClient], Awaitable[None]]
|
Callable to close the cached client. |
_close_url_client
|
**kwargs
|
Any
|
Passed to UrlConfig when config is None (url required). |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the URL is |
Source code in fast_healthchecks/checks/url.py
This module provides a health check class for PostgreSQL using asyncpg.
Classes:
| Name | Description |
|---|---|
PostgreSQLAsyncPGHealthCheck |
A class to perform health checks on a PostgreSQL database using asyncpg. |
Usage
The PostgreSQLAsyncPGHealthCheck class can be used to perform health checks on a PostgreSQL database by connecting to the database and executing a simple query.
Example
health_check = PostgreSQLAsyncPGHealthCheck( host="localhost", port=5432, user="username", password="password", database="dbname" )
or¶
health_check = PostgreSQLAsyncPGHealthCheck.from_dsn( "postgresql://username:password@localhost:5432/dbname", ) result = await health_check() print(result.healthy)
PostgreSQLAsyncPGHealthCheck
¶
Bases: BasePostgreSQLHealthCheck[HealthCheckResult]
Health check class for PostgreSQL using asyncpg.
Attributes:
| Name | Type | Description |
|---|---|---|
_name |
str
|
The name of the health check. |
_host |
str
|
The hostname of the PostgreSQL server. |
_port |
str
|
The port number of the PostgreSQL server. |
_user |
str
|
The username for authentication. |
_password |
str
|
The password for authentication. |
_database |
str
|
The database name. |
_ssl |
str
|
The SSL context for secure connections. |
_direct_tls |
str
|
Whether to use direct TLS. |
_timeout |
str
|
The timeout for the connection. |
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
__call__()
async
¶
Perform the health check.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
__init__(*, config=None, name='PostgreSQL', **kwargs)
¶
Initialize the PostgreSQLAsyncPGHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PostgresAsyncPGConfig | None
|
Connection config. If None, built from kwargs (host, port, user, etc.). |
None
|
name
|
str
|
The name of the health check. |
'PostgreSQL'
|
**kwargs
|
Any
|
Passed to PostgresAsyncPGConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/postgresql/asyncpg.py
This module provides a health check for PostgreSQL using psycopg.
Classes:
| Name | Description |
|---|---|
PostgreSQLPsycopgHealthCheck |
A class for health checking PostgreSQL using psycopg. |
Usage
The PostgreSQLPsycopgHealthCheck class can be used to perform health checks on a PostgreSQL database by connecting to the database and executing a simple query.
Example
health_check = PostgreSQLPsycopgHealthCheck( host="localhost", port=5432, user="username", password="password", database="dbname" )
or¶
health_check = PostgreSQLPsycopgHealthCheck.from_dsn( "postgresql://username:password@localhost:5432/dbname", ) result = await health_check() print(result.healthy)
PostgreSQLPsycopgHealthCheck
¶
Bases: BasePostgreSQLHealthCheck[HealthCheckResult]
Health check class for PostgreSQL using psycopg.
Attributes:
| Name | Type | Description |
|---|---|---|
_name |
str
|
The name of the health check. |
_host |
str
|
The hostname of the PostgreSQL server. |
_port |
str
|
The port number of the PostgreSQL server. |
_user |
str
|
The username for authentication. |
_password |
str
|
The password for authentication. |
_database |
str
|
The database name. |
_sslmode |
str
|
The SSL mode to use for the connection. |
_sslcert |
str
|
The path to the SSL certificate file. |
_sslkey |
str
|
The path to the SSL key file. |
_sslrootcert |
str
|
The path to the SSL root certificate file. |
_timeout |
str
|
The timeout for the health check. |
Source code in fast_healthchecks/checks/postgresql/psycopg.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
__call__()
async
¶
Perform the health check.
Returns:
| Name | Type | Description |
|---|---|---|
HealthCheckResult |
HealthCheckResult
|
The result of the health check. |
Source code in fast_healthchecks/checks/postgresql/psycopg.py
__init__(*, config=None, name='PostgreSQL', **kwargs)
¶
Initialize the PostgreSQLPsycopgHealthCheck.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PostgresPsycopgConfig | None
|
Connection config. If None, built from kwargs (host, port, user, etc.). |
None
|
name
|
str
|
The name of the health check. |
'PostgreSQL'
|
**kwargs
|
Any
|
Passed to PostgresPsycopgConfig when config is None. |
{}
|
Source code in fast_healthchecks/checks/postgresql/psycopg.py
Integrations¶
Base for FastAPI, FastStream, and Litestar integrations.
Provides Probe, run_probe(), healthcheck_shutdown(), and helpers to build health routes. Framework-specific routers use these to expose liveness/readiness.
ProbeAsgi
¶
An ASGI probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run. |
required |
options
|
ProbeRouteOptions | None
|
Route options (handlers, status codes, debug, timeout). When None, defaults from build_probe_route_options() are used. |
None
|
Source code in fast_healthchecks/integrations/base.py
__call__()
async
¶
Run the probe via run_probe (unified execution and timeout handling).
Returns:
| Type | Description |
|---|---|
tuple[bytes, dict[str, str] | None, int]
|
A tuple containing the response body, headers, and status code. |
Source code in fast_healthchecks/integrations/base.py
__init__(probe, *, options=None, runner=None)
¶
Initialize the ASGI probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run. |
required |
options
|
ProbeRouteOptions | None
|
Route options (handlers, status codes, debug, timeout). When None, defaults from build_probe_route_options() are used. |
None
|
runner
|
ProbeRunner | None
|
Optional ProbeRunner. When None, uses an internal reporting-mode runner with the configured timeout. |
None
|
Source code in fast_healthchecks/integrations/base.py
ProbeRouteOptions
¶
Bases: NamedTuple
Options for probe routes. Combines handler params and path prefix.
Source code in fast_healthchecks/integrations/base.py
to_route_params()
¶
Return ProbeRouteParams for create_probe_route_handler.
Source code in fast_healthchecks/integrations/base.py
ProbeRouteParams
¶
Bases: NamedTuple
Parameters for probe route handlers. Used by framework integrations.
Source code in fast_healthchecks/integrations/base.py
to_options(prefix='/health')
¶
Return ProbeRouteOptions with the given prefix.
Source code in fast_healthchecks/integrations/base.py
build_health_routes(probes, add_route, *, options=None)
¶
Build health route entries for framework integrations.
Used by Litestar and FastStream health() functions. When options is None, uses build_probe_route_options() defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
Probes to build routes for. |
required |
add_route
|
Callable[[Probe, ProbeRouteOptions], _T]
|
Callback (probe, options) -> route entry for the framework. |
required |
options
|
ProbeRouteOptions | None
|
Route options. When None, defaults from build_probe_route_options(). |
None
|
Returns:
| Type | Description |
|---|---|
list[_T]
|
List of route entries produced by add_route for each probe. |
Source code in fast_healthchecks/integrations/base.py
build_probe_route_options(*, success_handler=default_handler, failure_handler=default_handler, success_status=HTTPStatus.NO_CONTENT, failure_status=HTTPStatus.SERVICE_UNAVAILABLE, debug=False, prefix='/health', timeout=None)
¶
Build ProbeRouteOptions with defaults. Used by health() and _add_probe_route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
success_handler
|
HandlerType
|
Handler for healthy responses. Receives ProbeAsgiResponse. |
default_handler
|
failure_handler
|
HandlerType
|
Handler for unhealthy responses. Same signature. |
default_handler
|
success_status
|
int
|
HTTP status for healthy (default 204 No Content). |
NO_CONTENT
|
failure_status
|
int
|
HTTP status for unhealthy (default 503). |
SERVICE_UNAVAILABLE
|
debug
|
bool
|
Include check details in responses. |
False
|
prefix
|
str
|
URL prefix for probe routes (e.g. "/health"). |
'/health'
|
timeout
|
float | None
|
Max seconds for all checks; on exceed returns failure. None = no limit. |
None
|
Returns:
| Type | Description |
|---|---|
ProbeRouteOptions
|
ProbeRouteOptions for use with HealthcheckRouter or health(). |
Source code in fast_healthchecks/integrations/base.py
create_probe_route_handler(probe, params, *, response_factory, runner=None)
¶
Create an async handler for a probe route.
Framework integrations use this with their response_factory to build the handler, then register it (FastAPI add_api_route, FastStream/Litestar return).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to run when the route is called. |
required |
params
|
ProbeRouteParams
|
Route params (handlers, status codes, etc.). |
required |
response_factory
|
Callable[[bytes, dict[str, str], int], _T]
|
Called with (body, headers, status_code); returns framework response. |
required |
runner
|
ProbeRunner | None
|
Optional ProbeRunner used for probe execution. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[_T]]
|
Async callable that runs the probe and returns the framework response. |
Source code in fast_healthchecks/integrations/base.py
default_handler(response)
async
¶
Default handler for health check route.
Returns a minimal body {"status": "healthy"|"unhealthy"} for responses
that require content (e.g. 503). Returns None for 204 No Content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
ProbeAsgiResponse
|
The response from the probe. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Minimal status dict, or None for no response body. |
Source code in fast_healthchecks/integrations/base.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
make_probe_asgi(probe, *, options=None, runner=None)
¶
Create an ASGI probe from a probe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probe
|
Probe
|
The probe to create the ASGI probe from. |
required |
options
|
ProbeRouteOptions | None
|
Route options. When None, defaults from build_probe_route_options(). |
None
|
runner
|
ProbeRunner | None
|
Optional ProbeRunner. When None, uses an internal reporting-mode runner. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[tuple[bytes, dict[str, str] | None, int]]]
|
An ASGI probe. |
Source code in fast_healthchecks/integrations/base.py
probe_path_suffix(probe)
¶
probe_route_path(probe, prefix='/health')
¶
Return the route path for a probe given a prefix.
FastAPI integration for health checks.
HealthcheckRouter
¶
Bases: APIRouter
A router for health checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*probes
|
Probe
|
Probes to run (e.g. liveness, readiness, startup). |
()
|
options
|
ProbeRouteOptions | None
|
Route options. When None, uses build_probe_route_options() defaults. |
None
|
To close health check resources (e.g. cached clients) on app shutdown,
call await router.close() from your FastAPI lifespan, or use
healthcheck_shutdown(probes) and call the returned callback.
Source code in fast_healthchecks/integrations/fastapi.py
__init__(*probes, options=None, runner=None)
¶
Initialize the router.
Source code in fast_healthchecks/integrations/fastapi.py
close()
async
¶
Close resources owned by this router's health check probes.
Call this from your FastAPI lifespan shutdown (e.g. after yield
in an @asynccontextmanager lifespan) so cached clients are closed.
Source code in fast_healthchecks/integrations/fastapi.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
FastStream integration for health checks.
health(*probes, options=None, runner=None)
¶
Make list of routes for healthchecks.
Returns:
| Type | Description |
|---|---|
Iterable[tuple[str, ASGIApp]]
|
Iterable[tuple[str, ASGIApp]]: Generated healthcheck routes. |
To close health check resources on app shutdown, pass the same probes
to healthcheck_shutdown(probes) and register the returned callback
with your FastStream app's shutdown hooks (e.g. @app.on_shutdown).
Source code in fast_healthchecks/integrations/faststream.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
Litestar integration for health checks.
health(*probes, options=None, runner=None)
¶
Make list of routes for healthchecks.
Returns:
| Type | Description |
|---|---|
Iterable[HTTPRouteHandler]
|
Iterable[HTTPRouteHandler]: Generated healthcheck route handlers. |
To close health check resources on app shutdown, pass the same probes
to healthcheck_shutdown(probes) and add the returned callback to
Litestar's on_shutdown list.
Source code in fast_healthchecks/integrations/litestar.py
healthcheck_shutdown(probes)
¶
Return an async shutdown callback that closes the given probes' checks.
Use this with framework lifespan/shutdown hooks (e.g. Litestar on_shutdown,
FastStream shutdown) so that health check resources are closed on app shutdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probes
|
Iterable[Probe]
|
The same probes passed to your health routes. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[], Awaitable[None]]
|
An async callable with no arguments that closes all checks with |
Source code in fast_healthchecks/integrations/base.py
Utility functions for fast-healthchecks.
maybe_redact(data, *, redact_secrets)
¶
Return data with secrets redacted when requested.
parse_query_string(query)
¶
Parse a URL query string into a dictionary.
Keys and values are URL-decoded (unquoted). Pairs without '=' are stored with an empty value. Values containing '=' are preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query string (e.g. 'key1=value1&key2=value2'). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
A dictionary of key-value pairs. |
Source code in fast_healthchecks/utils.py
redact_secrets_in_dict(data)
¶
Return a recursively redacted copy of a string-keyed dictionary.
Source code in fast_healthchecks/redaction.py
validate_host_ssrf_async(host)
async
¶
Resolve a host and reject failures or any non-global address.
Call this before making the request when block_private_hosts=True, so that hostnames that resolve to private IPs (e.g. internal DNS or DNS rebinding) are rejected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
host
|
str
|
The hostname to resolve and validate. |
required |
Raises:
| Type | Description |
|---|---|
HealthCheckSSRFError
|
If resolution fails or any resolved IP is non-global. |
Source code in fast_healthchecks/utils.py
validate_url_ssrf(url, *, allowed_schemes=frozenset({'http', 'https'}), block_private_hosts=False)
¶
Validate URL for SSRF-sensitive use (e.g. healthchecks from config).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL string to validate. |
required |
allowed_schemes
|
frozenset[str]
|
Schemes permitted (default http, https). |
frozenset({'http', 'https'})
|
block_private_hosts
|
bool
|
If True, reject localhost and non-global IP ranges. |
False
|
Raises:
| Type | Description |
|---|---|
HealthCheckSSRFError
|
If scheme or hostname is invalid, or the host is in a blocked range. |