API Reference

Complete REST API documentation for programmatic control and automation of NexoralDNS.

🔒 Premium Feature

API access is only available for Premium tier users. Upgrade to Premium to unlock API capabilities.

Getting Started

Base URL

All API requests are made to:

http://localhost:4000/api

Authentication

NexoralDNS uses JWT (JSON Web Tokens) for API authentication. Include your token in the Authorization header:

Authorization: Bearer YOUR_JWT_TOKEN

Getting Your API Token

  1. Log in to the NexoralDNS dashboard
  2. Navigate to Settings → API Keys
  3. Click "Generate New API Key"
  4. Copy and securely store your token

DNS Records

Create DNS Record

Create a new DNS record (A, AAAA, or CNAME).

POST /api/dns
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

{
  "domain": "myapp.local",
  "type": "A",
  "value": "192.168.1.100",
  "ttl": 300
}

List DNS Records

Retrieve all DNS records for your account.

GET /api/dns?userId=YOUR_USER_ID
Authorization: Bearer YOUR_JWT_TOKEN

Get Specific DNS Record

GET /api/dns/:recordId
Authorization: Bearer YOUR_JWT_TOKEN

Update DNS Record

PUT /api/dns/:recordId
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

{
  "value": "192.168.1.101",
  "ttl": 600
}

Delete DNS Record

DELETE /api/dns/:recordId
Authorization: Bearer YOUR_JWT_TOKEN

Rewrite Rules

Create Rewrite Rule

Redirect one domain to another (e.g., google.com → ankan.site).

POST /api/rewrites
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

{
  "sourceDomain": "google.com",
  "targetDomain": "ankan.site",
  "applyToClients": ["192.168.1.5"],  // Empty array for global
  "ttl": 300,
  "priority": 10
}

List Rewrites

GET /api/rewrites?userId=YOUR_USER_ID
Authorization: Bearer YOUR_JWT_TOKEN

Update Rewrite

PUT /api/rewrites/:id
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

{
  "enabled": false
}

Delete Rewrite

DELETE /api/rewrites/:id
Authorization: Bearer YOUR_JWT_TOKEN

Block Rules

Create Block Rule

Block a domain network-wide or for specific clients.

POST /api/blocks
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

{
  "domain": "ads.google.com",
  "blockType": "exact",  // "exact" or "wildcard"
  "applyToClients": [],  // Empty for all clients
  "reason": "Ads"
}

List Blocks

GET /api/blocks?userId=YOUR_USER_ID
Authorization: Bearer YOUR_JWT_TOKEN

Delete Block

DELETE /api/blocks/:id
Authorization: Bearer YOUR_JWT_TOKEN

Analytics

Query Logs

Retrieve DNS query logs with filtering options.

GET /api/analytics/queries?startDate=2024-01-01&endDate=2024-01-31&clientIP=192.168.1.5
Authorization: Bearer YOUR_JWT_TOKEN

Response Example:

{
  "totalQueries": 150000,
  "cachedQueries": 120000,
  "upstreamQueries": 25000,
  "blockedQueries": 5000,
  "averageResponseTime": 2.3,
  "topDomains": [
    { "domain": "google.com", "count": 5000 },
    { "domain": "facebook.com", "count": 3000 }
  ]
}

Performance Stats

Get real-time performance metrics.

GET /api/analytics/performance
Authorization: Bearer YOUR_JWT_TOKEN

Response Example:

{
  "cacheHitRate": 0.82,
  "averageQueryTime": 2.1,
  "queriesPerSecond": 150,
  "activeConnections": 45,
  "uptime": 2592000
}

User Plans

Get User Plan

Retrieve your current subscription plan details.

GET /api/plans/:userId
Authorization: Bearer YOUR_JWT_TOKEN

Response Example:

{
  "planType": "pro",
  "features": {
    "maxRewrites": -1,  // -1 = unlimited
    "maxBlocks": -1,
    "customDNS": true,
    "analyticsEnabled": true,
    "apiAccess": true
  },
  "status": "active",
  "expiresAt": "2025-12-31T23:59:59Z"
}

