← Back to Guides
advancedAdvanced35 min read time

API & Webhooks for Custom Automation

Advanced guide for authentication, event handling, and custom integration examples using Bravin AI's API and webhooks.

Author: Bravin AI Team
Published on February 10, 2024
Updated on March 14, 2024

Introduction

The Bravin AI API allows you to integrate chatbot functionality into your own applications, trigger custom workflows, and sync data bidirectionally.

What You Can Build:

  • Custom dashboards
  • CRM integrations
  • Automated workflows
  • Multi-platform bots
  • Analytics pipelines
  • E-commerce automations

API access is available on Pro and Enterprise plans. Free plan has limited webhook support.

Authentication

API Key Authentication: All API requests require an API key in the Authorization header.

Never expose API keys in frontend code. Use them only on your backend server.

Authentication Example
curl https://api.bravin.ai/v1/conversations \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"

Authentication (continued)

Generate API Key:

  1. Log in to Bravin AI
  2. Go to Settings → API Keys
  3. Click Create New Key
  4. Name it descriptively
  5. Copy and store securely

Key Types:

  • Production - For live environment
  • Development - For testing
  • Restricted - Limited permissions

Rotate Keys: Best practice: rotate keys every 90 days.

Environment Variable Setup
# .env file
BRAVIN_API_KEY=sk_live_abc123xyz789
BRAVIN_API_URL=https://api.bravin.ai/v1

REST API Endpoints

Base URL: https://api.bravin.ai/v1

Main Endpoints:

Key Endpoints
# Conversations
GET    /conversations           # List conversations
GET    /conversations/:id       # Get specific conversation
POST   /conversations           # Create new conversation
DELETE /conversations/:id       # Delete conversation

# Messages
GET    /conversations/:id/messages  # Get messages
POST   /conversations/:id/messages  # Send message

# Knowledge Base
GET    /knowledge/documents     # List documents
POST   /knowledge/documents     # Upload document
DELETE /knowledge/documents/:id # Delete document

# Analytics
GET    /analytics/summary       # Get metrics
GET    /analytics/conversations # Conversation analytics

REST API Examples

Send a Message:

POST /conversations/:id/messages
const axios = require('axios');

const response = await axios.post(
  'https://api.bravin.ai/v1/conversations/conv_123/messages',
  {
    content: 'What are your business hours?',
    userId: 'user_456',
    metadata: {
      source: 'mobile_app',
      channel: 'in-app-chat'
    }
  },
  {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    }
  }
);

console.log(response.data);
// Output:
// {
//   "id": "msg_789",
//   "conversationId": "conv_123",
//   "content": "We're open Monday-Friday 9 AM - 6 PM EST.",
//   "role": "assistant",
//   "timestamp": "2024-03-14T10:30:00Z"
// }

Webhooks Setup

What Are Webhooks? Webhooks allow Bravin AI to send real-time notifications to your server when events occur.

