Downloads API - Usage Examples
Downloads API - Usage Examples
Section titled “Downloads API - Usage Examples”Practical examples for integrating the Downloads API into your scripts, automation tools, and server management systems.
Overview
Section titled “Overview”This guide provides real-world examples for common use cases:
- Automatic plugin updates
- Update detection
- Integration with server management tools
- CI/CD pipelines
- Monitoring and alerting
Bash Scripts
Section titled “Bash Scripts”Automatic Plugin Update
Section titled “Automatic Plugin Update”Download the latest plugin for PaperMC servers:
#!/bin/bash# Download latest Statsly plugin for PaperMCPLUGIN_DIR="plugins"BACKUP_DIR="plugins/backup"
# Create backup directory if it doesn't existmkdir -p "$BACKUP_DIR"
# Backup current plugin if it existsif [ -f "$PLUGIN_DIR/Statsly.jar" ]; then cp "$PLUGIN_DIR/Statsly.jar" "$BACKUP_DIR/Statsly-$(date +%Y%m%d-%H%M%S).jar" echo "Backed up current plugin"fi
# Download latest versioncurl -L -o "$PLUGIN_DIR/Statsly.jar" \ "https://api.statsly.org/api/plugin-versions/download/latest/PaperMC"
if [ $? -eq 0 ]; then echo "Plugin downloaded successfully!" echo "Restart your server to apply the update."else echo "Failed to download plugin" exit 1fiUpdate Detection Script
Section titled “Update Detection Script”Check if a newer version is available:
#!/bin/bashCURRENT_VERSION="1.0.0"SERVER_SOFTWARE="PaperMC"
# Get latest version metadataLATEST_VERSION=$(curl -s "https://api.statsly.org/api/plugin-versions/latest/$SERVER_SOFTWARE" | grep -o '"pluginVersion":"[^"]*"' | cut -d'"' -f4)
if [ "$LATEST_VERSION" != "$CURRENT_VERSION" ]; then echo "New version available: $LATEST_VERSION (current: $CURRENT_VERSION)" echo "Run update script to download."else echo "Already up to date!"fiPowerShell Scripts
Section titled “PowerShell Scripts”Windows Plugin Update
Section titled “Windows Plugin Update”Download the latest plugin with error handling:
$url = "https://api.statsly.org/api/plugin-versions/download/latest/PaperMC"$output = "plugins\Statsly.jar"$backupDir = "plugins\backup"
# Create backup directoryif (-not (Test-Path $backupDir)) { New-Item -ItemType Directory -Path $backupDir | Out-Null}
# Backup current pluginif (Test-Path $output) { $backupFile = "$backupDir\Statsly-$(Get-Date -Format 'yyyyMMdd-HHmmss').jar" Copy-Item $output $backupFile Write-Host "Backed up current plugin"}
try { Invoke-WebRequest -Uri $url -OutFile $output -ErrorAction Stop Write-Host "Plugin downloaded successfully!" Write-Host "Restart your server to apply the update."} catch { Write-Host "Failed to download plugin: $_" -ForegroundColor Red exit 1}Python Scripts
Section titled “Python Scripts”Update Checker
Section titled “Update Checker”Check if a newer version is available:
import requestsimport json
SERVER_SOFTWARE = "PaperMC"CURRENT_VERSION = "1.0.0"
# Get latest version metadatatry: response = requests.get(f"https://api.statsly.org/api/plugin-versions/latest/{SERVER_SOFTWARE}") response.raise_for_status()
data = response.json() latest_version = data["version"]["pluginVersion"]
if latest_version != CURRENT_VERSION: print(f"New version available: {latest_version} (current: {CURRENT_VERSION})") print(f"Download URL: https://api.statsly.org/api/plugin-versions/download/latest/{SERVER_SOFTWARE}") else: print("Already up to date!")except requests.RequestException as e: print(f"Error checking for updates: {e}")Automated Update Script
Section titled “Automated Update Script”Automatically download and update the plugin:
import requestsimport shutilfrom datetime import datetimeimport os
SERVER_SOFTWARE = "PaperMC"JAVA_VERSION = "17"PLUGIN_DIR = "plugins"BACKUP_DIR = "plugins/backup"
# Create backup directoryos.makedirs(BACKUP_DIR, exist_ok=True)
# Backup current plugincurrent_plugin = os.path.join(PLUGIN_DIR, "Statsly.jar")if os.path.exists(current_plugin): backup_name = f"Statsly-{datetime.now().strftime('%Y%m%d-%H%M%S')}.jar" backup_path = os.path.join(BACKUP_DIR, backup_name) shutil.copy2(current_plugin, backup_path) print(f"Backed up current plugin to {backup_name}")
# Download latest versionurl = f"https://api.statsly.org/api/plugin-versions/download/latest/{SERVER_SOFTWARE}/{JAVA_VERSION}"
try: response = requests.get(url, stream=True) response.raise_for_status()
# Get filename from Content-Disposition header filename = response.headers.get('Content-Disposition', '').split('filename=')[1].strip('"') if not filename: filename = "Statsly.jar"
output_path = os.path.join(PLUGIN_DIR, filename)
with open(output_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
print(f"Plugin downloaded successfully: {filename}") print("Restart your server to apply the update.")except requests.RequestException as e: print(f"Failed to download plugin: {e}") exit(1)Node.js Scripts
Section titled “Node.js Scripts”Automated Updates
Section titled “Automated Updates”Automatically update the plugin:
const https = require('https');const fs = require('fs');const path = require('path');
const serverSoftware = 'PaperMC';const javaVersion = '17';const pluginDir = './plugins';const backupDir = './plugins/backup';
// Create directories[pluginDir, backupDir].forEach(dir => { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); }});
// Backup current pluginconst currentPlugin = path.join(pluginDir, 'Statsly.jar');if (fs.existsSync(currentPlugin)) { const backupName = `Statsly-${Date.now()}.jar`; const backupPath = path.join(backupDir, backupName); fs.copyFileSync(currentPlugin, backupPath); console.log(`Backed up current plugin to ${backupName}`);}
// Download latest versionconst url = `https://api.statsly.org/api/plugin-versions/download/latest/${serverSoftware}/${javaVersion}`;
https.get(url, (response) => { if (response.statusCode === 200) { const filename = response.headers['content-disposition'] ?.split('filename=')[1] ?.replace(/[""]/g, '') || 'Statsly.jar';
const filePath = path.join(pluginDir, filename); const fileStream = fs.createWriteStream(filePath);
response.pipe(fileStream);
fileStream.on('finish', () => { console.log('Plugin downloaded successfully!'); console.log('Restart your server to apply the update.'); }); } else { console.error(`Failed to download: HTTP ${response.statusCode}`); }}).on('error', (err) => { console.error('Error:', err.message);});CI/CD Integration
Section titled “CI/CD Integration”GitHub Actions
Section titled “GitHub Actions”Automatically update plugin in CI/CD pipeline:
name: Update Statsly Plugin
on: schedule: - cron: '0 0 * * *' # Daily at midnight workflow_dispatch:
jobs: update-plugin: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3
- name: Download Latest Plugin run: | curl -L -o plugins/Statsly.jar \ "https://api.statsly.org/api/plugin-versions/download/latest/PaperMC/17"
- name: Commit Changes run: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add plugins/Statsly.jar git commit -m "Update Statsly plugin" || exit 0 git pushServer Management Tools
Section titled “Server Management Tools”Pterodactyl Panel Integration
Section titled “Pterodactyl Panel Integration”Update plugin via Pterodactyl panel:
#!/bin/bash# Pterodactyl panel plugin update script
PLUGIN_DIR="/home/container/plugins"SERVER_SOFTWARE="PaperMC"
# Download latest versioncurl -L -o "$PLUGIN_DIR/Statsly.jar" \ "https://api.statsly.org/api/plugin-versions/download/latest/$SERVER_SOFTWARE"
echo "Plugin updated! Restart your server."Best Practices
Section titled “Best Practices”Error Handling
Section titled “Error Handling”Always implement proper error handling:
- Check HTTP status codes
- Handle network errors
- Verify file downloads
- Implement retry logic
Backup Strategy
Section titled “Backup Strategy”Before updating:
- Backup current plugin version
- Test updates on staging servers first
- Keep multiple backup versions
- Document update procedures
Monitoring
Section titled “Monitoring”Monitor your update processes:
- Log update attempts
- Track success/failure rates
- Alert on update failures
- Monitor plugin performance after updates
Always test plugin updates on a staging server before applying to production. Keep backups of working versions.
Next Steps
Section titled “Next Steps”- Review Error Handling & Best Practices
- Check Server Software Compatibility
- Explore API Overview