Overview

The Minerack API provides programmatic access to manage Minecraft servers, send console commands, monitor server performance, and handle file operations.

Base URL

https://minerack.net/api

API Capabilities

  • Server Control: Start, stop, restart servers
  • Real-time Monitoring: CPU, memory, disk usage
  • Console Access: Send commands and view logs
  • File Management: Upload, download, edit files
  • User Management: Account operations
  • Server Creation: Deploy new instances
  • WebSocket Support: Real-time updates
  • Audit Logging: Track all operations
Authentication Required

All API endpoints require authentication via session cookies or API tokens. Ensure your account has email verification completed.

Authentication

The Minerack API uses session-based authentication with CSRF protection. Users must be logged in with verified email addresses to access server management features.

Session Authentication

Most common for web applications:

// Login first to establish session
const loginResponse = await fetch('https://minerack.net/api/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        username: 'your_username',
        password: 'your_password'
    }),
    credentials: 'include' // Important for session cookies
});

// Then make authenticated requests
const response = await fetch('https://minerack.net/api/server-status', {
    method: 'GET',
    credentials: 'include' // Include session cookies
});

CSRF Protection

All POST, PUT, and DELETE requests require a valid CSRF token:

// Get CSRF token first
const csrfResponse = await fetch('/api/csrf-token.php');
const csrfData = await csrfResponse.json();

// Include in requests
const response = await fetch('/api/server-action', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        action: 'start',
        csrf_token: csrfData.token
    }),
    credentials: 'include'
});

Rate Limits

API endpoints are rate-limited to ensure fair usage and system stability.

Endpoint Type Limit Window Headers
Server Actions 10 requests 1 minute X-RateLimit-Remaining
Console Commands 60 requests 1 minute X-RateLimit-Reset
File Operations 30 requests 1 minute X-RateLimit-Limit
General API 120 requests 1 minute All rate limit headers
Premium users have higher rate limits and priority processing.

Error Handling

The API uses conventional HTTP status codes and returns consistent error responses.

HTTP Status Codes

Code Description Common Causes
200 Success Request completed successfully
400 Bad Request Invalid parameters or request format
401 Unauthorized Authentication required
403 Forbidden Email not verified or insufficient permissions
404 Not Found Server or resource doesn't exist
500 Internal Server Error Server-side error occurred

Error Response Format

{
  "success": false,
  "message": "Email verification required to perform server actions",
  "error_code": "EMAIL_NOT_VERIFIED",
  "timestamp": 1701234567,
  "request_id": "req_abc123def456"
}

Server Status

Get real-time information about your Minecraft server including status, resource usage, and player count.

GET /api/server-status

Retrieves comprehensive server status information including current state, resource usage, and player statistics.

Request Example
const response = await fetch('https://minerack.net/api/server-status', {
    method: 'GET',
    credentials: 'include'
});

const data = await response.json();
Response Example
{
  "success": true,
  "data": {
    "status": "running",
    "name": "My Minecraft Server",
    "ip": "play.myserver.minerack.net",
    "port": 25565,
    "version": "1.21.1",
    "players": {
      "current": 3,
      "max": 20
    },
    "resources": {
      "memory": {
        "used": 1572864000,
        "total": 2147483648,
        "percentage": 73.2
      },
      "cpu": 15.7,
      "disk": {
        "used": 1073741824,
        "total": 5368709120,
        "percentage": 20.0
      },
      "network": {
        "rx": 1024576,
        "tx": 2048192
      }
    },
    "uptime": 7200,
    "tps": 19.8,
    "last_updated": "2024-01-15T10:30:00Z"
  }
}
Response Parameters
Parameter Type Description
status string Server state: running, offline, starting, stopping
resources.memory.used integer Memory usage in bytes
resources.cpu float CPU usage percentage
players.current integer Number of online players
uptime integer Server uptime in seconds
tps float Server ticks per second (performance metric)

Server Actions

Control your Minecraft server with power management actions.

POST /api/server-action

Send power management commands to your server. Requires email verification.

