Product

Authentication & API Keys

Complete guide to authenticating API requests with Twig AI

TL;DR

Complete guide to authenticating API requests with Twig AI. Best for: Server-to-server, automated workflows, production applications

Key Takeaways

  • Authentication Methods
  • Generating API Keys
  • API Key Types
  • API Key Scopes
  • Using API Keys
  • Key Management Best Practices

Complete guide to authenticating API requests with Twig AI.

Authentication Methods

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

Format: Bearer token in Authorization header

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 SettingsAPI 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

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

ScopePermissions
chatChat/completion requests
agents:readList and view agents
agents:writeCreate/edit agents
agents:deleteDelete agents
data:readView data sources
data:writeModify data sources
analytics:readView analytics
adminFull access

Example:

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

Using API Keys

Request Header

Authorization: Bearer YOUR_API_KEY

Examples

cURL:

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:

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:

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:

# .env file
TWIG_API_KEY=sk_live_abc123...

Secret Managers:

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

Configuration:

// 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:

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

Error Handling

Invalid Key

Response:

{
  "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:

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

Solution: Generate new key

Insufficient Permissions

Response:

{
  "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

{
  "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


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 /dev/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.

Related Pages

Last updated January 25, 2026