API 0 0

Last updated on Aug 04, 2025 00:34 in Uptime Cloud Monitor

API

What is the API?

The API (Application Programming Interface) provides programmatic access to all monitoring system functionality, allowing you to integrate monitoring capabilities into your applications, automate tasks, build custom dashboards, and create workflows that interact with your monitoring data. The API follows REST principles and returns data in JSON format.

Why Use the API?

Automation and Integration

  • Workflow automation: Automate monitor creation, updates, and management
  • CI/CD integration: Integrate monitoring into deployment pipelines
  • Custom applications: Build applications that interact with monitoring data
  • Third-party integrations: Connect with other tools and platforms

Data Access and Analysis

  • Historical data: Access historical monitoring and incident data
  • Custom reporting: Build custom reports and analytics
  • Data export: Export monitoring data for external analysis
  • Real-time monitoring: Build real-time dashboards and alerts

Scalability and Efficiency

  • Bulk operations: Perform operations on multiple resources efficiently
  • Programmatic control: Manage large numbers of monitors programmatically
  • Event-driven actions: Trigger actions based on monitoring events
  • Custom workflows: Create workflows tailored to your organization

Getting Started with the API

API Authentication

API Key Generation

  1. Log into your monitoring account
  2. Navigate to Account SettingsAPI
  3. Click "Generate API Key"
  4. Copy and securely store your API key
  5. Use the API key in the Authorization header

Authentication Format

Authorization: Bearer YOUR_API_KEY

API Base URL

All API requests are made to:

https://yourdomain.com/api/

Request Format

  • Content-Type: application/json
  • Accept: application/json
  • HTTP Methods: GET, POST, PUT, DELETE
  • Response Format: JSON

API Endpoints Overview

Monitors

List Monitors

  • Endpoint: GET /api/monitors
  • Purpose: Retrieve list of all monitors
  • Parameters: page, per_page, search, project_id
  • Response: Array of monitor objects with status and configuration

Get Monitor Details

  • Endpoint: GET /api/monitors/{monitor_id}
  • Purpose: Get detailed information about a specific monitor
  • Response: Complete monitor object with status, logs, and statistics

Create Monitor

  • Endpoint: POST /api/monitors
  • Purpose: Create a new monitor
  • Required fields: name, type, target
  • Optional fields: project_id, check_interval, notifications

Update Monitor

  • Endpoint: PUT /api/monitors/{monitor_id}
  • Purpose: Update existing monitor configuration
  • Fields: Any monitor configuration fields

Delete Monitor

  • Endpoint: DELETE /api/monitors/{monitor_id}
  • Purpose: Remove a monitor permanently
  • Response: Confirmation of deletion

Heartbeats

List Heartbeats

  • Endpoint: GET /api/heartbeats
  • Purpose: Retrieve list of heartbeat monitors
  • Parameters: page, per_page, search, project_id

Create Heartbeat

  • Endpoint: POST /api/heartbeats
  • Purpose: Create a new heartbeat monitor
  • Required fields: name, run_interval

Ping Heartbeat

  • Endpoint: GET /api/heartbeats/{heartbeat_code}/ping
  • Purpose: Send heartbeat ping (this is typically called by your scheduled tasks)
  • Response: Confirmation of heartbeat received

Status Pages

List Status Pages

  • Endpoint: GET /api/status-pages
  • Purpose: Retrieve list of status pages
  • Response: Array of status page configurations

Get Status Page

  • Endpoint: GET /api/status-pages/{status_page_id}
  • Purpose: Get status page details and current status
  • Response: Status page configuration and current service status

Update Status Page

  • Endpoint: PUT /api/status-pages/{status_page_id}
  • Purpose: Update status page configuration or status
  • Fields: Status page settings, service status overrides

Incidents

List Incidents

  • Endpoint: GET /api/incidents
  • Purpose: Retrieve incident history
  • Parameters: page, per_page, status, start_date, end_date

Get Incident

  • Endpoint: GET /api/incidents/{incident_id}
  • Purpose: Get detailed incident information
  • Response: Complete incident timeline and updates

Create Incident

  • Endpoint: POST /api/incidents
  • Purpose: Create manual incident report
  • Required fields: title, description, affected_services

Update Incident

  • Endpoint: PUT /api/incidents/{incident_id}
  • Purpose: Add updates to incident or change status
  • Fields: status, update_message, resolution_notes

Projects

List Projects

  • Endpoint: GET /api/projects
  • Purpose: Retrieve all projects
  • Response: Array of project objects with basic information

Create Project

  • Endpoint: POST /api/projects
  • Purpose: Create new project for organizing monitors
  • Required fields: name
  • Optional fields: description, color

Common API Usage Examples

Monitor Management

Create a Website Monitor

curl -X POST "https://yourdomain.com/api/monitors" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Company Website",
    "type": "website",
    "target": "https://example.com",
    "check_interval": 300,
    "notifications": [1, 2, 3]
  }'

Get Monitor Status

