> ## Documentation Index
> Fetch the complete documentation index at: https://docs.llmtag.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Developer API

> Complete API reference for developers integrating with the LLMTAG WordPress plugin

## API Overview

The LLMTAG plugin provides a comprehensive REST API for developers to integrate AI protection functionality into custom applications, external systems, and third-party tools.

<Card title="REST API v1" icon="code" horizontal>
  **Full CRUD Operations** • **Webhook Support** • **Rate Limiting** • **Authentication** • **Comprehensive Documentation**
</Card>

## Authentication

### API Key Authentication

All API requests require authentication using API keys:

<Steps>
  <Step title="Generate API Key">
    Go to **LLMTAG > Settings > API** and click **Generate New Key**
  </Step>

  <Step title="Configure Permissions">
    Set the permissions for your API key (read, write, admin)
  </Step>

  <Step title="Set Rate Limits">
    Configure rate limits for your API key
  </Step>

  <Step title="Test Authentication">
    Use the API key in your requests to verify authentication
  </Step>
</Steps>

### Request Headers

Include the API key in your request headers:

```http theme={null}
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

### Rate Limiting

API requests are rate-limited to prevent abuse:

<Columns cols={2}>
  <Card title="Free Tier" icon="gift">
    **Requests:** 1,000 per hour
    **Burst:** 100 requests per minute
    **Use for:** Development, testing
  </Card>

  <Card title="Pro Tier" icon="star">
    **Requests:** 10,000 per hour
    **Burst:** 500 requests per minute
    **Use for:** Production applications
  </Card>
</Columns>

## Core Endpoints

### Settings Management

#### Get Current Settings

```http theme={null}
GET /wp-json/llmtag/v1/settings
```

<ResponseExample>
  ```json Success Response theme={null}
  {
    "protection_mode": "standard",
    "ai_training_data": "disallow",
    "ai_use": ["search_indexing", "generative_synthesis"],
    "blocked_agents": [
      "GPTBot",
      "ChatGPT-User",
      "Claude-Web"
    ],
    "path_protection": {
      "/premium/": {
        "ai_training_data": "disallow",
        "ai_use": ["search_indexing"]
      }
    },
    "analytics_enabled": true,
    "last_updated": "2024-01-15T10:30:00Z"
  }
  ```
</ResponseExample>

#### Update Settings

```http theme={null}
PUT /wp-json/llmtag/v1/settings
```

<RequestExample>
  ```json Request Body theme={null}
  {
    "protection_mode": "advanced",
    "ai_training_data": "disallow",
    "ai_use": ["search_indexing", "generative_synthesis", "research"],
    "blocked_agents": [
      "GPTBot",
      "ChatGPT-User",
      "Claude-Web",
      "PerplexityBot"
    ],
    "path_protection": {
      "/premium/": {
        "ai_training_data": "disallow",
        "ai_use": ["search_indexing"]
      },
      "/research/": {
        "ai_training_data": "allow",
        "ai_use": ["search_indexing", "generative_synthesis", "research"]
      }
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "message": "Settings updated successfully",
    "data": {
      "protection_mode": "advanced",
      "ai_training_data": "disallow",
      "ai_use": ["search_indexing", "generative_synthesis", "research"],
      "blocked_agents": [
        "GPTBot",
        "ChatGPT-User",
        "Claude-Web",
        "PerplexityBot"
      ],
      "path_protection": {
        "/premium/": {
          "ai_training_data": "disallow",
          "ai_use": ["search_indexing"]
        },
        "/research/": {
          "ai_training_data": "allow",
          "ai_use": ["search_indexing", "generative_synthesis", "research"]
        }
      },
      "last_updated": "2024-01-15T10:35:00Z"
    }
  }
  ```
</ResponseExample>

### Analytics Data

#### Get Analytics Summary

```http theme={null}
GET /wp-json/llmtag/v1/analytics/summary
```

<ParamField query="period" type="string" default="24h">
  Time period for analytics data. Options: 1h, 24h, 7d, 30d
</ParamField>

<ResponseExample>
  ```json Success Response theme={null}
  {
    "period": "24h",
    "total_requests": 3642,
    "blocked_requests": 3642,
    "block_success_rate": 100,
    "top_blocked_agents": [
      {
        "agent": "GPTBot",
        "requests": 1247,
        "percentage": 34.2
      },
      {
        "agent": "ChatGPT-User",
        "requests": 892,
        "percentage": 24.5
      }
    ],
    "geographic_distribution": [
      {
        "country": "United States",
        "requests": 2156,
        "percentage": 59.2
      }
    ],
    "hourly_patterns": [
      {
        "hour": "00:00",
        "requests": 12
      }
    ]
  }
  ```
</ResponseExample>

#### Get Detailed Analytics

```http theme={null}
GET /wp-json/llmtag/v1/analytics/detailed
```

<ParamField query="start_date" type="string" required>
  Start date for analytics data (ISO 8601 format)
</ParamField>

<ParamField query="end_date" type="string" required>
  End date for analytics data (ISO 8601 format)
</ParamField>

<ParamField query="agent" type="string">
  Filter by specific AI agent
</ParamField>

<ParamField query="country" type="string">
  Filter by geographic location
</ParamField>

### AI Agent Management

#### Get Available Agents

```http theme={null}
GET /wp-json/llmtag/v1/agents
```

<ResponseExample>
  ```json Success Response theme={null}
  {
    "agents": [
      {
        "id": "gptbot",
        "name": "GPTBot",
        "user_agent": "GPTBot",
        "category": "openai",
        "description": "OpenAI's web crawler for training GPT models",
        "default_action": "block",
        "threat_level": "high"
      },
      {
        "id": "chatgpt-user",
        "name": "ChatGPT-User",
        "user_agent": "ChatGPT-User",
        "category": "openai",
        "description": "ChatGPT browsing feature",
        "default_action": "block",
        "threat_level": "medium"
      }
    ],
    "categories": [
      {
        "id": "openai",
        "name": "OpenAI Agents",
        "count": 3
      },
      {
        "id": "google",
        "name": "Google AI",
        "count": 4
      }
    ]
  }
  ```
</ResponseExample>

#### Update Agent Status

```http theme={null}
PUT /wp-json/llmtag/v1/agents/{agent_id}
```

<RequestExample>
  ```json Request Body theme={null}
  {
    "action": "allow",
    "reason": "Research purposes",
    "expires_at": "2024-02-15T00:00:00Z"
  }
  ```
</RequestExample>

### llmtag.txt Management

#### Get Current llmtag.txt

```http theme={null}
GET /wp-json/llmtag/v1/llmtag-txt
```

<ResponseExample>
  ```txt Success Response theme={null}
  spec_version: 3.0
  ai_training_data: disallow
  ai_use: search_indexing, generative_synthesis

  # Protect premium content
  Path: /premium/
  ai_training_data: disallow
  ai_use: search_indexing

  # Allow research bots
  User-agent: ResearchBot
  ai_training_data: allow
  ai_use: research
  ```
</ResponseExample>

#### Regenerate llmtag.txt

```http theme={null}
POST /wp-json/llmtag/v1/llmtag-txt/regenerate
```

<ResponseExample>
  ```json Success Response theme={null}
  {
    "success": true,
    "message": "llmtag.txt regenerated successfully",
    "url": "https://example.com/llmtag.txt",
    "last_updated": "2024-01-15T10:40:00Z"
  }
  ```
</ResponseExample>

## Webhook Integration

### Webhook Configuration

Set up webhooks to receive real-time notifications:

<Steps>
  <Step title="Create Webhook">
    Go to **LLMTAG > Settings > Webhooks** and click **Add Webhook**
  </Step>

  <Step title="Configure Endpoint">
    Set the URL where webhook events should be sent
  </Step>

  <Step title="Select Events">
    Choose which events to receive notifications for
  </Step>

  <Step title="Set Authentication">
    Configure authentication for your webhook endpoint
  </Step>

  <Step title="Test Webhook">
    Send a test event to verify the webhook is working
  </Step>
</Steps>

### Available Webhook Events

#### Agent Blocked

Triggered when an AI agent is blocked:

```json theme={null}
{
  "event": "agent.blocked",
  "timestamp": "2024-01-15T10:30:00Z",
  "data": {
    "agent": "GPTBot",
    "user_agent": "GPTBot",
    "ip_address": "192.168.1.100",
    "path": "/blog/post-1",
    "reason": "Blocked by policy",
    "request_id": "req_123456789"
  }
}
```

#### Settings Updated

Triggered when plugin settings are updated:

```json theme={null}
{
  "event": "settings.updated",
  "timestamp": "2024-01-15T10:35:00Z",
  "data": {
    "updated_by": "admin",
    "changes": [
      {
        "field": "ai_training_data",
        "old_value": "allow",
        "new_value": "disallow"
      }
    ]
  }
}
```

#### New Agent Detected

Triggered when a new AI agent is detected:

```json theme={null}
{
  "event": "agent.detected",
  "timestamp": "2024-01-15T10:40:00Z",
  "data": {
    "agent": "NewAI-Bot",
    "user_agent": "NewAI-Bot/1.0",
    "ip_address": "192.168.1.101",
    "path": "/",
    "first_seen": "2024-01-15T10:40:00Z"
  }
}
```

### Webhook Security

#### Signature Verification

All webhooks include a signature for verification:

```javascript theme={null}
// Example webhook signature verification
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}
```

## SDK and Libraries

### JavaScript SDK

```javascript theme={null}
// Install: npm install llmtag-wp-sdk
import { LLMTAGClient } from 'llmtag-wp-sdk';

