Skip to main content

API Keys

API keys enable programmatic access to your botBrains projects, allowing you to build custom integrations, automate workflows, and embed AI capabilities directly into your applications. Each API key can be scoped with specific permissions to ensure secure, controlled access to exactly the resources and operations your integration needs.

Why API Keys Matter

API keys unlock powerful automation and integration capabilities that extend botBrains beyond the dashboard:

Build Custom Integrations

Connect botBrains to your existing tools and workflows. Use the API to sync customer data from your CRM, trigger AI responses from your application backend, or integrate conversation analytics into your business intelligence platform.

Automate Operations

Programmatically manage knowledge sources, create conversations, and monitor AI performance without manual dashboard access. Schedule scripts to update data providers, export analytics reports, or sync user attributes from your authentication system.

Embed AI Capabilities

Power your application’s features with botBrains AI. Generate responses to user questions, retrieve knowledge snippets, or analyze conversation sentiment - all from your own codebase. Your users never need to know botBrains is powering their experience.

Secure Third-Party Access

Grant controlled access to external systems, contractors, or partners without sharing login credentials. API keys provide granular permission control and can be revoked instantly if compromised or no longer needed.

Support CI/CD Workflows

Integrate botBrains into your deployment pipeline. Use API keys in GitHub Actions, Jenkins, or other automation tools to update knowledge bases when documentation changes, test AI responses, or validate configurations before production deployment.

How API Keys Work

Authentication and Security

API keys authenticate requests to the botBrains API using a bearer token scheme:
Example API Request
curl https://api.botbrains.io/v1/projects/123/conversations \
  -H "Authorization: Bearer sk_live_abc123def456..." \
  -H "Content-Type: application/json"
Each key consists of:
  • Prefix (sk_live_ or sk_test_) - Indicates environment and key type
  • Secret - A cryptographically secure random string (43 characters)
  • Permissions - Specific operations this key can perform
Treat API keys like passwords. Never commit them to version control, share them in public channels, or expose them in client-side code. Anyone with your API key can perform actions within its permission scope.

Permission-Based Access Control

Unlike login credentials that grant full access, API keys use granular permissions to limit what operations they can perform. When you create an API key, you select exactly which actions it should be allowed to execute. Principle of Least Privilege: Grant only the minimum permissions required for your use case. If you’re building a read-only analytics dashboard, your API key only needs read permissions - not write or delete capabilities.

Project-Level Scope

API keys are scoped to a specific project. An API key created in your “Production Support Bot” project cannot access conversations, knowledge, or any other resources from your “Sales Bot” project. This isolation ensures security and prevents accidental cross-project operations. To access multiple projects programmatically, create separate API keys in each project with appropriate permissions for that specific use case.

Creating API Keys

Generate new API keys from your project’s settings:
1

Navigate to API Keys

Go to Project → Settings → API Keys in your project
2

Create New Key

Click Create API Key to open the creation dialog
3

Name Your Key

Enter a descriptive name indicating the key’s purpose (e.g., “GitHub Actions CI”, “Analytics Dashboard”, “CRM Sync Script”)
4

Select Permissions

Choose the specific permissions this key needs (see Permission Reference below)
5

Generate and Copy

Click Create Key and immediately copy the secret - you won’t see it again
6

Store Securely

Save the key in your password manager, environment variables, or secrets management system
Descriptive Naming: Use names that clearly indicate the key’s purpose and where it’s used. Good examples: “Production CRM Sync”, “Staging CI Pipeline”, “Analytics Export Script”, “Partner Integration Dev”. This makes it easy to identify which key to revoke if you need to remove access.

First-Time Secret Display

When you create an API key, botBrains displays the full secret exactly once in a dialog:
sk_live_Np8JQxH7mF3vKL9wRt2YzBnX4cDq6sA1pWe5iUoGhMj
Critical: Copy this secret immediately and store it securely. After you close this dialog, the full secret cannot be retrieved. If you lose it, you’ll need to generate a new key. For security, the secret is:
  • Never stored in plain text
  • Never displayed again after initial creation
  • Masked in the API keys table (shown as •••••••••••)
  • Can be viewed later (requires explicit action) but should be rotated if exposed

Managing Existing Keys

View Your API Keys