curl -X GET "https://yourdomain.com/api/monitors/123" \
  -H "Authorization: Bearer YOUR_API_KEY"

Update Monitor Configuration

curl -X PUT "https://yourdomain.com/api/monitors/123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "check_interval": 600,
    "is_enabled": true
  }'

Heartbeat Integration

Send Heartbeat Ping

curl -X GET "https://yourdomain.com/api/heartbeats/abc123def456/ping" \
  -H "Authorization: Bearer YOUR_API_KEY"

Create Heartbeat Monitor

curl -X POST "https://yourdomain.com/api/heartbeats" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Daily Backup Job",
    "run_interval": 86400,
    "grace_period": 3600
  }'

Status Page Management

Update Status Page Incident

curl -X PUT "https://yourdomain.com/api/status-pages/456" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "incident_status": "investigating",
    "incident_message": "We are investigating reports of slow response times."
  }'

Data Retrieval

Get Monitor Logs

curl -X GET "https://yourdomain.com/api/monitors/123/logs?start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_API_KEY"

Export Incident Data

curl -X GET "https://yourdomain.com/api/incidents?format=csv&start_date=2024-01-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

SDK and Libraries

Official SDKs

Python SDK

pip install monitoring-api-sdk
  
from monitoring_api import Client

client = Client(api_key='YOUR_API_KEY')
monitors = client.monitors.list()
print(f"Found {len(monitors)} monitors")

Node.js SDK

npm install monitoring-api-sdk
  
const MonitoringAPI = require('monitoring-api-sdk');
const client = new MonitoringAPI('YOUR_API_KEY');

async function getMonitors() {
  const monitors = await client.monitors.list();
  console.log(`Found ${monitors.length} monitors`);
}

PHP SDK

composer require monitoring/api-sdk
  
use Monitoring\API\Client;

$client = new Client('YOUR_API_KEY');
$monitors = $client->monitors()->list();
echo "Found " . count($monitors) . " monitors";

Community Libraries

  • Go: Third-party Go client library
  • Ruby: Community Ruby gem
  • Java: Maven package for Java applications
  • .NET: NuGet package for .NET applications

Integration Patterns

CI/CD Pipeline Integration

Deployment Monitoring

# GitHub Actions example
- name: Create deployment monitor
  run: |
    curl -X POST "https://yourdomain.com/api/monitors" \
      -H "Authorization: Bearer ${{ secrets.MONITORING_API_KEY }}" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Staging Environment - Build ${{ github.sha }}",
        "type": "website",
        "target": "https://staging-${{ github.sha }}.example.com"
      }'

Post-Deployment Verification

# Wait for deployment to stabilize, then verify monitoring
sleep 60
monitor_status=$(curl -s -H "Authorization: Bearer $API_KEY" \
  "https://yourdomain.com/api/monitors/123" | jq -r '.is_ok')
  
if [ "$monitor_status" = "true" ]; then
  echo "Deployment successful - monitoring shows all systems operational"
else
  echo "Deployment may have issues - monitoring shows problems"
  exit 1
fi

Infrastructure as Code

Terraform Integration

resource "monitoring_monitor" "web_server" {
  name     = "Web Server ${var.environment}"
  type     = "website"
  target   = "https://${var.domain}"
  interval = 300
  
  notifications = [
    monitoring_notification_handler.email.id,
    monitoring_notification_handler.slack.id
  ]
}

Ansible Playbook

- name: Create application monitor
  uri:
    url: "https://yourdomain.com/api/monitors"
    method: POST
    headers:
      Authorization: "Bearer {{ monitoring_api_key }}"
      Content-Type: "application/json"
    body_format: json
    body:
      name: "{{ app_name }} - {{ environment }}"
      type: "website"
      target: "{{ app_url }}"
      check_interval: 300

Custom Dashboard Development

React Component Example

import React, { useEffect, useState } from 'react';

function MonitorStatus() {
  const [monitors, setMonitors] = useState([]);
  
  useEffect(() => {
    fetch('/api/monitors', {
      headers: {
        'Authorization': `Bearer ${process.env.REACT_APP_API_KEY}`
      }
    })
    .then(response => response.json())
    .then(data => setMonitors(data));
  }, []);
  
  return (
    <div>
      {monitors.map(monitor => (
        <div key={monitor.id} className={monitor.is_ok ? 'online' : 'offline'}>
          {monitor.name}: {monitor.is_ok ? 'Online' : 'Offline'}
        </div>
      ))}
    </div>
  );
}

Webhooks and Event Handling

Webhook Configuration

  • Setup: Configure webhook endpoints in notification handlers
  • Events: Receive real-time notifications for monitor events
  • Payload: Structured JSON data about monitoring events
  • Security: Webhook signature verification for security

Webhook Payload Example

{
    "event": "monitor.down",
    "timestamp": "2024-01-15T10:30:00Z",
    "monitor": {
      "id": 123,
      "name": "Main Website",
      "type": "website",
      "target": "https://example.com",
      "status": "down"
    },
    "incident": {
      "id": 456,
      "started_at": "2024-01-15T10:29:45Z",
      "error_message": "Connection timeout"
    }
  }

