API Status Checker: Monitor Your API Health
Overview
The API Status Checker provides a powerful way to monitor the health, performance, and uptime of your APIs and web services. Whether you’re tracking your own endpoints or monitoring third-party services your application depends on, this API gives you real-time insights into service availability and performance metrics.
Quick Start
# Check default endpoints
curl "https://blstmo.com/api/status-checker"
# Check specific endpoints
curl "https://blstmo.com/api/status-checker?urls=https://api.example.com/health,https://api.another.com/status"
Key Features
- Real-time Status Checks: Get immediate feedback on endpoint availability
- Performance Metrics: Track response times and identify slow endpoints
- Historical Data: View trends with up to 100 historical data points per endpoint
- Uptime Calculation: Automatically calculate uptime percentage based on historical checks
- Multiple Endpoint Support: Check up to 10 endpoints in a single request
- Status Classification: Endpoints are classified as ‘up’, ‘down’, or ‘degraded’
- Summary Statistics: Get an overview of all monitored endpoints
API Reference
Endpoint
GET https://blstmo.com/api/status-checker
Query Parameters
Parameter | Type | Required | Description |
---|---|---|---|
urls | string | No | Comma-separated list of URLs to check. If not provided, default endpoints will be checked. |
Response Format
{
endpoints: [
{
url: string; // The URL that was checked
status: 'up' | 'down' | 'degraded'; // Current status
responseTime: number; // Response time in milliseconds
statusCode: number; // HTTP status code
lastChecked: string; // ISO timestamp of the check
history: [ // Historical check data
{
timestamp: string; // ISO timestamp
status: 'up' | 'down' | 'degraded';
responseTime: number; // Response time in milliseconds
statusCode: number; // HTTP status code
}
];
uptime: number; // Uptime percentage (0-100)
contentType?: string; // Content type of the response
error?: string; // Error message if the check failed
}
],
summary: {
healthy: number; // Count of healthy endpoints
degraded: number; // Count of degraded endpoints
down: number; // Count of down endpoints
averageResponseTime: number; // Average response time across all endpoints
overallStatus: 'operational' | 'degraded' | 'outage'; // Overall system status
}
}
Status Classification
Endpoints are classified based on HTTP status codes and response times:
-
Up:
- HTTP status code 2xx
- Response time ≤ 300ms
-
Degraded:
- HTTP status code 2xx but response time > 300ms
- HTTP status code 3xx or 4xx
-
Down:
- HTTP status code 5xx
- Connection timeout or error
- DNS resolution failure
Rate Limiting
The API is rate-limited to 120 requests per minute. If you exceed this limit, you will receive a 429 status code with an error message.
Implementation Examples
JavaScript/TypeScript
interface EndpointStatus {
url: string;
status: 'up' | 'down' | 'degraded';
responseTime: number;
statusCode: number;
lastChecked: string;
history: {
timestamp: string;
status: 'up' | 'down' | 'degraded';
responseTime: number;
statusCode: number;
}[];
uptime: number;
contentType?: string;
error?: string;
}
interface StatusResponse {
endpoints: EndpointStatus[];
summary: {
healthy: number;
degraded: number;
down: number;
averageResponseTime: number;
overallStatus: 'operational' | 'degraded' | 'outage';
};
}
async function checkApiStatus(urls?: string[]): Promise<StatusResponse> {
try {
const urlParam = urls ? `?urls=${urls.join(',')}` : '';
const response = await fetch(`https://blstmo.com/api/status-checker${urlParam}`);
if (response.status === 429) {
throw new Error('Rate limit exceeded. Please try again later.');
}
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to check API status');
}
return await response.json();
} catch (error) {
console.error('API Status check failed:', error);
throw error;
}
}
// Example usage
async function monitorServices() {
try {
// Check specific endpoints
const result = await checkApiStatus([
'https://api.example.com/health',
'https://api.another-service.com/status'
]);
console.log('Overall status:', result.summary.overallStatus);
console.log('Average response time:', result.summary.averageResponseTime, 'ms');
// Log details for each endpoint
result.endpoints.forEach(endpoint => {
console.log(`${endpoint.url}: ${endpoint.status} (${endpoint.responseTime}ms)`);
console.log(` Uptime: ${endpoint.uptime}%`);
if (endpoint.status !== 'up') {
console.warn(` Warning: Endpoint is ${endpoint.status}`);
if (endpoint.error) {
console.error(` Error: ${endpoint.error}`);
}
}
});
// Take action based on status
if (result.summary.overallStatus !== 'operational') {
sendAlert(`System status: ${result.summary.overallStatus}`);
}
} catch (error) {
console.error('Monitoring failed:', error);
}
}
// Run monitoring every 5 minutes
setInterval(monitorServices, 5 * 60 * 1000);
Python
import requests
import time
from typing import List, Dict, Any, Optional, Union, Literal
class ApiStatusChecker:
def __init__(self, base_url: str = "https://blstmo.com"):
self.base_url = base_url
def check_status(self, urls: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Check the status of API endpoints.
Args:
urls: List of URLs to check. If None, default endpoints will be checked.
Returns:
Dict containing endpoint statuses and summary information.
Raises:
requests.exceptions.HTTPError: If the API request fails.
ValueError: If rate limit is exceeded.
"""
endpoint = f"{self.base_url}/api/status-checker"
params = {}
if urls:
params['urls'] = ','.join(urls)
response = requests.get(endpoint, params=params)
if response.status_code == 429:
raise ValueError("Rate limit exceeded. Please try again later.")
response.raise_for_status()
return response.json()
def monitor_services(self, urls: List[str], interval_seconds: int = 300,
callback: Optional[callable] = None) -> None:
"""
Continuously monitor services at the specified interval.
Args:
urls: List of URLs to monitor.
interval_seconds: Time between checks in seconds.
callback: Function to call with results after each check.
"""
while True:
try:
result = self.check_status(urls)
print(f"Overall status: {result['summary']['overallStatus']}")
print(f"Average response time: {result['summary']['averageResponseTime']}ms")
# Process each endpoint
for endpoint in result['endpoints']:
status_emoji = "✅" if endpoint['status'] == 'up' else "⚠️" if endpoint['status'] == 'degraded' else "❌"
print(f"{status_emoji} {endpoint['url']}: {endpoint['status']} ({endpoint['responseTime']}ms)")
print(f" Uptime: {endpoint['uptime']}%")
if endpoint['status'] != 'up' and endpoint.get('error'):
print(f" Error: {endpoint['error']}")
# Call the callback if provided
if callback:
callback(result)
except Exception as e:
print(f"Monitoring error: {str(e)}")
# Wait for the next interval
time.sleep(interval_seconds)
# Example usage
if __name__ == "__main__":
checker = ApiStatusChecker()
# One-time check
try:
status = checker.check_status([
"https://api.example.com/health",
"https://api.another.com/status"
])
print(f"Status: {status['summary']['overallStatus']}")
except Exception as e:
print(f"Error: {str(e)}")
# Continuous monitoring (uncomment to use)
# def alert_handler(result):
# if result['summary']['overallStatus'] != 'operational':
# send_alert(f"System status: {result['summary']['overallStatus']}")
#
# checker.monitor_services(
# urls=["https://api.example.com/health"],
# interval_seconds=300,
# callback=alert_handler
# )
Use Cases
1. Service Dependency Monitoring
Monitor third-party APIs and services that your application depends on:
// Monitor critical service dependencies
const criticalServices = [
'https://api.payment-processor.com/health',
'https://api.authentication-service.com/status',
'https://api.storage-provider.com/health'
];
async function checkDependencies() {
try {
const result = await checkApiStatus(criticalServices);
if (result.summary.overallStatus !== 'operational') {
// Alert the team
sendAlert(`Critical service issue: ${result.summary.overallStatus}`);
// Log detailed information
const downServices = result.endpoints
.filter(e => e.status !== 'up')
.map(e => `${e.url} (${e.status})`);
logIncident({
type: 'dependency_issue',
services: downServices,
details: result
});
}
} catch (error) {
console.error('Dependency check failed:', error);
}
}
2. Status Dashboard
Create a real-time status dashboard for your services:
function StatusDashboard() {
const [status, setStatus] = useState<StatusResponse | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchStatus() {
try {
setLoading(true);
const result = await checkApiStatus([
'https://api.example.com/v1/health',
'https://api.example.com/v2/health',
'https://auth.example.com/health',
'https://payments.example.com/health'
]);
setStatus(result);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch status');
} finally {
setLoading(false);
}
}
fetchStatus();
// Refresh every minute
const interval = setInterval(fetchStatus, 60000);
return () => clearInterval(interval);
}, []);
// Render dashboard with status information
return (
<div className="status-dashboard">
{loading && <LoadingSpinner />}
{error && <ErrorAlert message={error} />}
{status && (
<>
<StatusSummary
status={status.summary.overallStatus}
healthy={status.summary.healthy}
degraded={status.summary.degraded}
down={status.summary.down}
responseTime={status.summary.averageResponseTime}
/>
<EndpointList endpoints={status.endpoints} />
<UptimeChart endpoints={status.endpoints} />
</>
)}
</div>
);
}
3. Automated Incident Response
Implement automated incident response based on API status:
async function automatedIncidentResponse() {
try {
const result = await checkApiStatus();
// Check for outages
const downEndpoints = result.endpoints.filter(e => e.status === 'down');
if (downEndpoints.length > 0) {
// Create incident
const incident = await createIncident({
title: `Service outage detected: ${downEndpoints.length} endpoints down`,
severity: downEndpoints.length > 2 ? 'critical' : 'major',
services: downEndpoints.map(e => e.url)
});
// Attempt automated recovery
for (const endpoint of downEndpoints) {
try {
await triggerServiceRecovery(endpoint.url);
await updateIncident(incident.id, {
notes: `Automated recovery attempted for ${endpoint.url}`
});
} catch (recoveryError) {
await updateIncident(incident.id, {
notes: `Automated recovery failed for ${endpoint.url}: ${recoveryError.message}`
});
}
}
// Notify on-call team
await notifyOnCall({
message: `Incident #${incident.id}: ${incident.title}`,
severity: incident.severity
});
}
// Check for degraded performance
const degradedEndpoints = result.endpoints.filter(e => e.status === 'degraded');
if (degradedEndpoints.length > 0) {
// Log warning
console.warn(`Performance degradation detected: ${degradedEndpoints.length} endpoints affected`);
// Create performance alert
await createPerformanceAlert({
services: degradedEndpoints.map(e => e.url),
responseTimes: degradedEndpoints.map(e => e.responseTime)
});
}
} catch (error) {
console.error('Automated incident response failed:', error);
}
}
Best Practices
1. Monitoring Frequency
Choose an appropriate monitoring frequency based on your needs:
- Critical services: Every 1-5 minutes
- Important services: Every 5-15 minutes
- Non-critical services: Every 15-60 minutes
Remember that more frequent checks will consume more of your rate limit.
2. Health Endpoint Design
When designing health endpoints for your own APIs:
- Keep them lightweight and fast
- Include only essential checks
- Return appropriate status codes
- Include relevant metrics
- Secure them appropriately
Example health endpoint response:
{
"status": "healthy",
"version": "1.2.3",
"uptime": 1234567,
"dependencies": {
"database": "connected",
"cache": "connected",
"messageQueue": "connected"
},
"metrics": {
"requestsPerMinute": 123,
"errorRate": 0.01,
"averageResponseTime": 45
}
}
3. Alert Thresholds
Set appropriate alert thresholds to avoid alert fatigue:
- Response time: Alert on sustained increases rather than spikes
- Status changes: Confirm with multiple checks before alerting
- Uptime: Consider using sliding windows (e.g., 24h, 7d, 30d)
- Dependencies: Prioritize alerts based on impact
4. Historical Analysis
Use historical data for trend analysis:
- Track response time trends to identify gradual degradation
- Correlate incidents with deployments or changes
- Identify patterns in outages or degraded performance
- Set baselines for normal operation
Support
For support, please contact our team at [email protected].