The API Keys page displays all keys for your project in a table showing: Name - The descriptive name you provided when creating the key Secret - Masked by default (•••••••••••••••••••••••••••••••••••••••••). Click the eye icon to reveal the full secret, or click the copy icon to copy it directly to your clipboard without revealing it. Permissions - All permissions granted to this key, displayed as badges (e.g., project:read, conversation:read, knowledge:write) Actions - Edit or delete buttons for managing the key
Secret Visibility: The full secret can be retrieved after creation by clicking the eye icon, but this requires your authentication. Treat any revealed secret as potentially compromised and consider rotating the key if it was displayed in an insecure environment.

Edit Key Permissions

You can modify a key’s permissions at any time without regenerating the secret:
1

Click Edit Icon

Find the key in your API Keys table and click the edit (pencil) icon
2

Update Permissions

Add or remove permissions using the permission picker
3

Save Changes

Click Update Permissions - changes take effect immediately
Use Cases for Updating Permissions:
  • Grant additional access as your integration evolves
  • Remove permissions that are no longer needed (permission reduction)
  • Temporarily elevate access for troubleshooting, then reduce
  • Align permissions with updated role requirements
Permission changes take effect immediately. If you remove permissions that an active integration relies on, API calls will start failing with 403 Forbidden errors.

Delete API Keys

Remove API keys that are no longer needed or have been compromised:
  1. Find the key in the API Keys table
  2. Click the delete (trash) icon
  3. Confirm deletion
Deletion is immediate and permanent:
  • All requests using this key will fail immediately with 401 Unauthorized
  • The key cannot be recovered - you’ll need to create a new one
  • Any running scripts or integrations will stop working
When to Delete Keys:
  • When decommissioning an integration or script
  • If a key is exposed or compromised
  • When a team member leaves who had access to the key
  • During security audits to remove unused keys
  • After migrating to a new key as part of rotation

Permission Reference

API key permissions map directly to the permission system used for user roles. Each permission grants access to specific operations within a functional area.

Core Permissions Structure

Permissions follow a resource:action naming pattern:
  • resource - The functional area (e.g., knowledge, conversation, deployment)
  • action - The operation type (typically read, write, create, update, delete)
Permission Dependencies: Many write/update/delete permissions automatically require the corresponding read permission. For example, granting knowledge:write automatically includes knowledge:read. The UI handles these dependencies when you select permissions.

Common Permission Patterns

Read-Only Access

For analytics dashboards, reporting scripts, or monitoring tools:
project:read
conversation:read
metric:read
topic:read
userpool:read
What You Can Do: Retrieve conversation history, view analytics data, export metrics, analyze user interactions What You Cannot Do: Modify any data, create conversations, update knowledge, change deployments

Knowledge Management

For content sync scripts, documentation updates, or CRM data imports:
knowledge:read
knowledge:write
table:read
table:write
file:read
conversation:read
What You Can Do: Create and update snippets, manage data tables, upload files, sync external data sources, view conversations to identify knowledge gaps What You Cannot Do: Modify AI behavior, change deployments, manage team access, generate conversations

Full Conversation Access

For custom support interfaces, chatbot integrations, or conversation management tools:
conversation:read
conversation:write
conversation:generate
userpool:read
userpool:update
label:read
label:upsert
What You Can Do: Create conversations, generate AI responses, update user profiles, apply labels, manage conversation lifecycle What You Cannot Do: Modify knowledge base, change AI configuration, deploy changes

Complete Permission List

You can find the up to date permission list in the Roles an Permissions documentation: Roles and Permissions.
Organization vs Project Permissions: API keys only support project-level permissions. Organization-level operations (billing, team management, organization settings) cannot be performed via API keys and require authenticated user sessions.

Using API Keys

Environment Variables

Store API keys in environment variables, never hardcode them in source files:
BOTBRAINS_API_KEY=sk_live_Np8JQxH7mF3vKL9wRt2YzBnX4cDq6sA1pWe5iUoGhMj
BOTBRAINS_PROJECT_ID=123
Never commit API keys to Git: Add .env to your .gitignore file. Use secrets management in CI/CD (GitHub Secrets, GitLab CI Variables, AWS Secrets Manager, etc.).

Client Libraries

Use official or community client libraries for type-safe, convenient API access:
import { BotBrainsClient } from '@botbrains/sdk';

