Skip to content

Health API Integration Guide for Admin Panel

Overview

The Health API provides real-time system monitoring and diagnostics for the tracker pipeline system. This guide shows how to integrate these endpoints into the admin panel for comprehensive system health monitoring.

Quick Start

Authentication

All health endpoints require admin authentication. Include the JWT token in requests:

const token = localStorage.getItem("adminToken");
const headers = {
  Authorization: `Bearer ${token}`,
  "Content-Type": "application/json",
};

Basic Health Check

For dashboard status indicators:

async function getSystemStatus() {
  const response = await fetch("/api/v1/health/status", { headers });
  const data = await response.json();
  return data.status; // "healthy", "degraded", "unhealthy", "critical"
}

Comprehensive Health Dashboard

For detailed health monitoring:

async function getSystemHealth() {
  const response = await fetch("/api/v1/health/system", { headers });
  return await response.json();
}

UI Integration Examples

Status Badge Component

function SystemStatusBadge() {
  const [status, setStatus] = useState("unknown");

  useEffect(() => {
    const checkStatus = async () => {
      try {
        const response = await fetch("/api/v1/health/status", { headers });
        const data = await response.json();
        setStatus(data.status);
      } catch (error) {
        setStatus("error");
      }
    };

    checkStatus();
    const interval = setInterval(checkStatus, 30000); // Check every 30s
    return () => clearInterval(interval);
  }, []);

  const getStatusColor = (status) => {
    switch (status) {
      case "healthy":
        return "green";
      case "degraded":
        return "yellow";
      case "unhealthy":
        return "orange";
      case "critical":
        return "red";
      default:
        return "gray";
    }
  };

  return (
    <div className={`status-badge ${getStatusColor(status)}`}>
      System: {status.toUpperCase()}
    </div>
  );
}

Health Dashboard Component

