Skip to main content

GET /health

Simple health check endpoint for monitoring API availability and uptime verification.


Endpoint

GET https://api.kixago.com/health

Authentication: Not required (public endpoint)


Request

Headers

No headers required. This endpoint is publicly accessible without authentication.

Example Request

curl "https://api.kixago.com/health"

Response

Success Response (200 OK)

{
"status": "ok",
"timestamp": "2025-01-15T14:30:00Z"
}

Response Schema

FieldTypeDescriptionExample
statusstringAPI status (always "ok" if responding)"ok"
timestampstringISO 8601 timestamp of the response"2025-01-15T14:30:00Z"

Use Cases

1. Uptime Monitoring

Use this endpoint to monitor API availability:

# Simple uptime check
curl -f "https://api.kixago.com/health" || echo "API is down!"

Monitoring services:

# Uptime Robot
Monitor Type: HTTP(s)
URL: https://api.kixago.com/health
Interval: 5 minutes
Expected Status: 200
# Pingdom
URL: https://api.kixago.com/health
Check Interval: 1 minute
Alert When: Status code != 200

2. Kubernetes Liveness Probe

# kubernetes.yaml
apiVersion: v1
kind: Pod
metadata:
name: myapp
spec:
containers:
- name: app
image: myapp:latest
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10

3. Load Balancer Health Check

# nginx.conf
upstream kixago_api {
server api.kixago.com:443;

# Health check configuration
check interval=5000 rise=2 fall=3 timeout=3000 type=http;
check_http_send "GET /health HTTP/1.1\r\nHost: api.kixago.com\r\n\r\n";
check_http_expect_alive http_2xx;
}

4. Integration Testing

// tests/integration/api-health.test.ts
describe('API Health Check', () => {
it('should return healthy status', async () => {
const response = await fetch('https://api.kixago.com/health');

expect(response.status).toBe(200);

const data = await response.json();
expect(data.status).toBe('ok');
expect(data.timestamp).toBeDefined();
});

it('should respond within 1 second', async () => {
const start = Date.now();
await fetch('https://api.kixago.com/health');
const duration = Date.now() - start;

expect(duration).toBeLessThan(1000);
});
});

5. Circuit Breaker Pattern

class CircuitBreaker {
private failureCount = 0;
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';

async checkHealth(): Promise<boolean> {
try {
const response = await fetch('https://api.kixago.com/health', {
signal: AbortSignal.timeout(5000)
});

if (response.ok) {
this.failureCount = 0;
this.state = 'CLOSED';
return true;
}

this.recordFailure();
return false;

} catch (err) {
this.recordFailure();
return false;
}
}

private recordFailure() {
this.failureCount++;

if (this.failureCount >= 3) {
this.state = 'OPEN';
console.error('Circuit breaker OPEN - API is unhealthy');
}
}

isHealthy(): boolean {
return this.state === 'CLOSED';
}
}

// Usage
const breaker = new CircuitBreaker();

setInterval(async () => {
await breaker.checkHealth();

if (!breaker.isHealthy()) {
// Disable API calls, use fallback, etc.
console.log('API unhealthy - using fallback mode');
}
}, 30000); // Check every 30 seconds

6. Status Page

// status-page.ts
async function getAPIStatus() {
try {
const start = Date.now();
const response = await fetch('https://api.kixago.com/health');
const duration = Date.now() - start;

if (response.ok) {
return {
status: 'operational',
responseTime: duration,
lastChecked: new Date().toISOString()
};
}

return {
status: 'degraded',
responseTime: duration,
lastChecked: new Date().toISOString()
};

} catch (err) {
return {
status: 'outage',
responseTime: null,
lastChecked: new Date().toISOString(),
error: err.message
};
}
}

// Display on status page
const status = await getAPIStatus();

console.log(`🟢 Kixago API: ${status.status}`);
console.log(` Response Time: ${status.responseTime}ms`);

7. Synthetic Monitoring

// Datadog Synthetic Test
// @datadog/synthetics-test

const { chromium } = require('@datadog/synthetics-test');

exports.handler = async () => {
const response = await fetch('https://api.kixago.com/health');

assert(response.status === 200, 'Health check returned non-200 status');

const data = await response.json();
assert(data.status === 'ok', 'Health check status is not ok');

return {
statusCode: 200,
body: 'Health check passed'
};
};

Response Examples

Example 1: Healthy API

Request:

curl -i "https://api.kixago.com/health"

Response:

HTTP/2 200 OK
Content-Type: application/json
Date: Wed, 15 Jan 2025 14:30:00 GMT
Content-Length: 58

{
"status": "ok",
"timestamp": "2025-01-15T14:30:00Z"
}

Example 2: With jq Parsing

# Extract just the status
curl -s "https://api.kixago.com/health" | jq -r '.status'
# Output: ok

# Check if healthy
if [ "$(curl -s https://api.kixago.com/health | jq -r '.status')" == "ok" ]; then
echo "✅ API is healthy"
else
echo "❌ API is unhealthy"
fi

Example 3: With Timeout

# Timeout after 5 seconds
curl --max-time 5 "https://api.kixago.com/health"

Error Scenarios

Network Error

If the API is unreachable:

curl "https://api.kixago.com/health"
# curl: (6) Could not resolve host: api.kixago.com

Exit code: Non-zero (use for monitoring)


Timeout

If the API doesn't respond within timeout:

curl --max-time 5 "https://api.kixago.com/health"
# curl: (28) Operation timed out after 5000 milliseconds

Monitoring Recommendations

Check Frequency

