# Authentication & API Keys

Complete guide to authenticating API requests with Twig AI.

## Authentication Methods

### API Keys (Recommended)

**Best for:** Server-to-server, automated workflows, production applications

**Format:** Bearer token in Authorization header

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

### OAuth 2.0 (For User Context)

**Best for:** User-specific actions, third-party integrations

**Flow:**

1. Redirect user to authorization URL
2. User grants permission
3. Receive authorization code
4. Exchange for access token
5. Use access token in requests

## Generating API Keys

### Via UI

1. Navigate to **Settings** → **API Keys**
2. Click **Generate New API Key**
3. Provide details:
   * **Name**: "Production API", "Development", etc.
   * **Scope**: Permissions (see below)
   * **Expiration**: Optional expiry date
4. Copy key immediately (shown only once)
5. Store securely

### Via API

```bash
curl -X POST https://api.twig.so/api/api-keys \
  -H "Authorization: Bearer ADMIN_KEY" \
  -d '{
    "name": "Production API",
    "scopes": ["chat", "agents:read"],
    "expiresAt": "2025-12-31"
  }'
```

## API Key Types

### Organization Keys

* Access all resources in organization
* Shared across team
* Higher permissions
* Require admin to create

### Personal Keys

* User-specific access
* Limited to user's permissions
* Can be self-generated
* Tied to user account

### Scoped Keys

* Limited permissions
* Specific operations only
* Most secure
* Recommended for production

## API Key Scopes

| Scope            | Permissions              |
| ---------------- | ------------------------ |
| `chat`           | Chat/completion requests |
| `agents:read`    | List and view agents     |
| `agents:write`   | Create/edit agents       |
| `agents:delete`  | Delete agents            |
| `data:read`      | View data sources        |
| `data:write`     | Modify data sources      |
| `analytics:read` | View analytics           |
| `admin`          | Full access              |

**Example:**

```json
{
  "scopes": [
    "chat",
    "agents:read",
    "analytics:read"
  ]
}
```

## Using API Keys

### Request Header

```
Authorization: Bearer YOUR_API_KEY
```

### Examples

**cURL:**

```bash
curl -X POST https://api.twig.so/api/chat \
  -H "Authorization: Bearer sk_live_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello", "agentId": "agent-123"}'
```

**JavaScript:**

```javascript
const response = await fetch('https://api.twig.so/api/chat', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk_live_abc123...',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: 'Hello',
    agentId: 'agent-123'
  })
});
```

**Python:**

```python
import requests

headers = {
    'Authorization': 'Bearer sk_live_abc123...',
    'Content-Type': 'application/json'
}

response = requests.post(
    'https://api.twig.so/api/chat',
    headers=headers,
    json={'prompt': 'Hello', 'agentId': 'agent-123'}
)
```

## Key Management Best Practices

### Security

✅ **Do:**

* Store keys in environment variables
* Use different keys for dev/staging/prod
* Rotate keys regularly (every 90 days)
* Use scoped keys with minimum permissions
* Revoke compromised keys immediately

❌ **Don't:**

* Hardcode keys in source code
* Commit keys to version control
* Share keys via email/chat
* Use same key across all environments
* Give keys broader scope than needed

### Storage

**Environment Variables:**

```bash
# .env file
TWIG_API_KEY=sk_live_abc123...
```

**Secret Managers:**

* AWS Secrets Manager
* Google Cloud Secret Manager
* HashiCorp Vault
* Azure Key Vault

**Configuration:**

```typescript
// config.ts
export const config = {
  twigApiKey: process.env.TWIG_API_KEY
};
```

### Rotation

**Manual Rotation:**

1. Generate new key
2. Update applications
3. Test thoroughly
4. Revoke old key
5. Monitor for errors

**Automated Rotation:**

```bash
# Rotate every 90 days
0 0 1 */3 * /usr/local/bin/rotate-keys.sh
```

## Error Handling

### Invalid Key

**Response:**

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "The API key provided is invalid"
  },
  "status": 401
}
```

**Solutions:**

* Verify key is correct
* Check for extra spaces
* Ensure key hasn't been revoked
* Verify key hasn't expired

### Expired Key

**Response:**

```json
{
  "error": {
    "code": "expired_api_key",
    "message": "API key expired on 2024-12-31"
  },
  "status": 401
}
```

**Solution:** Generate new key

### Insufficient Permissions

**Response:**

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "API key lacks required scope: agents:write"
  },
  "status": 403
}
```

**Solution:** Use key with appropriate scopes

## Monitoring

### Track Usage

View API key usage:

* Request count
* Success/failure rate
* Last used timestamp
* Geographic distribution

### Set Alerts

```typescript
{
  "alerts": {
    "unusualActivity": true,
    "highUsage": {
      "threshold": 10000,
      "period": "daily"
    },
    "failures": {
      "threshold": 100,
      "period": "hourly"
    }
  }
}
```

## Troubleshooting

### Key Not Working

1. Check format: `Authorization: Bearer KEY`
2. Verify key status (not revoked)
3. Check expiration date
4. Verify scopes match operation
5. Test with different endpoint

### Intermittent Failures

1. Check rate limits
2. Verify network connectivity
3. Review error logs
4. Check key permissions
5. Monitor API status page

## Next Steps

* [REST API Overview](/product/developer-api/overview.md) - Start using the API
* [Rate Limits](/product/developer-api/rate-limits.md) - Usage limits
* [Webhooks](/product/developer-api/webhooks.md) - Event notifications
* [Security Best Practices](/product/security/best-practices.md) - Secure your keys


---

# 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/authentication.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.