Request Parameters
Parameter Type Required Description
action string Yes Action to perform: start, stop, restart, kill
csrf_token string Yes CSRF protection token from /api/csrf-token
Request Example
const response = await fetch('https://minerack.net/api/server-action', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        action: 'start',
        csrf_token: 'your_csrf_token_here'
    }),
    credentials: 'include'
});

const data = await response.json();
Response Example
{
  "success": true,
  "message": "Server start command sent successfully",
  "action_id": "action_123456",
  "timestamp": "2024-01-15T10:30:00Z"
}
Try It

Console Logs

Retrieve server console output and logs for monitoring and debugging.

GET /api/get-server-log

Fetch recent console logs from your Minecraft server.

Query Parameters
Parameter Type Default Description
lines integer 100 Number of lines to retrieve (1-1000)
Request Example
const response = await fetch('https://minerack.net/api/get-server-log?lines=50', {
    method: 'GET',
    credentials: 'include'
});

const data = await response.json();
Response Example
{
  "success": true,
  "log": "[10:30:15] [Server thread/INFO]: Starting minecraft server version 1.21.1\n[10:30:16] [Server thread/INFO]: Loading properties\n[10:30:16] [Server thread/INFO]: Default game type: SURVIVAL\n[10:30:17] [Server thread/INFO]: Generating keypair\n[10:30:18] [Server thread/INFO]: Starting Minecraft server on *:25565",
  "source": "pterodactyl",
  "lines_requested": 50,
  "timestamp": 1705312200
}

Send Commands

Execute commands on your Minecraft server through the console.

POST /api/send-command

Send commands to your server console. Commands are executed with server operator privileges.

Request Parameters
Parameter Type Required Description
command string Yes Minecraft command to execute (without leading /)
csrf_token string Yes CSRF protection token
Common Commands
  • list - Show online players
  • say <message> - Broadcast message
  • tp <player1> <player2> - Teleport player
  • gamemode creative <player> - Change gamemode
  • give <player> <item> <amount> - Give items
  • time set day - Set time to day
  • weather clear - Clear weather
  • save-all - Save world data
Request Example
const response = await fetch('https://minerack.net/api/send-command', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        command: 'list',
        csrf_token: 'your_csrf_token_here'
    }),
    credentials: 'include'
});

const data = await response.json();
Try It

WebSocket Console

Real-time console connection for live server monitoring and command execution.

WSS /api/console-websocket

Establish a WebSocket connection for real-time console access. First, get WebSocket credentials:

Get WebSocket Auth
// Step 1: Get WebSocket authentication
const authResponse = await fetch('https://minerack.net/api/console-websocket-auth', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        csrf_token: 'your_csrf_token_here'
    }),
    credentials: 'include'
});

const authData = await authResponse.json();
// Returns: { success: true, token: "ws_token", socket: "wss://...", url: "wss://..." }
WebSocket Connection
// Step 2: Connect to WebSocket
const ws = new WebSocket(authData.url);

ws.onopen = () => {
    console.log('Console WebSocket connected');
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Console output:', data.message);
};

ws.onerror = (error) => {
    console.error('WebSocket error:', error);
};

ws.onclose = () => {
    console.log('Console WebSocket disconnected');
};
Send Commands via WebSocket
// Send command through WebSocket
const sendCommand = (command) => {
    if (ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
            type: 'command',
            command: command
        }));
    }
};

// Usage
sendCommand('list');
sendCommand('say Hello from WebSocket!');

List Files

Browse your server's file system and directory structure.

GET /api/files

List files and directories in your server's file system.

Query Parameters
Parameter Type Default Description
folder string / Directory path to list
Request Example
const response = await fetch('https://minerack.net/api/files?folder=/plugins', {
    method: 'GET',
    credentials: 'include'
});

