Skip to content

API Usage Guide

Learn how to interact with the VPN Exit Controller API for programmatic control of VPN nodes and proxy services.

API Overview

The VPN Exit Controller provides a comprehensive REST API for:

  • Node Management: Start, stop, and monitor VPN nodes
  • Load Balancing: Configure strategies and get optimal nodes
  • Metrics & Monitoring: Access performance data and health status
  • Speed Testing: Run bandwidth and latency tests
  • Proxy Management: Configure proxy routing

Authentication

All API endpoints require authentication using HTTP Basic Auth:

curl -u admin:your_password https://api.vpn.yourdomain.com/api/endpoint

Authentication Methods

# Using curl
curl -u admin:password https://api.vpn.yourdomain.com/api/nodes

# Using base64 encoding
curl -H "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
     https://api.vpn.yourdomain.com/api/nodes
# Set credentials
export VPN_API_USER=admin
export VPN_API_PASS=your_password

# Use in scripts
curl -u $VPN_API_USER:$VPN_API_PASS \
     https://api.vpn.yourdomain.com/api/nodes
# Python
import requests
from requests.auth import HTTPBasicAuth

response = requests.get(
    'https://api.vpn.yourdomain.com/api/nodes',
    auth=HTTPBasicAuth('admin', 'password')
)

Common API Operations

1. Node Management

List All Nodes

curl -u admin:password https://api.vpn.yourdomain.com/api/nodes

Response:

{
  "nodes": [
    {
      "id": "vpn-us",
      "country": "us",
      "city": "New York",
      "status": "running",
      "health": "healthy",
      "connections": 15,
      "uptime": 86400
    }
  ]
}

Start a New Node

curl -X POST -u admin:password \
  -H "Content-Type: application/json" \
  -d '{"country": "uk", "city": "London"}' \
  https://api.vpn.yourdomain.com/api/nodes/start

Stop a Node

curl -X DELETE -u admin:password \
  https://api.vpn.yourdomain.com/api/nodes/vpn-uk

2. Load Balancing

Get Best Node for Country

curl -u admin:password \
  https://api.vpn.yourdomain.com/api/load-balancer/best-node/us

# Get best UK node
curl -u admin:password \
  https://api.vpn.yourdomain.com/api/load-balancer/best-node/uk

Response:

{
  "node": {
    "id": "vpn-us-2",
    "score": 95.5,
    "latency": 12,
    "connections": 5
  },
  "strategy": "health_score"
}

Change Load Balancing Strategy

curl -X POST -u admin:password \
  -H "Content-Type: application/json" \
  -d '{"strategy": "weighted_latency"}' \
  https://api.vpn.yourdomain.com/api/load-balancer/strategy

3. Metrics and Monitoring

Get System Metrics

curl -u admin:password \
  https://api.vpn.yourdomain.com/api/metrics

Health Check

curl -u admin:password \
  https://api.vpn.yourdomain.com/api/health

4. Speed Testing

Run Speed Test

curl -X POST -u admin:password \
  https://api.vpn.yourdomain.com/api/speed-test/vpn-us

# Run speed test for UK node
curl -X POST -u admin:password \
  https://api.vpn.yourdomain.com/api/speed-test/vpn-uk

Response:

{
  "node_id": "vpn-us",
  "download_speed": 485.6,
  "upload_speed": 234.8,
  "latency": 15.2,
  "timestamp": "2024-01-15T10:30:00Z"
}

SDK Examples

Python SDK

import requests
from typing import Dict, List, Optional

