> ## Documentation Index
> Fetch the complete documentation index at: https://docs.intentgpt.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# System & Testing

> Health checks, testing, and system monitoring endpoints

## Overview

The System & Testing endpoints provide tools for monitoring API health, testing authentication, and ensuring proper system functionality. These endpoints are essential for monitoring and debugging integrations.

## Health Check

### GET /health

Comprehensive system health check that verifies API server status, database connectivity, and authentication services. This endpoint does not require authentication.

#### Example Request

```bash theme={null}
curl -X GET "https://api.intentgpt.ai/health"
```

#### Response Statuses

* **200 OK**: All systems operational
* **207 Multi-Status**: Some systems degraded but API functional
* **503 Service Unavailable**: Critical systems down

#### Healthy Response (200)

```json theme={null}
{
  "status": "OK",
  "version": "1.0.0",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "response_time_ms": 45,
  "checks": {
    "api_server": {
      "status": "OK"
    },
    "database": {
      "status": "OK",
      "connection": "OK",
      "tables": {
        "api_management.api_keys": {
          "status": "OK",
          "exists": true,
          "num_rows": 1250,
          "created": "2023-01-01T00:00:00.000Z",
          "modified": "2024-01-15T09:45:00.000Z"
        },
        "api_management.user_credits": {
          "status": "OK", 
          "exists": true,
          "num_rows": 1250
        },
        "api_management.usage_logs": {
          "status": "OK",
          "exists": true,
          "num_rows": 125000
        }
      }
    },
    "authentication": {
      "status": "OK"
    }
  }
}
```

#### Degraded Response (207)

```json theme={null}
{
  "status": "DEGRADED",
  "version": "1.0.0", 
  "timestamp": "2024-01-15T10:30:00.000Z",
  "response_time_ms": 1200,
  "message": "Missing required tables: api_management.usage_logs",
  "checks": {
    "api_server": {
      "status": "OK"
    },
    "database": {
      "status": "DEGRADED",
      "connection": "OK",
      "missing_tables": ["api_management.usage_logs"],
      "tables": {
        "api_management.api_keys": {
          "status": "OK",
          "exists": true
        },
        "api_management.user_credits": {
          "status": "OK",
          "exists": true
        },
        "api_management.usage_logs": {
          "status": "OK",
          "exists": false,
          "error": "Table api_management.usage_logs not found"
        }
      }
    },
    "authentication": {
      "status": "OK"
    }
  }
}
```

#### Error Response (503)

```json theme={null}
{
  "status": "ERROR",
  "version": "1.0.0",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "error": "Health check failed",
  "details": "Database connection timeout",
  "checks": {
    "api_server": {
      "status": "OK"
    },
    "database": {
      "status": "ERROR", 
      "error": "Connection timeout after 30 seconds"
    },
    "authentication": {
      "status": "UNKNOWN"
    }
  }
}
```

## Authentication Testing

### GET /test-auth

Test endpoint to verify that your authentication is working correctly. Supports both API key and JWT token authentication methods.

#### Authentication Methods

The endpoint will detect and test whichever authentication method you provide:

1. **API Key**: Use `X-API-Key` header
2. **JWT Token**: Use `Authorization: Bearer` header
3. **Legacy API Key**: Use `Authorization: Bearer` with legacy key

#### Example: Test API Key

```bash theme={null}
curl -X GET "https://api.intentgpt.ai/test-auth" \
-H "X-API-Key: your_api_key"
```

#### Example: Test JWT Token

```bash theme={null}
curl -X GET "https://api.intentgpt.ai/test-auth" \
-H "Authorization: Bearer your_jwt_token"
```

#### Success Response (200)

**API Key Authentication:**

```json theme={null}
{
  "message": "Authenticated via API Key",
  "auth_method": "api_key",
  "user_id": "user_abc123def456"
}
```

**JWT Authentication:**

```json theme={null}
{
  "message": "Authenticated via Clerk",
  "auth_method": "clerk", 
  "user_id": "user_clerk_xyz789"
}
```

**Legacy API Key:**

```json theme={null}
{
  "message": "Authenticated via API Key",
  "auth_method": "legacy_api_key",
  "user_id": "legacy_key_abcdef12..."
}
```

#### Error Response (401)

```json theme={null}
{
  "error": "Authentication required",
  "details": "Use either X-API-Key header or Bearer token"
}
```

## CORS Testing

### GET /cors-test

Test Cross-Origin Resource Sharing (CORS) configuration. This endpoint helps verify that your web application can properly communicate with the API from browser environments.

#### Example Request

```bash theme={null}
curl -X GET "https://api.intentgpt.ai/cors-test" \
-H "Origin: https://yourdomain.com"
```

#### Response

```json theme={null}
{
  "message": "CORS test successful",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

#### CORS Headers

The API supports requests from these origins:

* `https://intentgpt.ai`
* `https://www.intentgpt.ai`
* `http://localhost:8080`
* `http://localhost:3000`
* Development workstation URLs

## System Monitoring

### Health Check Integration

The health check endpoint is designed for integration with monitoring systems:

#### Kubernetes Liveness Probe

```yaml theme={null}
livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
  failureThreshold: 3
```

#### Docker Health Check

```dockerfile theme={null}
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
  CMD curl -f http://localhost/health || exit 1
```

#### Monitoring Script

