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
API Keys (Recommended)
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:
- Redirect user to authorization URL
- User grants permission
- Receive authorization code
- Exchange for access token
- Use access token in requests
Generating API Keys
Via UI
- Navigate to Settings → API Keys
- Click Generate New API Key
- Provide details:
- Name: "Production API", "Development", etc.
- Scope: Permissions (see below)
- Expiration: Optional expiry date
- Copy key immediately (shown only once)
- 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
| 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:
{
"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:
- Generate new key
- Update applications
- Test thoroughly
- Revoke old key
- 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
- Check format:
Authorization: Bearer KEY - Verify key status (not revoked)
- Check expiration date
- Verify scopes match operation
- Test with different endpoint
Intermittent Failures
- Check rate limits
- Verify network connectivity
- Review error logs
- Check key permissions
- Monitor API status page
Next Steps
- REST API Overview - Start using the API
- Rate Limits - Usage limits
- Webhooks - Event notifications
- Security Best Practices - 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 /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