Rate Limits

EndpointRate LimitWindow
Authentication5 requests1 minute
DNS Records (Read)100 requests1 minute
DNS Records (Write)20 requests1 minute
Rewrites/Blocks30 requests1 minute
Analytics60 requests1 minute

Error Handling

All errors return a JSON response with an error code and message:

{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired API token"
  }
}

Common Error Codes

CodeStatusDescription
UNAUTHORIZED401Invalid or missing API token
FORBIDDEN403Insufficient permissions
NOT_FOUND404Resource not found
VALIDATION_ERROR400Invalid request parameters
RATE_LIMIT429Rate limit exceeded
SERVER_ERROR500Internal server error

Example: Python Client

import requests

class NexoralDNSClient:
    def __init__(self, api_token, base_url="http://localhost:4000/api"):
        self.api_token = api_token
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_token}",
            "Content-Type": "application/json"
        }

    def create_dns_record(self, domain, record_type, value, ttl=300):
        """Create a new DNS record"""
        url = f"{self.base_url}/dns"
        data = {
            "domain": domain,
            "type": record_type,
            "value": value,
            "ttl": ttl
        }
        response = requests.post(url, json=data, headers=self.headers)
        return response.json()

    def list_dns_records(self, user_id):
        """List all DNS records"""
        url = f"{self.base_url}/dns?userId={user_id}"
        response = requests.get(url, headers=self.headers)
        return response.json()

    def create_block_rule(self, domain, block_type="exact", clients=None):
        """Create a domain block rule"""
        url = f"{self.base_url}/blocks"
        data = {
            "domain": domain,
            "blockType": block_type,
            "applyToClients": clients or [],
            "reason": "Custom"
        }
        response = requests.post(url, json=data, headers=self.headers)
        return response.json()

# Usage
client = NexoralDNSClient("your_api_token_here")

# Create DNS record
result = client.create_dns_record("myapp.local", "A", "192.168.1.100")
print(result)

# Block a domain
result = client.create_block_rule("ads.example.com")
print(result)

Example: Node.js Client

const axios = require('axios');

class NexoralDNSClient {
  constructor(apiToken, baseUrl = 'http://localhost:4000/api') {
    this.apiToken = apiToken;
    this.baseUrl = baseUrl;
    this.headers = {
      'Authorization': `Bearer ${apiToken}`,
      'Content-Type': 'application/json'
    };
  }

  async createDnsRecord(domain, type, value, ttl = 300) {
    const url = `${this.baseUrl}/dns`;
    const data = { domain, type, value, ttl };
    const response = await axios.post(url, data, { headers: this.headers });
    return response.data;
  }

  async listDnsRecords(userId) {
    const url = `${this.baseUrl}/dns?userId=${userId}`;
    const response = await axios.get(url, { headers: this.headers });
    return response.data;
  }

  async createBlockRule(domain, blockType = 'exact', clients = []) {
    const url = `${this.baseUrl}/blocks`;
    const data = { domain, blockType, applyToClients: clients, reason: 'Custom' };
    const response = await axios.post(url, data, { headers: this.headers });
    return response.data;
  }
}

// Usage
const client = new NexoralDNSClient('your_api_token_here');

(async () => {
  // Create DNS record
  const record = await client.createDnsRecord('myapp.local', 'A', '192.168.1.100');
  console.log(record);

  // Block a domain
  const block = await client.createBlockRule('ads.example.com');
  console.log(block);
})();

Webhooks (Coming Soon)

Webhook support is planned for future releases. This will allow you to receive real-time notifications for events such as:

  • New DNS queries
  • Blocked domain attempts
  • Configuration changes
  • Service status changes

Support

For API-related questions or issues:

  • Premium users: Contact priority support via email
  • General questions: Open an issue on GitHub
  • Documentation updates: See Contributing Guide