```python theme={null}
import requests
import time

def monitor_api_health():
    """Monitor API health and alert on issues"""
    
    try:
        response = requests.get('https://api.intentgpt.ai/health', timeout=30)
        
        if response.status_code == 200:
            data = response.json()
            print(f"✅ API healthy - Response time: {data['response_time_ms']}ms")
            
        elif response.status_code == 207:
            data = response.json()
            print(f"⚠️  API degraded - {data.get('message', 'Some systems degraded')}")
            
        elif response.status_code >= 500:
            print("🚨 API down - Critical error")
            
    except requests.RequestException as e:
        print(f"🚨 API unreachable - {str(e)}")

# Run monitoring
while True:
    monitor_api_health()
    time.sleep(60)  # Check every minute
```

## Error Diagnosis

### Common Issues

#### Authentication Failures

**Symptom**: 401 errors on `/test-auth`
**Solutions**:

1. Verify API key format and validity
2. Check header format (`X-API-Key` vs `Authorization: Bearer`)
3. Ensure key is active using `/toggle_key` endpoint

#### Health Check Degraded

**Symptom**: 207 status on `/health`
**Solutions**:

1. Check database connectivity
2. Verify required tables exist
3. Review system logs for errors

#### CORS Issues

**Symptom**: Browser requests blocked
**Solutions**:

1. Verify origin is in allowed list
2. Test with `/cors-test` endpoint
3. Check preflight OPTIONS requests

### Testing Checklist

Before going to production, test these scenarios:

* [ ] Health check returns 200 OK
* [ ] API key authentication works via `X-API-Key` header
* [ ] JWT token authentication works via `Authorization: Bearer`
* [ ] CORS requests succeed from your domain
* [ ] Error responses are properly formatted
* [ ] Rate limiting is functioning (if applicable)

## Integration Examples

### Frontend Health Check

```javascript theme={null}
// Check API health before making requests
const checkApiHealth = async () => {
  try {
    const response = await fetch('https://api.intentgpt.ai/health');
    const health = await response.json();
    
    if (response.status === 200) {
      console.log('API is healthy');
      return true;
    } else if (response.status === 207) {
      console.warn('API is degraded:', health.message);
      return true; // Still functional
    } else {
      console.error('API is down');
      return false;
    }
  } catch (error) {
    console.error('Cannot reach API:', error);
    return false;
  }
};

// Test authentication before critical operations
const testAuth = async (apiKey) => {
  try {
    const response = await fetch('https://api.intentgpt.ai/test-auth', {
      headers: { 'X-API-Key': apiKey }
    });
    
    if (response.status === 200) {
      const auth = await response.json();
      console.log('Authentication successful:', auth.auth_method);
      return true;
    } else {
      console.error('Authentication failed');
      return false;
    }
  } catch (error) {
    console.error('Auth test failed:', error);
    return false;
  }
};
```

### Backend Monitoring

```python theme={null}
import requests
import logging

class APIMonitor:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.intentgpt.ai"
        
    def comprehensive_check(self):
        """Run all system checks"""
        results = {
            'health': self.check_health(),
            'auth': self.check_auth(),
            'cors': self.check_cors()
        }
        
        # Log results
        for check, result in results.items():
            if result['status'] == 'ok':
                logging.info(f"✅ {check.upper()} check passed")
            else:
                logging.error(f"❌ {check.upper()} check failed: {result['error']}")
                
        return results
        
    def check_health(self):
        try:
            response = requests.get(f"{self.base_url}/health", timeout=10)
            if response.status_code in [200, 207]:
                return {'status': 'ok', 'data': response.json()}
            else:
                return {'status': 'error', 'error': f"HTTP {response.status_code}"}
        except Exception as e:
            return {'status': 'error', 'error': str(e)}
            
    def check_auth(self):
        try:
            response = requests.get(
                f"{self.base_url}/test-auth",
                headers={'X-API-Key': self.api_key},
                timeout=10
            )
            if response.status_code == 200:
                return {'status': 'ok', 'data': response.json()}
            else:
                return {'status': 'error', 'error': f"HTTP {response.status_code}"}
        except Exception as e:
            return {'status': 'error', 'error': str(e)}
            
    def check_cors(self):
        try:
            response = requests.get(
                f"{self.base_url}/cors-test",
                headers={'Origin': 'https://yourdomain.com'},
                timeout=10
            )
            if response.status_code == 200:
                return {'status': 'ok', 'data': response.json()}
            else:
                return {'status': 'error', 'error': f"HTTP {response.status_code}"}
        except Exception as e:
            return {'status': 'error', 'error': str(e)}

# Usage
monitor = APIMonitor("your_api_key")
results = monitor.comprehensive_check()
```

## Best Practices

### Monitoring

1. **Regular Health Checks**: Monitor `/health` every 1-5 minutes
2. **Alert Thresholds**: Alert on 207 (degraded) and 503 (down) responses
3. **Response Time Monitoring**: Track `response_time_ms` for performance trends

### Testing

1. **Pre-deployment Testing**: Always test auth before deploying
2. **CORS Validation**: Test from actual client domains
3. **Error Handling**: Verify your app handles API errors gracefully

### Debugging

1. **Use Test Endpoints**: Leverage `/test-auth` for debugging auth issues
2. **Check Health Details**: Review specific component failures in health checks
3. **Monitor Logs**: Enable logging for all API interactions during debugging