const client = new BotBrainsClient({
  apiKey: process.env.BOTBRAINS_API_KEY,
  projectId: process.env.BOTBRAINS_PROJECT_ID
});

// List conversations
const conversations = await client.conversations.list({
  limit: 50,
  status: 'unresolved'
});

// Create a new conversation
const conversation = await client.conversations.create({
  userId: 'user_123',
  message: 'How do I reset my password?'
});

// Get AI response
const response = await client.conversations.generateResponse({
  conversationId: conversation.id
});

Common Integration Patterns

Sync User Data from CRM

Keep botBrains user profiles synchronized with your CRM:
CRM Sync Script
async function syncUserFromCRM(crmUserId) {
  // Fetch user from your CRM
  const crmUser = await yourCRM.getUser(crmUserId);

  // Update in botBrains
  await fetch(
    `https://api.botbrains.io/v1/projects/${projectId}/users/${crmUser.id}`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        first_name: crmUser.firstName,
        last_name: crmUser.lastName,
        email: crmUser.email,
        external_attributes: {
          subscription_tier: crmUser.plan,
          account_status: crmUser.status,
          lifetime_value: crmUser.ltv
        }
      })
    }
  );
}

// Run sync on schedule or trigger
setInterval(() => syncAllUsers(), 3600000); // Hourly
Required Permissions: userpool:read, userpool:update

Update Knowledge When Docs Change

Automatically sync knowledge base when documentation is updated:
GitHub Actions Workflow
name: Sync Docs to botBrains

on:
  push:
    branches: [main]
    paths: ['docs/**']

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Trigger Knowledge Sync
        run: |
          curl -X POST \
            https://api.botbrains.io/v1/projects/${{ secrets.BOTBRAINS_PROJECT_ID }}/data-providers/${{ secrets.DATA_PROVIDER_ID }}/sync \
            -H "Authorization: Bearer ${{ secrets.BOTBRAINS_API_KEY }}" \
            -H "Content-Type: application/json"
Required Permissions: knowledge:read, knowledge:write

Export Analytics for BI Tools

Pull conversation analytics into your business intelligence platform:
Analytics Export
import pandas as pd
from datetime import datetime, timedelta

def export_weekly_metrics():
    # Fetch metrics from botBrains
    response = requests.get(
        f'https://api.botbrains.io/v1/projects/{project_id}/metrics',
        headers={'Authorization': f'Bearer {api_key}'},
        params={
            'start_date': (datetime.now() - timedelta(days=7)).isoformat(),
            'end_date': datetime.now().isoformat(),
            'group_by': 'day'
        }
    )

    metrics = response.json()

    # Convert to DataFrame for analysis
    df = pd.DataFrame(metrics['data'])

    # Push to your data warehouse
    df.to_sql('botbrains_metrics', your_db_connection, if_exists='append')

    return df

# Schedule with cron or orchestration tool
weekly_metrics = export_weekly_metrics()
Required Permissions: metric:read, conversation:read, export:read

Generate AI Responses in Your App

Embed botBrains AI directly in your application:
Custom Support Interface
async function getAIResponse(userId: string, question: string) {
  // Create conversation
  const createResponse = await fetch(
    `https://api.botbrains.io/v1/projects/${projectId}/conversations`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user_id: userId,
        message: question
      })
    }
  );

  const conversation = await createResponse.json();

  // Generate AI response
  const responseData = await fetch(
    `https://api.botbrains.io/v1/projects/${projectId}/conversations/${conversation.id}/generate`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      }
    }
  );

  const aiResponse = await responseData.json();

  return {
    conversationId: conversation.id,
    answer: aiResponse.message.content,
    sources: aiResponse.sources
  };
}

// Use in your app
const response = await getAIResponse('user_123', 'How do I reset my password?');
console.log(response.answer);
Required Permissions: conversation:read, conversation:generate, userpool:read

Rate Limits

API keys are subject to rate limits to ensure platform stability and fair usage:

Current Limits

  • Standard Plan: 100 requests per minute, 10,000 per day
  • Professional Plan: 300 requests per minute, 50,000 per day
  • Enterprise Plan: Custom limits based on agreement
Burst Allowance: Short bursts above the per-minute limit are allowed (up to 2x for up to 10 seconds) to accommodate traffic spikes.

Rate Limit Headers