const data = await response.json();
Response Example
{
  "success": true,
  "files": [
    {
      "name": "server.properties",
      "path": "/server.properties",
      "type": "file",
      "size": 1024,
      "modified": "2024-01-15T10:30:00Z",
      "is_directory": false,
      "permissions": "rw-r--r--"
    },
    {
      "name": "plugins",
      "path": "/plugins",
      "type": "directory",
      "size": 0,
      "modified": "2024-01-14T15:20:00Z",
      "is_directory": true,
      "permissions": "rwxr-xr-x"
    },
    {
      "name": "world",
      "path": "/world",
      "type": "directory",
      "size": 0,
      "modified": "2024-01-15T09:15:00Z",
      "is_directory": true,
      "permissions": "rwxr-xr-x"
    }
  ],
  "current_path": "/",
  "parent_path": null
}

File Operations

Upload, download, edit, and manage server files.

GET /api/download-file

Download a file from your server.

Query Parameters
Parameter Type Required Description
file string Yes Full path to the file
Request Example
// Download file
window.open('https://minerack.net/api/download-file?file=/server.properties', '_blank');

// Or with fetch for programmatic access
const response = await fetch('https://minerack.net/api/download-file?file=/server.properties', {
    credentials: 'include'
});

const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'server.properties';
a.click();
POST /api/upload-files

Upload files to your server. Maximum file size: 10MB each.

Request Example
const formData = new FormData();
formData.append('files[]', fileInput.files[0]);
formData.append('folder', '/plugins');
formData.append('csrf_token', 'your_csrf_token_here');

const response = await fetch('https://minerack.net/api/upload-files', {
    method: 'POST',
    body: formData,
    credentials: 'include'
});

const data = await response.json();
DELETE /api/delete-file

Delete a file from your server. This action cannot be undone.

Request Example
const response = await fetch('https://minerack.net/api/delete-file', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        file: '/plugins/old-plugin.jar',
        csrf_token: 'your_csrf_token_here'
    }),
    credentials: 'include'
});

const data = await response.json();

SDKs & Libraries

Official and community-maintained libraries for popular programming languages.

JavaScript/Node.js

Official JavaScript SDK for browser and Node.js applications.

npm install minerack-api
View Documentation
Python

Python library with async/await support and type hints.

pip install minerack-python
View Documentation
Java

Java library for desktop applications and Minecraft plugins.

<dependency>
  <groupId>net.minerack</groupId>
  <artifactId>minerack-java</artifactId>
</dependency>
View Documentation
Go

Community-maintained Go client library.

go get github.com/minerack/go-client
Community Project

Examples

Practical examples and use cases for integrating with the Minerack API.

Basic Server Management Bot

A simple Discord bot that can control your Minecraft server.

const Discord = require('discord.js');
const fetch = require('node-fetch');

const client = new Discord.Client();
const MINERACK_API = 'https://minerack.net/api';

