Metadata-Version: 2.4
Name: fastapi-neo4j-healthcheck
Version: 0.2.0
Summary: Lightweight Neo4j readiness endpoint for FastAPI
Keywords: fastapi,neo4j,healthcheck,kubernetes,readiness,monitoring,cypher
Author-email: Gabaoun <94999154+gabaoun@users.noreply.github.com>
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Framework :: FastAPI
Classifier: Topic :: System :: Monitoring
License-File: LICENSE
Requires-Dist: fastapi>=0.100.0
Requires-Dist: neo4j>=5.0.0 ; extra == "neo4j"
Requires-Dist: pytest>=8.0.0 ; extra == "test"
Requires-Dist: pytest-asyncio>=0.23.0 ; extra == "test"
Requires-Dist: pytest-cov>=5.0.0 ; extra == "test"
Requires-Dist: httpx>=0.27.0 ; extra == "test"
Requires-Dist: neo4j>=5.0.0 ; extra == "test"
Requires-Dist: ruff>=0.5.0 ; extra == "test"
Project-URL: Homepage, https://github.com/gabaoun/fastapi-neo4j-healthcheck
Project-URL: Issues, https://github.com/gabaoun/fastapi-neo4j-healthcheck/issues
Project-URL: Repository, https://github.com/gabaoun/fastapi-neo4j-healthcheck
Provides-Extra: neo4j
Provides-Extra: test

# fastapi-neo4j-healthcheck 🚀

[![PyPI version](https://img.shields.io/pypi/v/fastapi-neo4j-healthcheck?color=blue)](https://pypi.org/project/fastapi-neo4j-healthcheck/)
[![Python Versions](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://pypi.org/project/fastapi-neo4j-healthcheck/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI Status](https://github.com/gabaoun/fastapi-neo4j-healthcheck/actions/workflows/ci.yml/badge.svg)](https://github.com/gabaoun/fastapi-neo4j-healthcheck/actions)

Lightweight Neo4j readiness endpoint for [FastAPI](https://fastapi.tiangolo.com/).

## Features

- ⚡ **Sync & Async Driver Support**: Seamlessly works with `neo4j.AsyncGraphDatabase` and `neo4j.GraphDatabase`.
- 🩺 **Non-Blocking Ping**: Executes lightweight Cypher queries (`RETURN 1 AS ping`) off the main thread or via async I/O.
- ⏱️ **Timeout Protection**: Configurable timeout (default `3.0s`) to prevent health check hangs during database failover or high load.
- ⚓ **Kubernetes Ready**: Returns `200 OK` when healthy and `503 Service Unavailable` (customizable) when degraded.
- 📊 **Observability & Latency**: Includes latency in milliseconds (`latency_ms`) and database target details in the response payload.

## Installation

```bash
pip install fastapi-neo4j-healthcheck
```

Or with `neo4j` driver included:

```bash
pip install fastapi-neo4j-healthcheck[neo4j]
```

## Quickstart

### 1. Using Async Neo4j Driver (Recommended)

```python
from fastapi import FastAPI
from neo4j import AsyncGraphDatabase
from fastapi_neo4j_healthcheck import create_neo4j_health_router

app = FastAPI(title="Graph API")

# Initialize Neo4j Async Driver
driver = AsyncGraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

# Include Health Check Router
app.include_router(
    create_neo4j_health_router(
        driver_provider=driver,
        prefix="/health/neo4j",
        tags=["Health"],
    )
)
```

### 2. Using Sync Neo4j Driver

```python
from fastapi import FastAPI
from neo4j import GraphDatabase
from fastapi_neo4j_healthcheck import create_neo4j_health_router

app = FastAPI()
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))

app.include_router(
    create_neo4j_health_router(driver_provider=driver, prefix="/healthcheck")
)
```

### 3. Dynamic / Dependency-Injected Driver Provider

```python
from fastapi import FastAPI
from fastapi_neo4j_healthcheck import create_neo4j_health_router

app = FastAPI()


def get_db_driver():
    # Resolved on every request, e.g. a driver created in the app lifespan
    return app.state.neo4j_driver


app.include_router(
    create_neo4j_health_router(driver_provider=get_db_driver)
)
```

## Response Schema

### Healthy (HTTP 200)

```json
{
  "status": "healthy",
  "database": "neo4j",
  "latency_ms": 3.45,
  "details": {
    "connected": true
  }
}
```

### Unhealthy (HTTP 503)

```json
{
  "status": "unhealthy",
  "database": "neo4j",
  "latency_ms": 3001.12,
  "details": {
    "connected": false,
    "error": "ServiceUnavailable"
  }
}
```

By default only the exception class name is returned, because raw driver messages can leak
host, port and database names to unauthenticated callers. The full error is logged with
`logging` (logger `fastapi_neo4j_healthcheck.health`, with traceback). To include the raw
message in the response (e.g. on an internal-only endpoint), pass `expose_errors=True`.

## Kubernetes Readiness Probe Configuration

```yaml
readinessProbe:
  httpGet:
    path: /health/neo4j
    port: 8000
  initialDelaySeconds: 2
  periodSeconds: 5
```

Use this endpoint as a **readiness** probe only. Do not point a `livenessProbe` at it: a
database outage would make Kubernetes restart every healthy pod, which does not fix the
database and turns a partial outage into a full one. Liveness should only check that the
process itself is responsive. For that, pass `liveness_prefix` and the router registers a
separate endpoint that never touches Neo4j:

```python
app.include_router(
    create_neo4j_health_router(
        driver_provider=driver,
        prefix="/health/neo4j",
        liveness_prefix="/livez",
    )
)
```

```yaml
livenessProbe:
  httpGet:
    path: /livez
    port: 8000
  periodSeconds: 10
```

`/livez` returns `200 {"status": "alive"}` while the process can serve a request. It is
off by default (`liveness_prefix=None`).

## License

[MIT License](LICENSE) - Created by [Gabaoun](https://github.com/gabaoun).

