SDKs & Libraries

Code Examples

Example code for integrating with the AIO Radar API in various languages.

cURL Examples

Validate API Key

Bash
curl -X POST "https://aioradar.vercel.app/api/sites/validate" \
  -H "Authorization: Bearer aio_sk_your_api_key" \
  -H "Content-Type: application/json"

Sync Site Inventory

Bash
curl -X POST "https://aioradar.vercel.app/api/sites/sync" \
  -H "Authorization: Bearer aio_sk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "pages": [
      {
        "id": "123",
        "title": "Example Page",
        "url": "https://example.com/page",
        "type": "page",
        "content_excerpt": "Page content preview...",
        "word_count": 500
      }
    ]
  }'

Get LLMs.txt

Bash
curl -X GET "https://aioradar.vercel.app/api/sites/{site_id}/llms-txt" \
  -H "Authorization: Bearer aio_sk_your_api_key"

Get Schema Templates

Bash
curl -X GET "https://aioradar.vercel.app/api/sites/{site_id}/schema?format=script" \
  -H "Authorization: Bearer aio_sk_your_api_key"

PHP Examples

API Client Class

PHP
<?php
class AIORadarClient {
    private string $apiKey;
    private string $baseUrl = 'https://aioradar.vercel.app/api';

    public function __construct(string $apiKey) {
        $this->apiKey = $apiKey;
    }

    private function request(string $method, string $endpoint, array $data = []): array {
        $url = $this->baseUrl . $endpoint;

        $args = [
            'method' => $method,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'timeout' => 30,
        ];

        if (!empty($data) && in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $args['body'] = json_encode($data);
        }

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            throw new Exception($response->get_error_message());
        }

        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }

    public function validate(): array {
        return $this->request('POST', '/sites/validate');
    }

    public function sync(array $pages): array {
        return $this->request('POST', '/sites/sync', ['pages' => $pages]);
    }

    public function getLlmsTxt(string $siteId, bool $forceRegenerate = false): array {
        $endpoint = "/sites/{$siteId}/llms-txt";
        if ($forceRegenerate) {
            $endpoint .= '?force_regenerate=true';
        }
        return $this->request('GET', $endpoint);
    }

    public function getSummaries(string $siteId): array {
        return $this->request('GET', "/sites/{$siteId}/summaries");
    }

    public function getSchema(string $siteId, string $format = 'json'): array {
        return $this->request('GET', "/sites/{$siteId}/schema?format={$format}");
    }
}

// Usage
$client = new AIORadarClient('aio_sk_your_api_key');

// Validate connection
$result = $client->validate();
if (isset($result['data'])) {
    echo "Connected to site: " . $result['data']['domain'];
}

// Get LLMs.txt content
$llmsTxt = $client->getLlmsTxt($siteId);
echo $llmsTxt['data']['content'];

JavaScript/TypeScript Examples

Fetch API

TypeScript
const API_KEY = 'aio_sk_your_api_key';
const BASE_URL = 'https://aioradar.vercel.app/api';

async function aioRadarRequest(
  method: string,
  endpoint: string,
  data?: object
): Promise<any> {
  const url = `${BASE_URL}${endpoint}`;

  const options: RequestInit = {
    method,
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
  };

  if (data && ['POST', 'PUT', 'PATCH'].includes(method)) {
    options.body = JSON.stringify(data);
  }

  const response = await fetch(url, options);

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error?.message || 'API request failed');
  }

  return response.json();
}

// Validate API key
async function validateApiKey(): Promise<{ site_id: string; domain: string }> {
  const result = await aioRadarRequest('POST', '/sites/validate');
  return result.data;
}

// Sync inventory
async function syncInventory(pages: Page[]): Promise<SyncResult> {
  const result = await aioRadarRequest('POST', '/sites/sync', { pages });
  return result.data;
}

// Get LLMs.txt
async function getLlmsTxt(siteId: string, forceRegenerate = false): Promise<string> {
  const endpoint = forceRegenerate
    ? `/sites/${siteId}/llms-txt?force_regenerate=true`
    : `/sites/${siteId}/llms-txt`;
  const result = await aioRadarRequest('GET', endpoint);
  return result.data.content;
}

// Usage
const site = await validateApiKey();
console.log(`Connected to ${site.domain}`);

const llmsTxt = await getLlmsTxt(site.site_id);
console.log(llmsTxt);

Node.js with Axios

TypeScript
import axios, { AxiosInstance } from 'axios';

class AIORadarClient {
  private client: AxiosInstance;

  constructor(apiKey: string) {
    this.client = axios.create({
      baseURL: 'https://aioradar.vercel.app/api',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });
  }

  async validate() {
    const { data } = await this.client.post('/sites/validate');
    return data.data;
  }

  async sync(siteId: string, pages: any[]) {
    const { data } = await this.client.post('/sites/sync', { pages });
    return data.data;
  }

  async getLlmsTxt(siteId: string, forceRegenerate = false) {
    const params = forceRegenerate ? { force_regenerate: true } : {};
    const { data } = await this.client.get(`/sites/${siteId}/llms-txt`, { params });
    return data.data;
  }

  async getSummaries(siteId: string) {
    const { data } = await this.client.get(`/sites/${siteId}/summaries`);
    return data.data;
  }

  async submitImages(siteId: string, images: any[]) {
    const { data } = await this.client.post(`/sites/${siteId}/images`, { images });
    return data.data;
  }
}

// Usage
const client = new AIORadarClient(process.env.AIO_RADAR_API_KEY!);

const site = await client.validate();
console.log(`Site: ${site.name} (${site.domain})`);

const { content, cached, page_count } = await client.getLlmsTxt(site.site_id);
console.log(`LLMs.txt: ${page_count} pages, cached: ${cached}`);

Python Example

Python
import requests
from typing import Optional, Dict, Any, List

class AIORadarClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://aioradar.vercel.app/api"

    def _request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Dict:
        url = f"{self.base_url}{endpoint}"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        response = requests.request(method, url, headers=headers, json=data)
        response.raise_for_status()
        return response.json()

    def validate(self) -> Dict:
        return self._request("POST", "/sites/validate")["data"]

    def sync(self, pages: List[Dict]) -> Dict:
        return self._request("POST", "/sites/sync", {"pages": pages})["data"]

    def get_llms_txt(self, site_id: str, force_regenerate: bool = False) -> Dict:
        endpoint = f"/sites/{site_id}/llms-txt"
        if force_regenerate:
            endpoint += "?force_regenerate=true"
        return self._request("GET", endpoint)["data"]

    def get_summaries(self, site_id: str) -> Dict:
        return self._request("GET", f"/sites/{site_id}/summaries")["data"]

    def get_schema(self, site_id: str, format: str = "json") -> Dict:
        return self._request("GET", f"/sites/{site_id}/schema?format={format}")["data"]

# Usage
client = AIORadarClient("aio_sk_your_api_key")

# Validate connection
site = client.validate()
print(f"Connected to {site['domain']}")

# Get LLMs.txt
llms_txt = client.get_llms_txt(site["site_id"])
print(f"Pages: {llms_txt['page_count']}")
print(llms_txt["content"])

Error Handling

All examples should implement proper error handling:

TypeScript
try {
  const site = await validateApiKey();
} catch (error) {
  if (error.response?.status === 401) {
    console.error('Invalid API key');
  } else if (error.response?.status === 429) {
    console.error('Rate limit exceeded, retry after:', error.response.headers['retry-after']);
  } else {
    console.error('API error:', error.message);
  }
}