const client = new LLMTAGClient({
  apiKey: 'your-api-key',
  baseUrl: 'https://your-site.com'
});

// Get current settings
const settings = await client.settings.get();

// Update settings
await client.settings.update({
  protection_mode: 'advanced',
  ai_training_data: 'disallow'
});

// Get analytics
const analytics = await client.analytics.getSummary('24h');
```

### PHP SDK

```php theme={null}
// Install: composer require llmtag/wordpress-sdk
use LLMTAG\WordPress\Client;

$client = new Client([
    'api_key' => 'your-api-key',
    'base_url' => 'https://your-site.com'
]);

// Get current settings
$settings = $client->settings()->get();

// Update settings
$client->settings()->update([
    'protection_mode' => 'advanced',
    'ai_training_data' => 'disallow'
]);

// Get analytics
$analytics = $client->analytics()->getSummary('24h');
```

### Python SDK

```python theme={null}
# Install: pip install llmtag-wp-sdk
from llmtag_wp_sdk import LLMTAGClient

client = LLMTAGClient(
    api_key='your-api-key',
    base_url='https://your-site.com'
)

# Get current settings
settings = client.settings.get()

# Update settings
client.settings.update({
    'protection_mode': 'advanced',
    'ai_training_data': 'disallow'
})

# Get analytics
analytics = client.analytics.get_summary('24h')
```

## Error Handling

### Error Response Format

All API errors follow a consistent format:

```json theme={null}
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "The request is invalid",
    "details": {
      "field": "ai_training_data",
      "reason": "Invalid value. Must be 'allow' or 'disallow'"
    }
  }
}
```

### Common Error Codes

<Columns cols={2}>
  <Card title="Authentication Errors" icon="key">
    * `INVALID_API_KEY`
    * `API_KEY_EXPIRED`
    * `INSUFFICIENT_PERMISSIONS`
  </Card>

  <Card title="Validation Errors" icon="exclamation-triangle">
    * `INVALID_REQUEST`
    * `MISSING_REQUIRED_FIELD`
    * `INVALID_VALUE`
  </Card>

  <Card title="Rate Limiting" icon="clock">
    * `RATE_LIMIT_EXCEEDED`
    * `QUOTA_EXCEEDED`
  </Card>

  <Card title="Server Errors" icon="server">
    * `INTERNAL_ERROR`
    * `SERVICE_UNAVAILABLE`
    * `DATABASE_ERROR`
  </Card>
</Columns>

### Error Handling Best Practices

<Steps>
  <Step title="Check HTTP Status Codes">
    Always check the HTTP status code before processing the response
  </Step>

  <Step title="Handle Rate Limiting">
    Implement exponential backoff for rate limit errors
  </Step>

  <Step title="Validate Responses">
    Validate API responses before using the data
  </Step>

  <Step title="Log Errors">
    Log API errors for debugging and monitoring
  </Step>
</Steps>

## Testing and Development

### API Testing

#### Using cURL

```bash theme={null}
# Test authentication
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://your-site.com/wp-json/llmtag/v1/settings

