# REST API Overview

Programmatic access to agents, data sources, and analytics.

## Base URL

```
https://api.twig.so
```

**Protocol**: HTTPS only (HTTP redirects to HTTPS with 301)

**API versioning**: Path-based (`/api/v1/...` for new endpoints, `/api/...` for legacy)

## Authentication

All API requests require authentication using an API key:

```bash
curl -X GET https://api.twig.so/api/agents \
  -H "Authorization: Bearer YOUR_API_KEY"
```

See [Authentication](/getting-started/authentication.md) for details on generating API keys.

## Rate Limits

API requests are rate-limited per organization:

| Plan           | Requests per Minute | Requests per Day |
| -------------- | ------------------- | ---------------- |
| **Free**       | 20                  | 1,000            |
| **Pro**        | 100                 | 10,000           |
| **Enterprise** | 1,000+              | Custom           |

Rate limit headers are included in every response:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
```

When exceeded, you'll receive a `429 Too Many Requests` response.

## Response Format

### Success Response

```json
{
  "data": {
    "id": "agent-123",
    "name": "Customer Support Agent",
    ...
  },
  "status": "success"
}
```

### Error Response

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Agent not found",
    "details": {
      "agentId": "agent-123"
    }
  },
  "status": "error"
}
```

## Common Error Codes

| Code                  | Status | Description                |
| --------------------- | ------ | -------------------------- |
| `invalid_request`     | 400    | Malformed request          |
| `unauthorized`        | 401    | Invalid or missing API key |
| `forbidden`           | 403    | Insufficient permissions   |
| `not_found`           | 404    | Resource not found         |
| `rate_limit_exceeded` | 429    | Too many requests          |
| `internal_error`      | 500    | Server error               |

## Core Endpoints

### Chat & Completion

#### POST /api/chat

Generate an AI response for a given prompt.

```bash
curl -X POST https://api.twig.so/api/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "What is your refund policy?",
    "agentId": "agent-123",
    "sessionId": "session-456",
    "stream": false
  }'
```

**Response:**

```json
{
  "response": "Our refund policy allows returns within 30 days...",
  "sources": [
    {
      "title": "Refund Policy",
      "url": "https://example.com/refund-policy",
      "content": "...",
      "relevance": 0.95
    }
  ],
  "metadata": {
    "latency": 1.2,
    "tokensUsed": 1523,
    "strategy": "CEDAR",
    "confidence": 0.92
  }
}
```

### Agents

#### GET /api/ai-agent-managers

List all AI agents in your organization.

```bash
curl -X GET https://api.twig.so/api/ai-agent-managers \
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### POST /api/ai-agent-managers

Create a new AI agent.

```bash
curl -X POST https://api.twig.so/api/ai-agent-managers \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support Agent",
    "description": "Customer support assistant",
    "strategyCode": "CEDAR",
    "dataSourceIds": ["ds-1", "ds-2"]
  }'
```

#### GET /api/ai-agent-managers/:id

Get details of a specific agent.

#### PUT /api/ai-agent-managers/:id

Update an agent's configuration.

#### DELETE /api/ai-agent-managers/:id

Delete an agent.

### Data Sources

#### GET /api/data-specs

List all data sources.

```bash
curl -X GET https://api.twig.so/api/data-specs \
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### POST /api/data-specs

Create a new data source.

```bash
curl -X POST https://api.twig.so/api/data-specs \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "WEBSITE",
    "name": "Product Documentation",
    "url": "https://docs.example.com",
    "refreshFrequency": "DAILY"
  }'
```

#### POST /api/data-specs/:id/process

Trigger processing/sync for a data source.

```bash
curl -X POST https://api.twig.so/api/data-specs/ds-123/process \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Interactions

#### GET /api/interactions

List recent interactions.

```bash
curl -X GET https://api.twig.so/api/interactions?limit=50 \
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### POST /api/interactions/feedback

Submit feedback on an interaction.

