Skip to content

Server API

Server health, information, and statistics endpoints.

Health Check

Simple health check endpoint to verify API availability.

Endpoint: GET /api/health

Authentication: None required

Success Response (200):

json
{
  "success": true,
  "status": "healthy",
  "timestamp": "2024-01-20T15:30:00Z",
  "uptime": 86400
}

Example:

bash
curl http://localhost:8080/api/health

Get Server Information

Retrieve detailed server information.

Endpoint: GET /api/server/info

Authentication: Required (JWT)

Success Response (200):

json
{
  "success": true,
  "server": {
    "name": "My Minecraft Server",
    "version": "1.21.3",
    "platform": "Paper",
    "onlinePlayers": 15,
    "maxPlayers": 20,
    "tps": 20.0,
    "worldInfo": {
      "name": "world",
      "seed": "-1234567890",
      "difficulty": "NORMAL",
      "gameMode": "SURVIVAL",
      "time": 12000,
      "isDay": true
    },
    "plugins": [
      {
        "name": "CraftServerManager",
        "version": "1.0.0",
        "enabled": true
      }
    ]
  }
}

Example:

bash
curl http://localhost:8080/api/server/info \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Get Server Statistics

View real-time server performance metrics (admin only).

Endpoint: GET /api/server/stats

Authentication: Required (JWT, Admin)

Success Response (200):

json
{
  "success": true,
  "current": {
    "timestamp": "2024-01-20T15:30:00Z",
    "cpuUsage": 45.5,
    "memoryUsed": 4096,
    "memoryTotal": 8192,
    "memoryPercent": 50.0,
    "diskUsed": 102400,
    "diskTotal": 512000,
    "diskPercent": 20.0,
    "onlinePlayers": 15,
    "tps": 19.8
  },
  "averages": {
    "avgCpu": 42.3,
    "avgMemoryPercent": 48.5,
    "avgDiskPercent": 19.8,
    "avgTps": 19.9,
    "avgPlayers": 12.5
  },
  "history": [
    {
      "timestamp": "2024-01-20T15:29:00Z",
      "cpuUsage": 43.2,
      "memoryPercent": 49.0,
      "tps": 19.9,
      "onlinePlayers": 14
    }
  ]
}

Example:

bash
curl http://localhost:8080/api/server/stats \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"

Notes:

  • Statistics collected every minute
  • History includes last 24 hours
  • Averages calculated from history
  • Memory values in MB
  • Disk values in MB

Code Examples

TypeScript

typescript
interface ServerInfo {
  name: string;
  version: string;
  platform: string;
  onlinePlayers: number;
  maxPlayers: number;
  tps: number;
}

interface ServerStats {
  cpuUsage: number;
  memoryPercent: number;
  diskPercent: number;
  tps: number;
  onlinePlayers: number;
}

class ServerAPI {
  constructor(private baseUrl: string, private token?: string) {}
  
  async healthCheck() {
    const response = await fetch(`${this.baseUrl}/api/health`);
    return await response.json();
  }
  
  async getServerInfo(): Promise<ServerInfo> {
    const response = await fetch(`${this.baseUrl}/api/server/info`, {
      headers: { 'Authorization': `Bearer ${this.token}` }
    });
    const data = await response.json();
    return data.server;
  }
  
  async getServerStats(): Promise<ServerStats> {
    const response = await fetch(`${this.baseUrl}/api/server/stats`, {
      headers: { 'Authorization': `Bearer ${this.token}` }
    });
    const data = await response.json();
    return data.current;
  }
  
  async monitorHealth(callback: (healthy: boolean) => void) {
    setInterval(async () => {
      try {
        const response = await this.healthCheck();
        callback(response.success);
      } catch (error) {
        callback(false);
      }
    }, 30000); // Check every 30 seconds
  }
}

Python

python
class ServerAPI:
    def __init__(self, base_url, token=None):
        self.base_url = base_url
        self.token = token
    
    def health_check(self):
        response = requests.get(f'{self.base_url}/api/health')
        return response.json()
    
    def get_server_info(self):
        headers = {'Authorization': f'Bearer {self.token}'} if self.token else {}
        response = requests.get(
            f'{self.base_url}/api/server/info',
            headers=headers
        )
        return response.json()
    
    def get_server_stats(self):
        response = requests.get(
            f'{self.base_url}/api/server/stats',
            headers={'Authorization': f'Bearer {self.token}'}
        )
        return response.json()
    
    def monitor_health(self, interval=30):
        """Monitor server health at specified interval (seconds)"""
        import time
        while True:
            try:
                result = self.health_check()
                print(f"Server health: {'OK' if result['success'] else 'FAIL'}")
            except Exception as e:
                print(f"Health check failed: {e}")
            time.sleep(interval)

Shell Script

bash
#!/bin/bash
# Simple server health monitor

BASE_URL="http://localhost:8080"

check_health() {
    response=$(curl -s "$BASE_URL/api/health")
    status=$(echo "$response" | jq -r '.status')
    
    if [ "$status" = "healthy" ]; then
        echo "✓ Server is healthy"
        return 0
    else
        echo "✗ Server is unhealthy"
        return 1
    fi
}

# Monitor every 60 seconds
while true; do
    check_health
    sleep 60
done

TPS (Ticks Per Second)

TPS indicates server performance:

  • 20.0 - Perfect (target)
  • 19.5-19.9 - Good
  • 18.0-19.4 - Fair
  • <18.0 - Poor (lag)

Monitoring Best Practices

Health Checks

  • Use /api/health for uptime monitoring
  • No authentication required
  • Lightweight endpoint
  • Check every 30-60 seconds

Performance Monitoring

  • Use /api/server/stats for detailed metrics
  • Admin authentication required
  • Poll every 1-5 minutes
  • Store historical data for trends

Alerting Thresholds

Consider alerting when:

  • TPS < 18.0 for 5+ minutes
  • Memory > 90% for 10+ minutes
  • CPU > 80% for 10+ minutes
  • Disk > 95%

Integration Examples

Prometheus

yaml
scrape_configs:
  - job_name: 'minecraft_server'
    static_configs:
      - targets: ['localhost:8080']
    metrics_path: '/api/server/stats'
    bearer_token: 'YOUR_ADMIN_TOKEN'

Grafana Dashboard

Create visualizations for:

  • TPS over time
  • Player count trends
  • Memory/CPU usage
  • Disk space utilization

Discord Webhook

typescript
async function alertDiscord(stats: ServerStats) {
  if (stats.tps < 18.0) {
    await fetch('YOUR_DISCORD_WEBHOOK', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        content: '⚠️ Server TPS is low!',
        embeds: [{
          title: 'Performance Alert',
          fields: [
            { name: 'TPS', value: stats.tps.toString(), inline: true },
            { name: 'CPU', value: `${stats.cpuUsage}%`, inline: true },
            { name: 'Memory', value: `${stats.memoryPercent}%`, inline: true }
          ],
          color: 0xFF0000
        }]
      })
    });
  }
}

Notes

  • Health check endpoint has no rate limit
  • Server info refreshed in real-time
  • Statistics history retained for 24 hours
  • Admin privileges required for detailed stats
  • TPS calculated from server tick loop
  • Memory values include JVM and native memory

Released under the MIT License.