# API Health Checker (`wheat_tourist/api-health-checker`) Actor

Monitor API endpoints with health scoring (0-100), performance ratings, and actionable insights. Checks availability, latency, and response validation. Retry logic with exponential backoff. Get recommendations for slow or failing endpoints. Perfect for uptime monitoring and SLA verification.

- **URL**: https://apify.com/wheat\_tourist/api-health-checker.md
- **Developed by:** [Varun Chopra](https://apify.com/wheat_tourist) (community)
- **Categories:** Developer tools, Automation, Other
- **Stats:** 3 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $10.00 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## API Health Checker

Comprehensive API health assessment engine with scoring, multi-dimensional evaluation, and actionable insights. Perfect for uptime monitoring, SLA verification, and automated health checks.

**Now with GenAI/LLM API monitoring** – supports OpenAI, Anthropic, Google AI, and Azure OpenAI.

### Features

- **Health Scoring (0-100)** – Quantitative assessment of each endpoint's health
- **Multi-Dimensional Evaluation** – Availability, performance, validation, reliability
- **Actionable Insights** – Deterministic recommendations for operators
- **Performance Rating** – fast / acceptable / slow classification
- **Configurable Scoring** – Custom thresholds and weights
- **Retry Logic** – Exponential backoff for transient failures
- **Fault Tolerant** – Individual failures don't crash the run

#### GenAI/LLM Features

- **Multi-Provider Support** – OpenAI, Anthropic, Google AI, Azure OpenAI, Custom
- **Token Usage Tracking** – Input/output/total tokens per request
- **Rate Limit Detection** – Automatic detection and retry on 429 errors
- **Content Filtering** – Detects safety filter activations
- **Time-to-First-Token** – Streaming latency measurement (coming soon)

### Health Scoring System

Each endpoint receives a health score from 0-100 based on four dimensions:

| Dimension | Weight | Description |
|-----------|--------|-------------|
| **Availability** | 40% | Endpoint reachable + correct status code |
| **Performance** | 30% | Latency rating (fast=100%, acceptable=67%, slow=33%) |
| **Validation** | 20% | Response validation passed |
| **Reliability** | 10% | Retry behavior (0 retries=100%, 1=70%, 2+=30%) |

#### Status Classification

| Status | Condition | Description |
|--------|-----------|-------------|
| `healthy` | Score ≥ 80 | Endpoint performing well |
| `degraded` | Score 50-79 | Endpoint has issues but functional |
| `unhealthy` | Score < 50 | Endpoint failing or critical issues |

### Input Example

#### Standard REST Endpoints

```json
{
    "endpoints": [
        {
            "name": "Production API",
            "url": "https://api.example.com/health",
            "method": "GET",
            "expectedStatus": 200,
            "timeoutMs": 10000,
            "maxLatencyMs": 2000,
            "validateJsonKeys": ["status"]
        }
    ],
    "retryCount": 3,
    "notifyOnFailure": true
}
```

#### GenAI Endpoints

```json
{
    "endpoints": [],
    "genaiEndpoints": [
        {
            "name": "OpenAI GPT-4",
            "provider": "openai",
            "model": "gpt-4",
            "apiKeyEnvVar": "OPENAI_API_KEY",
            "testPrompt": "Hi, respond with one word.",
            "maxTokens": 50,
            "timeoutMs": 30000
        },
        {
            "name": "Claude 3 Sonnet",
            "provider": "anthropic",
            "model": "claude-3-sonnet-20240229",
            "apiKeyEnvVar": "ANTHROPIC_API_KEY"
        },
        {
            "name": "Gemini Pro",
            "provider": "google",
            "model": "gemini-pro",
            "apiKeyEnvVar": "GOOGLE_AI_KEY"
        }
    ]
}
```

### Output Example

```json
{
    "summary": {
        "totalEndpoints": 3,
        "healthyEndpoints": 2,
        "degradedEndpoints": 1,
        "unhealthyEndpoints": 0,
        "averageLatencyMs": 450,
        "overallHealthScore": 85,
        "overallStatus": "degraded",
        "durationMs": 1523,
        "timestamp": "2024-01-15T10:00:00.000Z",
        "genai": {
            "totalGenAIEndpoints": 2,
            "totalTokensUsed": 150,
            "averageTTFTMs": null,
            "rateLimitedEndpoints": 0,
            "contentFilteredEndpoints": 0
        }
    },
    "results": [
        {
            "name": "OpenAI GPT-4",
            "url": "openai://gpt-4",
            "status": "healthy",
            "healthScore": 95,
            "latencyMs": 850,
            "isGenAI": true,
            "genaiMetrics": {
                "provider": "openai",
                "model": "gpt-4",
                "tokenUsage": {
                    "inputTokens": 10,
                    "outputTokens": 5,
                    "totalTokens": 15
                },
                "isRateLimited": false,
                "isContentFiltered": false,
                "responsePreview": "Hello!"
            }
        }
    ],
    "insights": {
        "recommendedActions": []
    }
}
```

### GenAI Provider Configuration

| Provider | Required Fields | Notes |
|----------|-----------------|-------|
| `openai` | model, apiKeyEnvVar | Uses chat/completions API |
| `anthropic` | model, apiKeyEnvVar | Uses messages API |
| `google` | model, apiKeyEnvVar | Uses generateContent API |
| `azure` | model, apiKeyEnvVar, baseUrl | OpenAI-compatible format |
| `custom` | model, apiKeyEnvVar, baseUrl | For self-hosted or other LLMs |

#### GenAI Endpoint Fields

| Field | Type | Required | Default |
|-------|------|----------|---------|
| `name` | String | ✓ | – |
| `provider` | String | ✓ | – |
| `model` | String | ✓ | – |
| `apiKeyEnvVar` | String | ✓ | – |
| `baseUrl` | String | \* | Provider default |
| `testPrompt` | String | | "Hi, respond with a single word." |
| `maxTokens` | Integer | | 50 |
| `timeoutMs` | Integer | | 30000 |
| `streaming` | Boolean | | false |

\* Required for `azure` and `custom` providers

### Insights & Recommendations

The Actor generates deterministic, rule-based recommendations:

| Condition | Recommendation |
|-----------|----------------|
| Endpoint unreachable | Investigate - endpoint is unreachable |
| Wrong status code | Check - returning X instead of expected Y |
| Slow performance | Optimize - latency exceeds threshold |
| GenAI rate limited | Implement backoff or increase quota |
| Content filtered | Review test prompt or safety settings |
| High token usage | Reduce test prompt complexity |

### Environment Variables

Set API keys as environment variables:

```bash
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GOOGLE_AI_KEY=AI...
```

Use `{{VAR_NAME}}` in REST endpoint headers:

```json
{
    "headers": {
        "Authorization": "Bearer {{API_TOKEN}}"
    }
}
```

### Programmatic Integration

```javascript
const result = await apify.actor('your-actor').call(input);
const output = await result.dataset().listItems();
const report = output[0];

if (report.summary.overallStatus === 'unhealthy') {
    // Trigger alert
}

// Check GenAI health
if (report.summary.genai?.rateLimitedEndpoints > 0) {
    // Handle rate limiting
}
```

### Limitations

- JSON key validation: top-level keys only
- Maximum timeout: 5 minutes per endpoint
- GenAI streaming TTFT: Coming in future release
- Retry delays capped at 30 seconds

### Technical Specifications

| Spec | Value |
|------|-------|
| Max timeout | 300,000 ms (5 min) |
| Max retry delay | 30,000 ms |
| Min timeout | 100 ms |
| Score range | 0-100 |
| GenAI max tokens | 1-1000 |

### Deployment

```bash
npm install
npm run build
apify push
```

### Support

- [Apify Documentation](https://docs.apify.com)

# Actor input Schema

## `endpoints` (type: `array`):

List of API endpoints to check for health

## `retryCount` (type: `integer`):

Retries for transient failures (exponential backoff)

## `notifyOnFailure` (type: `boolean`):

Log detailed notifications for unhealthy/degraded endpoints

## `performanceThresholds` (type: `object`):

Custom latency thresholds for performance rating

## `scoringWeights` (type: `object`):

Custom weights for health score calculation

## `genaiEndpoints` (type: `array`):

List of GenAI/LLM API endpoints to monitor (OpenAI, Anthropic, Google, Azure)

## `genaiThresholds` (type: `object`):

Performance thresholds for GenAI endpoints

## Actor input object example

```json
{
  "endpoints": [
    {
      "name": "Example API",
      "url": "https://api.example.com/health",
      "method": "GET",
      "expectedStatus": 200,
      "timeoutMs": 10000,
      "maxLatencyMs": 2000
    }
  ],
  "retryCount": 3,
  "notifyOnFailure": false,
  "genaiEndpoints": []
}
```

# Actor output Schema

## `healthReport` (type: `string`):

Complete API health assessment results including summary, endpoint details, and insights

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "endpoints": [
        {
            "name": "Example API",
            "url": "https://api.example.com/health",
            "method": "GET",
            "expectedStatus": 200,
            "timeoutMs": 10000,
            "maxLatencyMs": 2000
        }
    ],
    "genaiEndpoints": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("wheat_tourist/api-health-checker").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "endpoints": [{
            "name": "Example API",
            "url": "https://api.example.com/health",
            "method": "GET",
            "expectedStatus": 200,
            "timeoutMs": 10000,
            "maxLatencyMs": 2000,
        }],
    "genaiEndpoints": [],
}

# Run the Actor and wait for it to finish
run = client.actor("wheat_tourist/api-health-checker").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "endpoints": [
    {
      "name": "Example API",
      "url": "https://api.example.com/health",
      "method": "GET",
      "expectedStatus": 200,
      "timeoutMs": 10000,
      "maxLatencyMs": 2000
    }
  ],
  "genaiEndpoints": []
}' |
apify call wheat_tourist/api-health-checker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=wheat_tourist/api-health-checker",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Gl9x26HA44LkCUsdk/builds/PPTrLI9cTKkN1j2tF/openapi.json