class VPNController:
    def __init__(self, base_url: str, username: str, password: str):
        self.base_url = base_url.rstrip('/')
        self.auth = (username, password)

    def list_nodes(self) -> List[Dict]:
        """List all VPN nodes"""
        response = requests.get(
            f"{self.base_url}/api/nodes",
            auth=self.auth
        )
        response.raise_for_status()
        return response.json()['nodes']

    def start_node(self, country: str, city: Optional[str] = None) -> Dict:
        """Start a new VPN node"""
        data = {"country": country}
        if city:
            data["city"] = city

        response = requests.post(
            f"{self.base_url}/api/nodes/start",
            json=data,
            auth=self.auth
        )
        response.raise_for_status()
        return response.json()

    def get_best_node(self, country: str) -> Dict:
        """Get the best node for a country"""
        response = requests.get(
            f"{self.base_url}/api/load-balancer/best-node/{country}",
            auth=self.auth
        )
        response.raise_for_status()
        return response.json()

# Usage
vpn = VPNController('https://api.vpn.yourdomain.com', 'admin', 'password')
nodes = vpn.list_nodes()
best_us = vpn.get_best_node('us')
best_uk = vpn.get_best_node('uk')

JavaScript/Node.js SDK

const axios = require('axios');

class VPNController {
    constructor(baseUrl, username, password) {
        this.client = axios.create({
            baseURL: baseUrl,
            auth: {
                username: username,
                password: password
            }
        });
    }

    async listNodes() {
        const response = await this.client.get('/api/nodes');
        return response.data.nodes;
    }

    async startNode(country, city = null) {
        const data = { country };
        if (city) data.city = city;

        const response = await this.client.post('/api/nodes/start', data);
        return response.data;
    }

    async getBestNode(country) {
        const response = await this.client.get(`/api/load-balancer/best-node/${country}`);
        return response.data;
    }
}

// Usage
const vpn = new VPNController('https://api.vpn.yourdomain.com', 'admin', 'password');
const nodes = await vpn.listNodes();
const bestUS = await vpn.getBestNode('us');
const bestUK = await vpn.getBestNode('uk');

Error Handling

The API returns standard HTTP status codes:

Status Code Description
200 Success
201 Created
400 Bad Request
401 Unauthorized
404 Not Found
409 Conflict (e.g., node already exists)
500 Internal Server Error

Error Response Format

{
  "error": "Node not found",
  "detail": "No node with ID 'vpn-xyz' exists",
  "timestamp": "2024-01-15T10:30:00Z"
}

Error Handling Examples

try:
    response = vpn.start_node('us')
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 409:
        print("Node already exists")
    elif e.response.status_code == 401:
        print("Invalid credentials")
    else:
        print(f"Error: {e.response.json()['error']}")
try {
    const response = await vpn.startNode('us');
} catch (error) {
    if (error.response) {
        if (error.response.status === 409) {
            console.log("Node already exists");
        } else if (error.response.status === 401) {
            console.log("Invalid credentials");
        } else {
            console.log(`Error: ${error.response.data.error}`);
        }
    }
}

Rate Limiting

API requests are rate limited to prevent abuse:

  • Default Limit: 100 requests per minute per IP
  • Burst Limit: 20 requests per second
  • Headers: Rate limit info in response headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642257600

Webhooks

Configure webhooks for real-time events:

curl -X POST -u admin:password \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-webhook.com/vpn-events",
    "events": ["node.started", "node.stopped", "node.unhealthy"]
  }' \
  https://api.vpn.yourdomain.com/api/webhooks

Webhook Events

  • node.started - VPN node successfully started
  • node.stopped - VPN node stopped
  • node.unhealthy - Node health check failed
  • failover.triggered - Automatic failover occurred
  • speed.test.completed - Speed test finished

Best Practices

API Usage Tips

  1. Cache responses when appropriate to reduce API calls
  2. Use bulk operations when available
  3. Implement exponential backoff for retries
  4. Monitor rate limits to avoid throttling
  5. Use webhooks for real-time updates instead of polling

Security Best Practices

  • Never hardcode credentials in your code
  • Use environment variables or secure vaults
  • Rotate API credentials regularly
  • Implement request signing for sensitive operations
  • Use HTTPS for all API communications

API Playground

Try the API directly from your browser:

 

Next Steps


Need Help?

Check our API Reference for detailed endpoint documentation or contact support for assistance.