Setup:

  1. Create an endpoint on your server (e.g., https://yoursite.com/webhooks/bravin)
  2. Go to Settings → Webhooks
  3. Click Add Webhook
  4. Enter your URL
  5. Select events to subscribe to
  6. Save

Your Endpoint Must:

  • Accept POST requests
  • Return 200 OK within 5 seconds
  • Verify webhook signature (security)
Express.js Webhook Handler
const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

app.post('/webhooks/bravin', (req, res) => {
  // Verify signature
  const signature = req.headers['x-bravin-signature'];
  const payload = JSON.stringify(req.body);
  const expectedSignature = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  if (signature !== expectedSignature) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process webhook
  const event = req.body;
  console.log('Received event:', event.type);
  
  switch (event.type) {
    case 'conversation.created':
      handleNewConversation(event.data);
      break;
    case 'message.received':
      handleNewMessage(event.data);
      break;
    // ... other event types
  }
  
  res.status(200).send('OK');
});

app.listen(3000);

Webhook Event Types

Available Events:

Conversation Events:

  • conversation.created - New conversation started
  • conversation.updated - Conversation metadata changed
  • conversation.closed - Conversation marked as resolved
  • conversation.reopened - Closed conversation reopened

Message Events:

  • message.received - User sent a message
  • message.sent - Agent responded
  • message.failed - Message delivery failed

Agent Events:

  • agent.handoff.requested - AI requested human takeover
  • agent.confidence.low - Response confidence below threshold

Feedback Events:

  • feedback.received - User rated conversation
  • feedback.comment - User left detailed feedback
Example Event Payload
{
  "id": "evt_abc123",
  "type": "message.received",
  "timestamp": "2024-03-14T10:30:00Z",
  "data": {
    "conversationId": "conv_123",
    "messageId": "msg_456",
    "userId": "user_789",
    "content": "I need help with my order",
    "sentiment": "neutral",
    "intent": "order_inquiry",
    "confidence": 0.89
  }
}

Integration Examples

Example 1: Sync to CRM (HubSpot) Automatically create CRM contacts when new conversations start:

CRM Sync
async function handleNewConversation(eventData) {
  const { userId, email, name, conversationId } = eventData;
  
  // Create or update contact in HubSpot
  await hubspot.contacts.create({
    email: email,
    properties: {
      firstname: name,
      lastname: '',
      chatbot_conversation_id: conversationId,
      lead_source: 'AI Chatbot',
      lifecycle_stage: 'lead'
    }
  });
  
  console.log(`Created HubSpot contact for ${email}`);
}

Integration Examples (continued)

Example 2: E-commerce Order Status Let customers check order status via chatbot:

Order Status Lookup
app.post('/webhooks/bravin', async (req, res) => {
  const event = req.body;
  
  if (event.type === 'message.received') {
    const message = event.data.content.toLowerCase();
    
    // Check if asking for order status
    if (message.includes('order') && message.includes('status')) {
      // Extract order number from message
      const orderMatch = message.match(/#?(\d{5,})/);
      
      if (orderMatch) {
        const orderNumber = orderMatch[1];
        
        // Look up order in your system
        const order = await getOrderStatus(orderNumber);
        
        // Send response via Bravin API
        await axios.post(
          `https://api.bravin.ai/v1/conversations/${event.data.conversationId}/messages`,
          {
            content: `Your order #${orderNumber} is ${order.status}. Estimated delivery: ${order.estimatedDelivery}`,
            role: 'assistant'
          },
          {
            headers: { 'Authorization': `Bearer ${process.env.BRAVIN_API_KEY}` }
          }
        );
      }
    }
  }
  
  res.status(200).send('OK');
});

Rate Limits and Best Practices

Rate Limits:

  • Free Plan: 100 requests/hour
  • Pro Plan: 1,000 requests/hour
  • Enterprise Plan: 10,000 requests/hour

Best Practices:

  1. Implement Exponential Backoff

    • Retry failed requests with increasing delays
    • Max 3 retries
  2. Cache Responses

    • Cache frequently accessed data (e.g., knowledge base)
    • TTL: 5-15 minutes
  3. Batch Requests

    • Use batch endpoints when available
    • Example: /conversations/batch for multiple conversations
  4. Monitor Usage

    • Check X-RateLimit-Remaining header
    • Set up alerts before hitting limits
  5. Use Webhooks

    • Don't poll for updates
    • Webhooks are real-time and don't count toward rate limits

Contact sales for custom rate limits if you need higher throughput.

Troubleshooting

Common Issues:

1. 401 Unauthorized

  • Check API key is correct
  • Verify key hasn't expired
  • Ensure Bearer prefix in Authorization header

2. 429 Rate Limit Exceeded

  • Implement exponential backoff
  • Upgrade plan for higher limits
  • Batch requests where possible

3. Webhook Not Receiving Events

  • Verify URL is publicly accessible (not localhost)
  • Check firewall allows Bravin AI IPs
  • Ensure endpoint returns 200 OK
  • Verify signature validation logic

4. 500 Server Error

  • Check status page: status.bravin.ai
  • Review request payload for validity
  • Contact support if persistent

Debug Mode: Enable verbose logging in your API client:

Never log API keys or sensitive data in production!

Debug Logging
axios.interceptors.request.use(request => {
  console.log('Starting Request', JSON.stringify(request, null, 2));
  return request;
});

axios.interceptors.response.use(response => {
  console.log('Response:', JSON.stringify(response.data, null, 2));
  return response;
});

Was this guide helpful?