Event Processing

// Express.js webhook handler
app.post('/webhooks/monitoring', (req, res) => {
  const event = req.body;
  
  switch(event.event) {
    case 'monitor.down':
      handleMonitorDown(event.monitor, event.incident);
      break;
    case 'monitor.up':
      handleMonitorUp(event.monitor);
      break;
    case 'incident.resolved':
      handleIncidentResolved(event.incident);
      break;
  }
  
  res.status(200).send('OK');
});

API Rate Limits and Best Practices

Rate Limiting

  • Request limits: Maximum requests per minute/hour
  • Burst limits: Short-term burst capacity
  • Rate limit headers: Information about current usage
  • Backoff strategies: Exponential backoff for rate limited requests

Best Practices

Authentication Security

  • Secure storage: Store API keys securely, never in code repositories
  • Environment variables: Use environment variables for API keys
  • Key rotation: Regularly rotate API keys
  • Scope limitation: Use API keys with minimal necessary permissions

Error Handling

  • Status code checking: Always check HTTP status codes
  • Retry logic: Implement retry logic for transient failures
  • Graceful degradation: Handle API unavailability gracefully
  • Error logging: Log API errors for troubleshooting

Performance Optimization

  • Pagination: Use pagination for large datasets
  • Filtering: Use API filters to reduce data transfer
  • Caching: Cache API responses when appropriate
  • Batch operations: Use bulk operations where available

API Response Formats

Success Responses

{
    "status": "success",
    "data": {
      "monitor": {
        "id": 123,
        "name": "Website Monitor",
        "type": "website",
        "target": "https://example.com",
        "is_ok": true,
        "uptime": 99.95,
        "response_time": 245
      }
    },
    "meta": {
      "timestamp": "2024-01-15T10:30:00Z"
    }
  }

Error Responses

{
    "status": "error",
    "error": {
      "code": "VALIDATION_ERROR",
      "message": "Invalid monitor configuration",
      "details": {
        "target": ["Target URL is required"],
        "type": ["Monitor type must be one of: website, ping, port"]
      }
    },
    "meta": {
      "timestamp": "2024-01-15T10:30:00Z"
    }
  }

Pagination

{
    "status": "success",
    "data": {
      "monitors": [...],
      "pagination": {
        "current_page": 1,
        "per_page": 25,
        "total_pages": 4,
        "total_items": 87,
        "has_next": true,
        "has_previous": false
      }
    }
  }

Advanced API Features

Bulk Operations

Bulk Monitor Updates

curl -X PUT "https://yourdomain.com/api/monitors/bulk" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "monitor_ids": [123, 124, 125],
    "updates": {
      "check_interval": 600,
      "is_enabled": true
    }
  }'

Real-time Subscriptions

WebSocket Connection

const socket = new WebSocket('wss://yourdomain.com/api/ws');
socket.onopen = function() {
  socket.send(JSON.stringify({
    'auth': 'YOUR_API_KEY',
    'subscribe': ['monitor.status', 'incident.updates']
  }));
};

socket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  console.log('Real-time update:', data);
};

Advanced Filtering

Complex Query Parameters

GET /api/monitors?project_id=123&status=down&created_after=2024-01-01&sort=uptime:desc

Troubleshooting API Issues

Common Problems

Authentication Errors

  • 401 Unauthorized: Check API key validity and format
  • 403 Forbidden: Verify API key permissions for the requested resource
  • API key format: Ensure proper Bearer token format in Authorization header

Request Errors

  • 400 Bad Request: Check request JSON syntax and required fields
  • 404 Not Found: Verify endpoint URL and resource ID
  • 429 Too Many Requests: Implement rate limiting and retry logic

Data Issues

  • Missing data: Check API response structure and field names
  • Inconsistent data: Verify timezone settings and data filtering
  • Stale data: Check data refresh rates and caching policies

Tips for Effective API Usage

  • Read the documentation: Familiarize yourself with complete API documentation
  • Use official SDKs: Leverage official SDKs when available for easier integration
  • Implement proper error handling: Always handle API errors gracefully
  • Respect rate limits: Implement appropriate rate limiting in your applications
  • Cache responses: Cache API responses to reduce unnecessary requests
  • Use webhooks: Prefer webhooks over polling for real-time updates
  • Monitor API usage: Track your API usage to optimize performance
  • Test thoroughly: Test API integrations in development environments first
  • Keep keys secure: Never expose API keys in client-side code or repositories
  • Stay updated: Keep track of API updates and new features
  • Use pagination: Always use pagination for large datasets
  • Implement retries: Add retry logic for handling temporary failures
  • Log API interactions: Maintain logs for troubleshooting and monitoring
  • Validate data: Validate API responses before using the data
  • Plan for scale: Design API integrations to handle growth in data and usage
** The time is base on America/New_York timezone