EnvironmentRecommended FrequencyNotes
Production1-5 minutesBalance between cost and early detection
Staging5-15 minutesLess critical than production
Development15-30 minutesOptional monitoring

Alert Thresholds

Set up alerts based on these thresholds:

MetricWarningCritical
Consecutive Failures2 failures3 failures
Response Time> 1 second> 3 seconds
Availability (24h)< 99.5%< 99%

Example Monitoring Script

#!/bin/bash
# health-check.sh

URL="https://api.kixago.com/health"
MAX_RESPONSE_TIME=3000 # milliseconds
ALERT_WEBHOOK="https://hooks.slack.com/services/YOUR/WEBHOOK"

# Measure response time
start=$(date +%s%3N)
response=$(curl -s -w "%{http_code}" -o /dev/null --max-time 10 "$URL")
end=$(date +%s%3N)
duration=$((end - start))

# Check status
if [ "$response" != "200" ]; then
# Alert: API is down
curl -X POST "$ALERT_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"🔴 Kixago API is DOWN (HTTP $response)\"}"
exit 1
fi

# Check response time
if [ "$duration" -gt "$MAX_RESPONSE_TIME" ]; then
# Alert: Slow response
curl -X POST "$ALERT_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"⚠️ Kixago API slow response: ${duration}ms\"}"
fi

echo "✅ Health check passed (${duration}ms)"
exit 0

Run via cron:

# Check every 5 minutes
*/5 * * * * /path/to/health-check.sh >> /var/log/kixago-health.log 2>&1

Code Examples

JavaScript/TypeScript

async function checkAPIHealth(): Promise<boolean> {
try {
const response = await fetch('https://api.kixago.com/health', {
signal: AbortSignal.timeout(5000) // 5 second timeout
});

if (!response.ok) {
return false;
}

const data = await response.json();
return data.status === 'ok';

} catch (err) {
console.error('Health check failed:', err);
return false;
}
}

// Usage
const isHealthy = await checkAPIHealth();
console.log(`API is ${isHealthy ? 'healthy ✅' : 'unhealthy ❌'}`);

Python

import requests

def check_api_health():
try:
response = requests.get(
'https://api.kixago.com/health',
timeout=5
)

if response.status_code != 200:
return False

data = response.json()
return data.get('status') == 'ok'

except requests.RequestException as e:
print(f'Health check failed: {e}')
return False

# Usage
if check_api_health():
print('✅ API is healthy')
else:
print('❌ API is unhealthy')

Go

package main

import (
"encoding/json"
"fmt"
"net/http"
"time"
)

type HealthResponse struct {
Status string `json:"status"`
Timestamp string `json:"timestamp"`
}

func checkAPIHealth() (bool, error) {
client := &http.Client{
Timeout: 5 * time.Second,
}

resp, err := client.Get("https://api.kixago.com/health")
if err != nil {
return false, err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}

var health HealthResponse
if err := json.NewDecoder(resp.Body).Decode(&health); err != nil {
return false, err
}

return health.Status == "ok", nil
}

func main() {
healthy, err := checkAPIHealth()
if err != nil {
fmt.Printf("❌ Health check failed: %v\n", err)
return
}

if healthy {
fmt.Println("✅ API is healthy")
} else {
fmt.Println("❌ API is unhealthy")
}
}

PHP

<?php
function checkAPIHealth(): bool {
$ch = curl_init('https://api.kixago.com/health');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
return false;
}

$data = json_decode($response, true);
return isset($data['status']) && $data['status'] === 'ok';
}

// Usage
if (checkAPIHealth()) {
echo "✅ API is healthy\n";
} else {
echo "❌ API is unhealthy\n";
}

Comparison with Risk Profile Endpoint

Feature/health/v1/risk-profile/{wallet}
Authentication❌ Not required✅ Required (API key)
Response Time< 100ms1-5 seconds
Rate Limited❌ No✅ Yes
PurposeUptime monitoringGet wallet data
CachingNo30 seconds
Use CaseHealth checksApplication logic

Best Practices

✅ DO

  • Use for uptime monitoring - Perfect for monitoring tools
  • Set reasonable timeouts - 5 seconds recommended
  • Check periodically - Every 1-5 minutes
  • Alert on consecutive failures - Not single failures
  • Track response time - Monitor performance trends
  • Use in CI/CD pipelines - Verify API availability before deployment

❌ DON'T

  • Don't use for business logic - Only for health checks
  • Don't check too frequently - Respect reasonable intervals
  • Don't rely on this alone - Also test authenticated endpoints
  • Don't ignore response time - Track degradation trends
  • Don't skip error handling - Always handle network errors

Troubleshooting

Issue: Health Check Failing

Symptoms:

curl: (6) Could not resolve host: api.kixago.com

Possible causes:

  1. DNS issue - Cannot resolve domain
  2. Network issue - Firewall blocking requests
  3. API outage - Service is down

Resolution:

# Test DNS resolution
nslookup api.kixago.com

# Test network connectivity
ping api.kixago.com

# Check firewall rules
curl -v "https://api.kixago.com/health"

Issue: Slow Response Time

Symptoms:

Health check takes > 1 second to respond

Possible causes:

  1. Network latency - Long distance to server
  2. API degradation - Increased load
  3. CDN issue - Edge node problems

Resolution:

# Measure detailed timing
curl -w "\nTime Total: %{time_total}s\nTime DNS: %{time_namelookup}s\nTime Connect: %{time_connect}s\n" \
"https://api.kixago.com/health"

Next Steps


Need Help?