function HealthDashboard() {
  const [healthData, setHealthData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchHealthData = async () => {
      try {
        const response = await fetch("/api/v1/health/system", { headers });
        const data = await response.json();
        setHealthData(data);
      } catch (error) {
        console.error("Failed to fetch health data:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchHealthData();
  }, []);

  if (loading) return <div>Loading health data...</div>;

  return (
    <div className="health-dashboard">
      <h2>System Health</h2>

      {/* Overall Status */}
      <div className="health-overview">
        <h3>Overall Status: {healthData.status}</h3>
        <p>Last checked: {new Date(healthData.timestamp).toLocaleString()}</p>
      </div>

      {/* Basic Infrastructure */}
      <div className="infrastructure-health">
        <h3>Infrastructure</h3>
        <div className="component">
          Database: {healthData.basic_health.components.database.status}
        </div>
        <div className="component">
          Redis: {healthData.basic_health.components.redis.status}
        </div>
      </div>

      {/* Pipeline Health */}
      <div className="pipeline-health">
        <h3>Pipeline Health</h3>
        <div className="metric">
          Success Rate: {healthData.pipeline_health.success_rate}%
        </div>
        <div className="metric">
          Tests Passed: {healthData.pipeline_health.successful_steps}/
          {healthData.pipeline_health.total_steps}
        </div>
      </div>

      {/* Recommendations */}
      {healthData.pipeline_health.recommendations.length > 0 && (
        <div className="recommendations">
          <h3>Recommendations</h3>
          {healthData.pipeline_health.recommendations.map((rec, index) => (
            <div key={index} className={`recommendation ${rec.severity}`}>
              <strong>{rec.issue}</strong>
              <p>{rec.action}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Diagnostics Page Component

function DiagnosticsPage() {
  const [pipelineHealth, setPipelineHealth] = useState(null);
  const [loading, setLoading] = useState(true);

  const refreshDiagnostics = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/v1/health/pipeline", { headers });
      const data = await response.json();
      setPipelineHealth(data);
    } catch (error) {
      console.error("Failed to fetch pipeline health:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    refreshDiagnostics();
  }, []);

  if (loading) return <div>Running diagnostics...</div>;

  return (
    <div className="diagnostics-page">
      <div className="diagnostics-header">
        <h2>System Diagnostics</h2>
        <button onClick={refreshDiagnostics} disabled={loading}>
          Refresh Diagnostics
        </button>
      </div>

      {/* Test Results */}
      <div className="test-results">
        {Object.entries(pipelineHealth.test_steps).map(([key, step]) => (
          <div
            key={key}
            className={`test-step ${step.success ? "success" : "failure"}`}
          >
            <h3>{step.name}</h3>
            <div className="test-status">
              Status: {step.success ? "PASS" : "FAIL"}
            </div>

            {step.issues.length > 0 && (
              <div className="issues">
                <h4>Issues:</h4>
                <ul>
                  {step.issues.map((issue, index) => (
                    <li key={index}>{issue}</li>
                  ))}
                </ul>
              </div>
            )}

            {step.details && (
              <details>
                <summary>Details</summary>
                <pre>{JSON.stringify(step.details, null, 2)}</pre>
              </details>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

Styling Suggestions

CSS for Health Components

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-weight: bold;
  text-transform: uppercase;
  font-size: 12px;
}

.status-badge.green {
  background: #10b981;
  color: white;
}
.status-badge.yellow {
  background: #f59e0b;
  color: white;
}
.status-badge.orange {
  background: #f97316;
  color: white;
}
.status-badge.red {
  background: #ef4444;
  color: white;
}
.status-badge.gray {
  background: #6b7280;
  color: white;
}

.health-dashboard {
  padding: 20px;
  max-width: 1200px;
}

.health-overview {
  background: #f8fafc;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.infrastructure-health,
.pipeline-health {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.component,
.metric {
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.recommendations {
  background: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 8px;
  padding: 16px;
}

.recommendation.critical {
  background: #fee2e2;
  border-color: #ef4444;
}

.recommendation.warning {
  background: #fef3c7;
  border-color: #f59e0b;
}

.test-step {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.test-step.success {
  border-color: #10b981;
  background: #f0fdf4;
}

.test-step.failure {
  border-color: #ef4444;
  background: #fef2f2;
}

Performance Recommendations

  1. Polling Frequency:
  2. Status checks: Every 30 seconds
  3. Full health checks: Every 5 minutes
  4. Diagnostics: On-demand only

  5. Caching:

  6. Cache health data for 30 seconds
  7. Show loading states during refresh
  8. Handle network errors gracefully

  9. User Experience:

  10. Show timestamps for all health data
  11. Provide manual refresh buttons
  12. Display response times for transparency

Error Handling

async function fetchWithErrorHandling(url) {
  try {
    const response = await fetch(url, { headers });

    if (!response.ok) {
      if (response.status === 401) {
        // Redirect to login
        window.location.href = "/login";
        return null;
      }
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    return await response.json();
  } catch (error) {
    console.error("Health API error:", error);
    // Show user-friendly error message
    showNotification("Unable to fetch system health data", "error");
    return null;
  }
}

Integration Checklist

  • Add health status badge to main navigation
  • Create dedicated health dashboard page
  • Implement diagnostics page for troubleshooting
  • Set up automatic polling for status updates
  • Add error handling and loading states
  • Style components to match admin panel theme
  • Test with different health scenarios
  • Add documentation for admin users

API Endpoints Summary

Endpoint Purpose Response Time Polling Frequency
/health/status Quick status check ~50ms Every 30s
/health/basic Infrastructure health ~50ms Every 2 minutes
/health/pipeline Full diagnostics ~1-3s On-demand
/health/system Complete overview ~1-3s Every 5 minutes

Testing

The Health API integration has comprehensive behavioral test coverage that validates real admin panel workflows:

Test Coverage

The health monitoring system includes 41 comprehensive tests that validate:

  • Admin Panel Integration: Dashboard loading, status widgets, real-time updates
  • Authentication & Authorization: Admin-only access, token validation, error handling
  • Performance Requirements: Response time validation for different endpoint types
  • Error Recovery: Database failures, partial service failures, graceful degradation
  • Business Workflows: Daily health assessments, incident response, troubleshooting
  • Compliance & Reporting: Management reporting, audit trails, business continuity

Test Organization

tests/behaviors/health_monitoring/
├── test_health_api_routes.py          # API endpoint behavioral tests (17 tests)
├── test_health_service_operations.py  # Service layer behavioral tests (20 tests)
└── test_health_integration_workflows.py # End-to-end workflow tests (4 tests)

Key Test Scenarios for Admin Panel Integration

  1. Dashboard Widget Performance:
  2. Status endpoint responds within 500ms for dashboard widgets
  3. Basic health endpoint suitable for frequent polling
  4. Consistent status reporting across concurrent requests

  5. Real-time Dashboard Integration:

  6. Multiple concurrent health requests work correctly
  7. Dashboard data consistency across widgets
  8. Auto-refresh functionality maintains performance

  9. Admin Panel Authentication:

  10. Health endpoints properly require admin authentication
  11. Non-admin users are correctly rejected
  12. Invalid tokens are handled gracefully

  13. Error Handling for UI:

  14. Database connection failures are reported clearly
  15. Partial service failures provide detailed component status
  16. API errors include user-friendly error messages

  17. Complete Admin Workflows:

  18. Daily health assessment routines
  19. Incident response monitoring workflows
  20. System troubleshooting with diagnostic information

Running Integration Tests

# Run all health monitoring tests
./run_tests_with_coverage.sh tests/behaviors/health_monitoring/

# Run specific admin panel integration tests
./run_tests_with_coverage.sh tests/behaviors/health_monitoring/test_health_api_routes.py::TestAdminPanelHealthAPIIntegration

# Run real-time dashboard integration tests
./run_tests_with_coverage.sh tests/behaviors/health_monitoring/test_health_integration_workflows.py::TestCompleteHealthMonitoringWorkflows::test_admin_panel_real_time_health_dashboard_integration

Testing Your Integration

When implementing health API integration in your admin panel:

  1. Test Authentication: Ensure your JWT token handling works with health endpoints
  2. Test Performance: Verify response times meet your dashboard requirements
  3. Test Error Handling: Simulate network failures and API errors
  4. Test Real-time Updates: Verify polling and auto-refresh functionality
  5. Test Different Health States: Test with healthy, degraded, and unhealthy system states

For detailed testing implementation information, see Health API Testing Implementation.

Next Steps

  1. Implement the basic status badge first
  2. Add the health dashboard page
  3. Create the diagnostics page for troubleshooting
  4. Test with various system states using the behavioral test scenarios
  5. Add monitoring alerts based on health status
  6. Validate integration using the comprehensive test suite