```bash
curl -X POST https://api.twig.so/api/interactions/feedback \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "interactionId": "int-123",
    "rating": 5,
    "comment": "Very helpful!"
  }'
```

### Analytics

#### GET /api/analytics/charts/dashboard

Get analytics dashboard data.

```bash
curl -X GET https://api.twig.so/api/analytics/charts/dashboard?startDate=2024-01-01&endDate=2024-01-31 \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## Advanced Features

### Streaming Responses

Enable streaming for real-time response delivery:

```bash
curl -X POST https://api.twig.so/api/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Explain RAG in detail",
    "agentId": "agent-123",
    "stream": true
  }'
```

Responses are sent as Server-Sent Events (SSE):

```
data: {"delta": "RAG stands for", "done": false}
data: {"delta": " Retrieval-Augmented", "done": false}
data: {"delta": " Generation...", "done": false}
data: {"delta": "", "done": true, "sources": [...]}
```

### Semantic Search Only

Retrieve relevant documents without generating a response:

```bash
curl -X POST https://api.twig.so/api/semantic-search \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "pricing information",
    "orgId": "org-123",
    "topK": 10
  }'
```

### Webhooks

Register webhooks to receive events:

```bash
curl -X POST https://api.twig.so/api/webhooks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhook",
    "events": ["interaction.created", "agent.updated"],
    "secret": "your-webhook-secret"
  }'
```

## SDKs & Client Libraries

### JavaScript/TypeScript

```bash
npm install @twig-ai/sdk
```

```typescript
import { TwigAI } from '@twig-ai/sdk';

const twig = new TwigAI({ apiKey: process.env.TWIG_API_KEY });

const response = await twig.chat({
  prompt: "What is your refund policy?",
  agentId: "agent-123"
});

console.log(response.text);
```

### Python (Coming Soon)

```bash
pip install twig-ai
```

```python
from twig_ai import TwigAI

twig = TwigAI(api_key=os.environ["TWIG_API_KEY"])

response = twig.chat(
    prompt="What is your refund policy?",
    agent_id="agent-123"
)

print(response.text)
```

## Best Practices

### 1. Error Handling

Always handle errors gracefully:

```typescript
try {
  const response = await twig.chat({ prompt, agentId });
  return response;
} catch (error) {
  if (error.code === 'rate_limit_exceeded') {
    // Wait and retry
    await sleep(1000);
    return retry();
  }
  // Log error and handle appropriately
  logger.error(error);
  throw error;
}
```

### 2. Rate Limit Management

Implement exponential backoff:

```typescript
async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.code === 'rate_limit_exceeded' && i < maxRetries - 1) {
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }
      throw error;
    }
  }
}
```

### 3. Caching

Cache responses for frequently asked questions:

```typescript
const cache = new Map();

async function getCachedResponse(prompt, agentId) {
  const cacheKey = `${agentId}:${prompt}`;
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  
  const response = await twig.chat({ prompt, agentId });
  cache.set(cacheKey, response);
  
  return response;
}
```

### 4. Session Management

Maintain conversation context with session IDs:

```typescript
const sessionId = generateSessionId();

// First message
await twig.chat({
  prompt: "What are your pricing plans?",
  agentId: "agent-123",
  sessionId
});

// Follow-up maintains context
await twig.chat({
  prompt: "What's included in the Enterprise plan?",
  agentId: "agent-123",
  sessionId // Same session
});
```

## Next Steps

* [API Endpoints Reference](https://github.com/thrivapp/twig-help-docs/blob/staging/developer-api/endpoints.md) - Complete endpoint documentation
* [Authentication](/getting-started/authentication.md) - API key management
* [Webhooks](/product/developer-api/webhooks.md) - Event notifications
* [SDKs](/product/developer-api/sdks.md) - Client library documentation
* [Rate Limits](/product/developer-api/rate-limits.md) - Detailed rate limit information


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.twig.so/product/developer-api/overview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