# Update settings
curl -X PUT \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"protection_mode": "advanced"}' \
     https://your-site.com/wp-json/llmtag/v1/settings
```

#### Using Postman

1. Import the API collection from the plugin documentation
2. Set your API key in the collection variables
3. Test each endpoint to verify functionality

### Development Environment

<Steps>
  <Step title="Set Up Local Environment">
    Install WordPress locally with the LLMTAG plugin
  </Step>

  <Step title="Enable Debug Mode">
    Enable WordPress debug mode for detailed error messages
  </Step>

  <Step title="Generate Test API Key">
    Create a test API key with full permissions
  </Step>

  <Step title="Test All Endpoints">
    Verify all API endpoints work correctly
  </Step>
</Steps>

## Best Practices

### API Usage

<Columns cols={2}>
  <Card title="Use Appropriate HTTP Methods" icon="code">
    Use GET for reading data, PUT for updates, POST for actions
  </Card>

  <Card title="Implement Caching" icon="clock">
    Cache API responses to reduce server load and improve performance
  </Card>

  <Card title="Handle Errors Gracefully" icon="exclamation-triangle">
    Implement proper error handling and user feedback
  </Card>

  <Card title="Respect Rate Limits" icon="gauge">
    Implement rate limiting in your applications to avoid hitting API limits
  </Card>
</Columns>

### Security

<Warning>
  Always follow security best practices when using the API:
</Warning>

* **Secure API Keys**: Store API keys securely and never expose them in client-side code
* **Use HTTPS**: Always use HTTPS for API requests
* **Validate Input**: Validate all input data before sending API requests
* **Monitor Usage**: Monitor API usage for unusual patterns or abuse
* **Regular Rotation**: Regularly rotate API keys for security

### Performance

<Note>
  Follow these tips to optimize API performance:
</Note>

* **Batch Requests**: Combine multiple operations into single requests when possible
* **Use Pagination**: Use pagination for large data sets
* **Implement Caching**: Cache frequently accessed data
* **Monitor Response Times**: Track API response times and optimize as needed
* **Use Webhooks**: Use webhooks instead of polling for real-time updates
