pgSentinelAPI Reference
Complete REST API documentation for pgSentinel monitoring platform. All endpoints, parameters, responses, and code examples.
Base URL
All API endpoints are prefixed with this base URL
API Endpoints
Complete reference for all available endpoints
System Health
/healthGet system health status
Response
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"services": {
"database": "connected",
"redis": "connected",
"prometheus": "active"
}
}/statusGet detailed system status
Response
{
"uptime": 3600,
"memory_usage": "45%",
"cpu_usage": "12%",
"active_connections": 15,
"total_queries": 1250
}pgbalancer Management
/pgbalancer/statusGet pgbalancer connection status
Response
{
"connected": true,
"version": "1.0.0",
"uptime": 3600,
"active_connections": 8,
"total_connections": 150
}/pgbalancer/reloadReload pgbalancer configuration
Response
{
"success": true,
"message": "Configuration reloaded successfully"
}/pgbalancer/poolsGet connection pool statistics
Response
{
"pools": [
{
"name": "postgres",
"active_connections": 5,
"idle_connections": 3,
"total_connections": 8,
"max_connections": 100
}
]
}Real-time Metrics
/metrics/liveGet 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
}
}/metrics/historyGet historical metrics
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| start_time | string | Yes | Start time (ISO 8601) |
| end_time | string | No | End time (ISO 8601) |
| interval | string | No | Data 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
/insights/dashboardGet 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
}
}/insights/queriesGet query performance insights
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| limit | integer | No | Number of queries to return (default: 20) |
| order_by | string | No | Sort 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
}
]
}/insights/tablesGet 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"
}
]
}/insights/indexesGet index usage statistics
Response
{
"indexes": [
{
"index_name": "idx_users_email",
"table_name": "users",
"usage_count": 1250,
"size_mb": 2.1,
"is_used": true
}
]
}/insights/recommendationsGet 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/liveReal-time metrics WebSocket connection
WebSocket Events
{
"timestamp": "2024-01-15T10:30:00Z",
"connections": 15,
"queries_per_second": 45.2
}{
"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
Bad Request
Invalid request parameters or malformed JSON
Unauthorized
Authentication required or invalid credentials
Forbidden
Insufficient permissions for the requested resource
Not Found
Requested resource does not exist
Unprocessable Entity
Request validation failed
Too Many Requests
Rate limit exceeded
Internal Server Error
Unexpected server error
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
Interactive API Explorer
Try the API directly in your browser
Swagger UI Documentation
Interactive API documentation with live testing capabilities
Open API Explorer