// Login and get session cookie
async function loginToMinerack(username, password) {
    const response = await fetch(`${MINERACK_API}/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
    });
    
    // Store session cookie for subsequent requests
    return response.headers.get('set-cookie');
}

// Get server status
async function getServerStatus(sessionCookie) {
    const response = await fetch(`${MINERACK_API}/server-status`, {
        headers: { 'Cookie': sessionCookie }
    });
    return await response.json();
}

// Discord command handler
client.on('message', async (message) => {
    if (message.content === '!server status') {
        try {
            const status = await getServerStatus(sessionCookie);
            const embed = new Discord.MessageEmbed()
                .setTitle('Server Status')
                .addField('Status', status.data.status, true)
                .addField('Players', `${status.data.players.current}/${status.data.players.max}`, true)
                .addField('CPU Usage', `${status.data.resources.cpu}%`, true)
                .setColor(status.data.status === 'running' ? 'GREEN' : 'RED');
            
            message.channel.send(embed);
        } catch (error) {
            message.channel.send('Error fetching server status: ' + error.message);
        }
    }
});

client.login('YOUR_DISCORD_BOT_TOKEN');

Automated Server Maintenance

A Python script that performs regular server maintenance tasks.

import asyncio
import aiohttp
import logging
from datetime import datetime, time

class MinerackMaintenanceBot:
    def __init__(self, username, password):
        self.api_base = 'https://minerack.net/api'
        self.session = None
        self.username = username
        self.password = password
    
    async def login(self):
        """Login and maintain session"""
        async with aiohttp.ClientSession() as session:
            async with session.post(f'{self.api_base}/login', 
                                  json={'username': self.username, 'password': self.password}) as resp:
                if resp.status == 200:
                    self.session = session
                    logging.info("Successfully logged in to Minerack")
                else:
                    raise Exception("Failed to login")
    
    async def get_server_status(self):
        """Get current server status"""
        async with self.session.get(f'{self.api_base}/server-status') as resp:
            return await resp.json()
    
    async def send_command(self, command, csrf_token):
        """Send command to server"""
        async with self.session.post(f'{self.api_base}/send-command',
                                   json={'command': command, 'csrf_token': csrf_token}) as resp:
            return await resp.json()
    
    async def daily_maintenance(self):
        """Perform daily maintenance at 3 AM"""
        while True:
            now = datetime.now().time()
            maintenance_time = time(3, 0)  # 3:00 AM
            
            if now >= maintenance_time:
                try:
                    # Get CSRF token
                    async with self.session.get(f'{self.api_base}/csrf-token') as resp:
                        csrf_data = await resp.json()
                        csrf_token = csrf_data['token']
                    
                    # Warn players
                    await self.send_command('say Server maintenance in 5 minutes!', csrf_token)
                    await asyncio.sleep(300)  # Wait 5 minutes
                    
                    # Save world
                    await self.send_command('save-all', csrf_token)
                    await asyncio.sleep(30)
                    
                    # Restart server
                    async with self.session.post(f'{self.api_base}/server-action',
                                               json={'action': 'restart', 'csrf_token': csrf_token}) as resp:
                        result = await resp.json()
                        logging.info(f"Restart result: {result}")
                    
                    # Wait until next day
                    await asyncio.sleep(86400)  # 24 hours
                    
                except Exception as e:
                    logging.error(f"Maintenance failed: {e}")
                    await asyncio.sleep(3600)  # Retry in 1 hour
            
            await asyncio.sleep(60)  # Check every minute

# Usage
async def main():
    bot = MinerackMaintenanceBot('your_username', 'your_password')
    await bot.login()
    await bot.daily_maintenance()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

Web Dashboard Integration

Frontend JavaScript for integrating server controls into your website.

class MinerackDashboard {
    constructor() {
        this.apiBase = 'https://minerack.net/api';
        this.csrfToken = null;
        this.isAuthenticated = false;
        this.init();
    }
    
    async init() {
        await this.getCsrfToken();
        await this.checkAuthStatus();
        this.setupEventListeners();
        this.startPolling();
    }
    
    async getCsrfToken() {
        try {
            const response = await fetch(`${this.apiBase}/csrf-token`, {
                credentials: 'include'
            });
            const data = await response.json();
            this.csrfToken = data.token;
        } catch (error) {
            console.error('Failed to get CSRF token:', error);
        }
    }
    
    async checkAuthStatus() {
        try {
            const response = await fetch(`${this.apiBase}/server-status`, {
                credentials: 'include'
            });
            this.isAuthenticated = response.ok;
            
            if (!this.isAuthenticated) {
                this.showLoginPrompt();
            }
        } catch (error) {
            console.error('Auth check failed:', error);
            this.isAuthenticated = false;
        }
    }
    
    async getServerStatus() {
        if (!this.isAuthenticated) return null;
        
        try {
            const response = await fetch(`${this.apiBase}/server-status`, {
                credentials: 'include'
            });
            
            if (response.ok) {
                return await response.json();
            }
        } catch (error) {
            console.error('Failed to get server status:', error);
        }
        return null;
    }
    
    async controlServer(action) {
        if (!this.isAuthenticated || !this.csrfToken) return;
        
        const validActions = ['start', 'stop', 'restart', 'kill'];
        if (!validActions.includes(action)) {
            console.error('Invalid server action:', action);
            return;
        }
        
        try {
            const response = await fetch(`${this.apiBase}/server-action`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    csrf_token: this.csrfToken
                }),
                credentials: 'include'
            });
            
            const result = await response.json();
            this.showNotification(
                result.success ? `Server ${action} successful` : `Server ${action} failed: ${result.message}`,
                result.success ? 'success' : 'error'
            );
            
            // Refresh status after action
            setTimeout(() => this.updateDisplay(), 2000);
            
        } catch (error) {
            console.error('Server action failed:', error);
            this.showNotification(`Server ${action} failed`, 'error');
        }
    }
    
    async sendCommand(command) {
        if (!this.isAuthenticated || !this.csrfToken) return;
        
        try {
            const response = await fetch(`${this.apiBase}/send-command`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    command: command.trim(),
                    csrf_token: this.csrfToken
                }),
                credentials: 'include'
            });
            
            const result = await response.json();
            this.addToConsole(`> ${command}`);
            
            if (!result.success) {
                this.addToConsole(`Error: ${result.message}`);
            }
            
        } catch (error) {
            console.error('Command send failed:', error);
            this.addToConsole(`Error: Failed to send command`);
        }
    }
    
    async updateDisplay() {
        const status = await this.getServerStatus();
        if (!status || !status.success) return;
        
        const data = status.data;
        
        // Update status indicators
        this.updateElement('server-status', data.status);
        this.updateElement('player-count', `${data.players.current}/${data.players.max}`);
        this.updateElement('cpu-usage', `${Math.round(data.resources.cpu)}%`);
        this.updateElement('memory-usage', 
            `${Math.round(data.resources.memory.percentage)}%`);
        
        // Update status styling
        const statusElement = document.getElementById('server-status');
        if (statusElement) {
            statusElement.className = `status ${data.status}`;
        }
        
        // Enable/disable controls based on status
        this.updateControls(data.status);
    }
    
    updateControls(status) {
        const startBtn = document.getElementById('start-btn');
        const stopBtn = document.getElementById('stop-btn');
        const restartBtn = document.getElementById('restart-btn');
        
        if (startBtn) startBtn.disabled = (status === 'running' || status === 'starting');
        if (stopBtn) stopBtn.disabled = (status === 'offline' || status === 'stopping');
        if (restartBtn) restartBtn.disabled = (status === 'offline');
    }
    
    updateElement(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }
    
    addToConsole(message) {
        const console = document.getElementById('console-output');
        if (console) {
            const timestamp = new Date().toLocaleTimeString();
            console.innerHTML += `
[${timestamp}] ${message}
`; console.scrollTop = console.scrollHeight; } } showNotification(message, type = 'info') { // Create notification element const notification = document.createElement('div'); notification.className = `notification ${type}`; notification.textContent = message; // Add to page document.body.appendChild(notification); // Auto-remove after 5 seconds setTimeout(() => { notification.remove(); }, 5000); } showLoginPrompt() { this.showNotification('Please log in to access server controls', 'warning'); // Redirect to login page or show login modal } setupEventListeners() { // Server control buttons document.getElementById('start-btn')?.addEventListener('click', () => this.controlServer('start')); document.getElementById('stop-btn')?.addEventListener('click', () => this.controlServer('stop')); document.getElementById('restart-btn')?.addEventListener('click', () => this.controlServer('restart')); // Console command input const commandInput = document.getElementById('command-input'); if (commandInput) { commandInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { const command = commandInput.value.trim(); if (command) { this.sendCommand(command); commandInput.value = ''; } } }); } } startPolling() { // Update display every 30 seconds setInterval(() => { if (this.isAuthenticated) { this.updateDisplay(); } }, 30000); // Initial update this.updateDisplay(); } } // Initialize dashboard when page loads document.addEventListener('DOMContentLoaded', () => { window.minerackDashboard = new MinerackDashboard(); }); // HTML structure example: /*

Server Status: Loading...

Players: 0/0

CPU: 0%

Memory: 0%

*/
More Examples

Looking for more integration examples? Check out our GitHub repository:

  • Discord Bot Templates - Ready-to-use Discord bots
  • Webhook Integrations - Connect with external services
  • Monitoring Scripts - Automated server monitoring
  • Custom Dashboards - Full-featured web interfaces

Ready to Get Started?

Join thousands of developers using the Minerack API to build amazing Minecraft experiences.

All API endpoints are protected with enterprise-grade security and monitoring.