pgSentinelAPI Reference

Complete REST API documentation for pgSentinel monitoring platform. All endpoints, parameters, responses, and code examples.

25+ endpoints
REST + WebSocket
Production ready

Base URL

http://localhost:8000/api/v1

All API endpoints are prefixed with this base URL

API Endpoints

Complete reference for all available endpoints

System Health

GET/health

Get system health status

Response

{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00Z",
  "services": {
    "database": "connected",
    "redis": "connected",
    "prometheus": "active"
  }
}
GET/status

Get detailed system status

Response

{
  "uptime": 3600,
  "memory_usage": "45%",
  "cpu_usage": "12%",
  "active_connections": 15,
  "total_queries": 1250
}

pgbalancer Management

GET/pgbalancer/status

Get pgbalancer connection status

Response

{
  "connected": true,
  "version": "1.0.0",
  "uptime": 3600,
  "active_connections": 8,
  "total_connections": 150
}
POST/pgbalancer/reload

Reload pgbalancer configuration

Response

{
  "success": true,
  "message": "Configuration reloaded successfully"
}
GET/pgbalancer/pools

Get connection pool statistics

Response

{
  "pools": [
    {
      "name": "postgres",
      "active_connections": 5,
      "idle_connections": 3,
      "total_connections": 8,
      "max_connections": 100
    }
  ]
}

Real-time Metrics

GET/metrics/live

Get real-time metrics

Response

{
  "timestamp": "2024-01-15T10:30:00Z",
  "connections": {
    "active": 15,
    "idle": 8,
    "total": 23
  },
  "performance": {
    "queries_per_second": 45.2,
    "avg_response_time": 12.5,
    "cache_hit_ratio": 98.5
  }
}
GET/metrics/history

Get historical metrics

Parameters

NameTypeRequiredDescription
start_timestringYesStart time (ISO 8601)
end_timestringNoEnd time (ISO 8601)
intervalstringNoData interval (1m, 5m, 1h)

Response

{
  "data": [
    {
      "timestamp": "2024-01-15T10:00:00Z",
      "connections": 15,
      "queries_per_second": 42.1,
      "avg_response_time": 11.8
    }
  ]
}

pg_stat_insights

GET/insights/dashboard

Get complete insights dashboard data

Response

{
  "query_stats": {
    "total_queries": 1250,
    "slow_queries": 23,
    "avg_execution_time": 12.5
  },
  "table_stats": {
    "total_tables": 45,
    "bloated_tables": 3,
    "total_size_mb": 1024
  },
  "cache_stats": {
    "buffer_hit_ratio": 98.5,
    "index_hit_ratio": 99.2
  }
}
GET/insights/queries

Get query performance insights

Parameters

NameTypeRequiredDescription
limitintegerNoNumber of queries to return (default: 20)
order_bystringNoSort by: calls, total_time, avg_time

Response

{
  "queries": [
    {
      "query": "SELECT * FROM users WHERE id = $1",
      "calls": 150,
      "total_time": 1250.5,
      "avg_time": 8.34,
      "rows": 1
    }
  ]
}
GET/insights/tables

Get table statistics and bloat analysis

Response

{
  "tables": [
    {
      "table_name": "users",
      "size_mb": 45.2,
      "bloat_percentage": 5.2,
      "last_vacuum": "2024-01-15T08:00:00Z",
      "last_analyze": "2024-01-15T08:00:00Z"
    }
  ]
}
GET/insights/indexes

Get index usage statistics

Response

{
  "indexes": [
    {
      "index_name": "idx_users_email",
      "table_name": "users",
      "usage_count": 1250,
      "size_mb": 2.1,
      "is_used": true
    }
  ]
}
GET/insights/recommendations

Get performance optimization recommendations

Response

{
  "recommendations": [
    {
      "type": "missing_index",
      "priority": "high",
      "description": "Add index on users.email for faster lookups",
      "impact": "Reduce query time by 80%"
    }
  ]
}

WebSocket Events

WS/ws/live

Real-time metrics WebSocket connection

WebSocket Events

metrics_updateReal-time metrics data
{
  "timestamp": "2024-01-15T10:30:00Z",
  "connections": 15,
  "queries_per_second": 45.2
}
alertSystem alert notification
{
  "level": "warning",
  "message": "High connection count detected",
  "timestamp": "2024-01-15T10:30:00Z"
}