Every API response includes rate limit information:
HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1640995200
  • X-RateLimit-Limit - Maximum requests allowed per minute
  • X-RateLimit-Remaining - Requests remaining in current window
  • X-RateLimit-Reset - Unix timestamp when limit resets

Handling Rate Limits

When you exceed the rate limit, the API returns 429 Too Many Requests:
{
  "error": "rate_limit_exceeded",
  "message": "Rate limit exceeded. Please retry after 23 seconds.",
  "retry_after": 23
}
Implement Exponential Backoff:
Rate Limit Handling
async function makeRequestWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After') || Math.pow(2, attempt);
      console.log(`Rate limited. Retrying after ${retryAfter}s...`);
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      continue;
    }

    return response;
  }

  throw new Error('Max retries exceeded');
}
Optimize for Rate Limits: Batch requests when possible, cache responses appropriately, use webhooks instead of polling, and implement request queuing for high-volume integrations.

Best Practices

Rotate Keys Regularly

Implement a key rotation schedule to minimize exposure risk: Recommended Rotation Schedule:
  • Production keys: Every 90 days
  • Development keys: Every 180 days
  • Contractor/partner keys: When access ends or every 30 days
  • Compromised keys: Immediately
Rotation Process:
1

Generate New Key

Create a new API key with identical permissions
2

Update Systems

Deploy the new key to all systems using the old key (update environment variables, secrets managers, CI/CD configs)
3

Monitor

Watch for errors indicating systems still using the old key
4

Delete Old Key

After confirming all systems migrated (typically 24-48 hours), delete the old key

Use Separate Keys per Integration

Create dedicated API keys for each integration or use case: Why This Matters:
  • Easier Auditing - Track which integration is making which requests
  • Simpler Revocation - Decommission one integration without affecting others
  • Granular Permissions - Grant only what each integration needs
  • Clearer Naming - “CRM Sync” vs “Analytics Export” vs “CI Pipeline”
Example Key Organization:
Production CRM Sync (userpool:read, userpool:update)
Production Analytics Dashboard (conversation:read, metric:read)
Staging CI Pipeline (knowledge:write, deployment:update)
Partner Integration Dev (conversation:read, conversation:generate)

Secure Storage

Never expose API keys in insecure locations:
Common Mistakes to Avoid:
  • Hardcoding keys in source code
  • Committing keys to version control
  • Storing keys in client-side code (JavaScript, mobile apps)
  • Sharing keys in Slack, email, or documentation
  • Using the same key across development and production
Secure Storage Options: Environment Variables - For local development and simple deployments
export BOTBRAINS_API_KEY=sk_live_...
Secrets Managers - For production systems
  • AWS Secrets Manager
  • Google Secret Manager
  • Azure Key Vault
  • HashiCorp Vault
CI/CD Secret Storage - For automation pipelines
  • GitHub Secrets
  • GitLab CI/CD Variables
  • CircleCI Environment Variables
  • Jenkins Credentials
Password Managers - For manual storage (backups, team access)
  • 1Password
  • LastPass
  • Bitwarden

Monitor Key Usage

Track API key activity to detect anomalies: What to Monitor:
  • Unusual request volumes (sudden spikes may indicate compromise)
  • Failed authentication attempts (wrong key being used)
  • Permission errors (integration trying unauthorized actions)
  • Geographic anomalies (requests from unexpected locations)
  • Off-hours activity (requests when systems should be idle)
Set Up Alerts: Configure notifications for suspicious patterns that might indicate key compromise or misconfiguration.

Environment Separation

Use different API keys for different environments:
Development:   sk_test_DevEnvironment_123...
Staging:       sk_test_StagingCI_456...
Production:    sk_live_ProductionCRM_789...
Benefits:
  • Prevent production data exposure in development
  • Enable testing without affecting real users
  • Simplify troubleshooting (clear separation of logs)
  • Reduce risk of accidental production modifications

Respond to Compromises Quickly

If an API key is exposed or compromised:
1

Immediate Revocation

Delete the compromised key immediately from the API Keys page
2

Generate Replacement

Create a new key with the same permissions but a new secret
3

Update Systems

Deploy the new key to all systems that were using the old one
4

Audit Activity

Review API logs to determine what actions were taken with the compromised key
5

Assess Impact

Check if any unauthorized data access or modifications occurred
6

Notify if Necessary