Code Examples

Ready-to-use client implementations

Python Client

import requests
import json
from datetime import datetime, timedelta

class PgSentinelClient:
    def __init__(self, base_url="http://localhost:8000/api/v1"):
        self.base_url = base_url
        self.session = requests.Session()
    
    def get_health(self):
        """Get system health status"""
        response = self.session.get(f"{self.base_url}/health")
        return response.json()
    
    def get_metrics(self, start_time=None, end_time=None):
        """Get historical metrics"""
        params = {}
        if start_time:
            params['start_time'] = start_time.isoformat()
        if end_time:
            params['end_time'] = end_time.isoformat()
        
        response = self.session.get(f"{self.base_url}/metrics/history", params=params)
        return response.json()
    
    def get_query_insights(self, limit=20):
        """Get query performance insights"""
        response = self.session.get(f"{self.base_url}/insights/queries", 
                                  params={'limit': limit})
        return response.json()

# Usage
client = PgSentinelClient()
health = client.get_health()
print(f"System status: {health['status']}")

# Get metrics for last hour
end_time = datetime.now()
start_time = end_time - timedelta(hours=1)
metrics = client.get_metrics(start_time, end_time)
print(f"Data points: {len(metrics['data'])}")

JavaScript/Node.js Client

class PgSentinelClient {
    constructor(baseUrl = 'http://localhost:8000/api/v1') {
        this.baseUrl = baseUrl;
    }
    
    async request(endpoint, options = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return response.json();
    }
    
    async getHealth() {
        return this.request('/health');
    }
    
    async getMetrics(startTime, endTime) {
        const params = new URLSearchParams();
        if (startTime) params.append('start_time', startTime.toISOString());
        if (endTime) params.append('end_time', endTime.toISOString());
        
        return this.request(`/metrics/history?${params}`);
    }
    
    async getQueryInsights(limit = 20) {
        return this.request(`/insights/queries?limit=${limit}`);
    }
    
    // WebSocket connection for real-time data
    connectWebSocket(onMessage) {
        const ws = new WebSocket('ws://localhost:8000/ws/live');
        
        ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            onMessage(data);
        };
        
        return ws;
    }
}

// Usage
const client = new PgSentinelClient();

// Get system health
client.getHealth().then(health => {
    console.log('System status:', health.status);
});

// Connect to real-time updates
const ws = client.connectWebSocket((data) => {
    console.log('Real-time update:', data);
});

cURL Examples

# Get system health
curl -X GET "http://localhost:8000/api/v1/health" \
  -H "Content-Type: application/json"

# Get real-time metrics
curl -X GET "http://localhost:8000/api/v1/metrics/live" \
  -H "Content-Type: application/json"

# Get query insights
curl -X GET "http://localhost:8000/api/v1/insights/queries?limit=10" \
  -H "Content-Type: application/json"

# Get historical metrics
curl -X GET "http://localhost:8000/api/v1/metrics/history?start_time=2024-01-15T09:00:00Z&interval=5m" \
  -H "Content-Type: application/json"

# Reload pgbalancer configuration
curl -X POST "http://localhost:8000/api/v1/pgbalancer/reload" \
  -H "Content-Type: application/json"

# Get table statistics
curl -X GET "http://localhost:8000/api/v1/insights/tables" \
  -H "Content-Type: application/json"

HTTP Status Codes

Common error responses and their meanings

400

Bad Request

Invalid request parameters or malformed JSON

401

Unauthorized

Authentication required or invalid credentials

403

Forbidden

Insufficient permissions for the requested resource

404

Not Found

Requested resource does not exist

422

Unprocessable Entity

Request validation failed

429

Too Many Requests

Rate limit exceeded

500

Internal Server Error

Unexpected server error

503

Service Unavailable

Service temporarily unavailable

Rate Limiting

API usage limits and best practices

Standard Limit

1000 requests

per hour per IP

Burst Limit

100 requests

per minute per IP

WebSocket

No limit

real-time connections

Rate Limit Headers

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642248000

Interactive API Explorer

Try the API directly in your browser

Swagger UI Documentation

Interactive API documentation with live testing capabilities

Open API Explorer