If customer data was accessed, follow your incident response procedures
Common Exposure Scenarios:
  • Committed to public GitHub repository
  • Posted in public Slack channel or forum
  • Included in screenshot or screen share
  • Accidentally logged to monitoring service
  • Left in developer laptop that was lost/stolen

Troubleshooting

401 Unauthorized Errors

Symptom: API requests return 401 Unauthorized Possible Causes:
  1. Invalid API key - Key was deleted or never existed
  2. Incorrect format - Missing “Bearer” prefix or malformed key
  3. Wrong environment - Using test key in production or vice versa
Solutions:
# Check Authorization header format
Authorization: Bearer sk_live_Np8JQxH7mF3vKL9wRt2YzBnX4cDq6sA1pWe5iUoGhMj

# Verify key exists in dashboard
# Check that key wasn't deleted
# Ensure no extra whitespace or line breaks in key

403 Forbidden Errors

Symptom: API requests return 403 Forbidden or “Insufficient permissions” Possible Causes:
  1. Missing permission - Key doesn’t have required permission for the operation
  2. Wrong project - Using key from Project A to access Project B resources
  3. Permission recently removed - Key permissions were updated
Solutions:
  • Review the permission requirements for the endpoint you’re calling
  • Check key permissions in the API Keys dashboard
  • Verify you’re using the correct project ID in the request
  • Update key permissions if your integration needs changed

Rate Limit Exceeded

Symptom: Getting 429 Too Many Requests responses Solutions:
  • Implement exponential backoff (see Rate Limits section)
  • Reduce request frequency
  • Cache responses when appropriate
  • Use batch endpoints instead of individual requests
  • Consider upgrading to a higher-tier plan

Key Not Working After Creation

Symptom: Newly created key returns 401 errors Solutions:
  • Verify you copied the complete secret from the creation dialog
  • Check for whitespace or newline characters in your stored key
  • Ensure you’re using the key in the correct project
  • Wait 1-2 minutes - keys may take a moment to propagate

Can’t View Full Secret

Symptom: Need to retrieve API key secret but only see masked version Solutions:
  • Click the eye icon to reveal the full secret (requires authentication)
  • If secret was compromised during reveal, rotate the key
  • If you lost the secret and can’t retrieve it securely, create a new key

Permission Errors After Updating Key

Symptom: Integration stopped working after modifying key permissions Solutions:
  • Review what permissions were removed
  • Check application logs for specific permission error messages
  • Add back required permissions or update integration to not use removed capabilities
  • Consider creating a new key with correct permissions instead of modifying

Security Considerations

Scope Keys Appropriately

Grant the minimum permissions required: Bad Practice:
Creating one "master" API key with all permissions
Using the same key for all integrations
Granting full project access when only conversation read is needed
Good Practice:
Analytics Dashboard: conversation:read, metric:read, topic:read
CRM Sync: userpool:read, userpool:update
Documentation Sync: knowledge:read, knowledge:write
CI Pipeline: deployment:update, knowledge:write

Never Use in Client-Side Code

API keys must only be used in server-side code:
Never Expose Keys in:
  • Frontend JavaScript (React, Vue, Angular)
  • Mobile apps (iOS, Android)
  • Browser extensions
  • Public repositories
  • Client-side environment variables
Why: Anyone can inspect client-side code and extract the API key. Instead, create a backend API that uses the key server-side. Safe Pattern:
User's Browser → Your Backend API (uses API key) → botBrains API

Audit Key Usage

Regularly review which keys exist and what they’re used for: Quarterly Audit Checklist:
  • List all active API keys
  • Verify each key is still needed
  • Confirm permissions are still appropriate
  • Check key names are descriptive and accurate
  • Delete keys for decommissioned integrations
  • Rotate keys that haven’t been rotated in 90+ days
  • Review API logs for unusual patterns

Compliance Considerations

API keys and data export permissions have compliance implications: GDPR/Privacy Regulations:
  • Keys with full_export:read can access PII - restrict carefully
  • Document which systems have API access to customer data
  • Include API integrations in your data processing records
  • Ensure third-party API key holders have data processing agreements
SOC 2/Security Certifications:
  • Maintain inventory of all API keys and their permissions
  • Document key rotation procedures
  • Implement monitoring and alerting for key usage
  • Include API keys in security incident response plans

Next Steps

Now that you understand API key management, explore related topics: