ChatbotAssistant

Chatbot API Documentation

This documentation contains the complete API specification for integration with our chatbot system. The API enables creating custom integrations, managing chat sessions, and processing messages. Each endpoint is described in detail, along with request and response examples, allowing for quick implementation.

Important Prerequisites: To use the API, you need an active account on the ChatbotAssistant platform and an API key, which can be generated in the admin panel.
0

Integration Process Overview

Integration with the chatbot API is a process consisting of several key stages that will enable smooth connection of your application with our system.

  1. Configuration and Authentication - preparing the chatbot in the ChatbotAssistant panel and obtaining the API key.
  2. Understanding the Workflow - familiarizing yourself with the asynchronous communication model based on webhooks.
  3. Endpoint Implementation - using the API to create sessions and send messages.
  4. Response Handling - creating a webhook endpoint to receive and verify responses from the chatbot.
  5. Applying Best Practices - implementing recommendations for security, performance, and error handling.
Implementation Time: The time needed for full integration depends on the complexity of your system, but with this documentation you should be able to implement basic integration within a few hours.
1

Authentication

All API requests require authentication using an API key. The key can be found and generated in API settings.

Authentication Header

The API key should be passed in the HTTP header X-API-Key:

X-API-Key: your-api-key
API Key Security: Protect your API key! Do not publish it in public code repositories or share it with unauthorized persons. The API key provides full access to your account and all chatbots associated with it.

API Key Management

You can manage your API keys in the admin panel:

  1. Generating new API keys
  2. Revoking access for compromised keys
2

Chatbot Configuration

In this section, you will learn how to create and configure a new chatbot on the ChatbotAssistant platform based on our API.

Configuration Steps:

  1. On the side menu, find and click the section Create Chatbot, select the option Manual Configuration, or go to the section Dashboard, then select Create New Chatbot
  2. In the chatbot creation panel, in the section Select Chatbot Features check the option API Integration
  3. You can also check the feature Website Widget during configuration API Integration
  4. Fill out the chatbot creation form by entering the following information:
    • Chatbot Name - enter the chatbot name that users will see, e.g. Customer Support
    • Description (optional) - will help you find the right chatbot
    • Company Information - enter detailed information about your company, products, services, prices, opening hours, etc. The more information you provide, the better the chatbot will respond to customer questions.
    • Allowed Domains (for website widget option) - provide your website domain, e.g. example.com (without https://). If you have more than one domain or subdomain, enter all of them separated by commas. (NOT RECOMMENDED) Leave the field empty to allow all domains.
  5. At the bottom of the form, you will see a section called API Configuration, where you must provide the address Webhook URL of your page. This is the address where chatbot responses will be sent in API mode
  6. After filling in all the fields necessary for the chatbot to function, click the button Create Chatbot
  7. Now it will be possible to obtain Webhook Secret. To find the secret, go to the section Dashboard and find the chatbot created in the previous steps
  8. You will find the webhook secret in the section Options, then Webhook Settings or by clicking the button Edit and going to the bottom of the page
Tip: Completing company information in a complete and detailed manner is a key factor in determining whether the customer will receive a correct and detailed answer to their question.

Generating a New Webhook Secret:

At any time you can generate a new webhook secret. Just:

  1. Go to the section Dashboard, find the specific chatbot, click Options, then Webhook Settings.
  2. Under the section Webhook Secret check the box Generate new webhook secret and confirm the operation with the button Save Changes.
  3. After saving the changes, a new webhook secret will be automatically generated and visible in the webhook settings panel.
Attention!: Generating a new webhook secret will invalidate all existing integrations using the current secret.

Webhook Configuration

The webhook URL must meet the following requirements:

  • Must use HTTPS protocol
  • Must be accessible from the internet (cannot be a private address)
  • Must respond with 200 OK code to POST requests
  • Should handle signature headers for verification
Webhook URL: Each chatbot can have its own unique webhook URL. This allows you to direct responses from different chatbots to different systems or endpoints.
3

API Workflow

The API enables integration of the chatbot with your application or system. A typical workflow looks as follows:

  1. Authentication - using the API key in the request header
  2. Create Chat Session - initiating a new conversation with the chatbot
  3. Sending User Messages - passing the message content to the chatbot
  4. Receiving Chatbot Response via Webhook - processing the asynchronous response

All requests and responses use JSON format.

Data Flow Diagram

Data Flow Diagram API
Asynchronous Communication: Chatbot responses are delivered asynchronously through webhooks, which means your application must be ready to receive HTTP requests from our server.
4

API Endpoints

The chatbot API provides the following main endpoints:

Endpoint Method Description
/api/chatbot/{chatbot_id}/session POST Creating a new chat session
/api/chatbot/{chatbot_id}/send POST Sending user messages to the chatbot

Below you will find detailed specifications for each endpoint, along with request and response examples.

5

Create Chat Session

POST /api/chatbot/{chatbot_id}/session

This endpoint creates a new chat session for a specific chatbot. A session is required to send messages and must be stored on the client side.

Path Parameters

ParameterTypeDescriptionRequired
chatbot_idStringChatbot identifierYes

Request Headers

HeaderValueDescriptionRequired
X-API-KeyStringYour API key for authenticationYes
Content-Typeeapplication/jsonRequest Data FormatYes

Request Parameters (body)

ParameterTypeDescriptionRequired
webhook_dataObjectAny JSON data that will be passed back in the webhookNo
client_idStringClient identifier for trackingNo

Example Request

{
  "webhook_data": {
    "conversation_id": "conv-456",
    "department": "sales",
    "custom_field": "value"
  },
  "client_id": "user_12345"
}

Responses

200 OK
{
  "success": true,
  "session": {
    "token": "abc123def456"
  },
  "webhook": {
    "url": "https://your-backend.com/webhooks/chatbot",
    "secret": "secret123"
  }
}
400 Bad Request
{
  "success": false,
  "error": "Invalid request parameters"
}
401 Unauthorized
{
  "success": false,
  "error": "Invalid API key"
}
404 Not Found
{
  "success": false,
  "error": "Chatbot not found"
}
Session Token: Save the session token, you will need it to send messages. The session token is valid for 24 hours from the last activity.

Try It Out

6

Sending Messages

POST/api/chatbot/{chatbot_id}/send

This endpoint sends a message from the user to the chatbot. The chatbot's response will be delivered asynchronously through the previously configured webhook.

Path Parameters

ParameterTypeDescriptionRequired
chatbot_idStringChatbot identifierYes

Request Headers

HeaderValueDescriptionRequired
X-API-KeyStringYour API key for authenticationYes
Content-Typeeapplication/jsonRequest Data FormatYes

Request Parameters (body)

ParameterTypeDescriptionRequired
sessionStringSession token returned during its creationYes
messageStringUser message contentYes
webhook_dataObjectAny JSON data that will be passed back in the webhookNo

Example Request

{
  "session": "abc123def456",
  "message": "Good morning, I have a question.",
  "webhook_data": {
    "message_reference": "msg-789",
    "context": "homepage"
  }
}

Responses

200 OK
{
  "success": true,
  "message_id": 456
}
400 Bad Request
{
  "success": false,
  "error": "Missing required parameter: message"
}
401 Unauthorized
{
  "success": false,
  "error": "Invalid session token"
}
429 Too Many Requests
{
  "success": false,
  "error": "Rate limit exceeded",
  "retry_after": 60
}
Asynchronous Processing: The message will be processed asynchronously. The chatbot's response will be delivered through the webhook.

Try It Out

7

Receiving Responses via Webhook

After the message is processed by the chatbot, the response will be sent to the configured webhook URL. The webhook will receive the following data format:

Webhook Data Format

{
  "id": 457,
  "role": "assistant",
  "content": "Good morning! How can I help?",
  "timestamp": "2026-04-10T15:23:45.123456",
  "session_token": "abc123def456",
  "chatbot_id": 123,
  "webhook_data": {
    "conversation_id": "conv-456",
    "department": "sales",
    "message_reference": "msg-789",
    "context": "homepage",
    "custom_field": "value"
  }
}

Webhook Response Structure:

FieldTypeDescription
idIntegerMessage identifier
roleStringMessage author role ("assistant")
contentStringAssistant response content
timestampStringTimestamp in ISO format
session_tokenStringSession Token
chatbot_idIntegerChatbot identifier
webhook_dataObjectData passed during session creation or message sending
is_errorBooleanPresent only if an error occurred during processing

Webhook Headers

The webhook contains the following headers that can be used to verify the source:

HeaderDescription
X-Signature-TimestampTimestamp in Unix format
X-Signature-HashHMAC-SHA256 signature
Content-Typeeapplication/json
User-AgentChatbotAssistant-Webhook/1.0
Webhook Response: Your server should respond with 200 OK code to confirm receipt of the webhook. You can also return JSON data, which however will not be used by the system.

Example Webhook Handling Implementation

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

const app = express();
const PORT = 3000;
const WEBHOOK_SECRET = 'secret123'; // from the admin panel

// Middleware for parsing JSON
app.use(bodyParser.json());

// Webhook endpoint
app.post('/webhooks/chatbot', (req, res) => {
  const timestamp = req.headers['x-signature-timestamp'];
  const signature = req.headers['x-signature-hash'];
  const payload = JSON.stringify(req.body);

  // Signature verification
  const expectedSignature = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(`${timestamp}.${payload}`)
    .digest('hex');

  if (signature !== expectedSignature) {
    console.error('Invalid webhook signature');
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Message processing
  const { id, role, content, session_token, webhook_data } = req.body;

  console.log(`Received message from chatbot: ${content}`);
  console.log(`Webhook Data:`, webhook_data);

  // Process the message here...

  // Confirmation of receipt
  res.status(200).json({ success: true });
});

app.listen(PORT, () => {
  console.log(`Webhook server running on port ${PORT}`);
});
from flask import Flask, request, jsonify
import hmac
import hashlib
import json

app = Flask(__name__)
WEBHOOK_SECRET = 'secret123'  # from admin panel

@app.route('/webhooks/chatbot', methods=['POST'])
def chatbot_webhook():
    # Get data and headers
    timestamp = request.headers.get('X-Signature-Timestamp')
    signature = request.headers.get('X-Signature-Hash')
    payload = request.data.decode('utf-8')

    # Signature verification
    expected_signature = hmac.new(
        WEBHOOK_SECRET.encode(),
        f"{timestamp}.{payload}".encode(),
        hashlib.sha256
    ).hexdigest()

    # Check signature
    if not hmac.compare_digest(expected_signature, signature):
        return jsonify({'error': 'Invalid signature'}), 401

    # Data processing
    data = request.json
    message_id = data.get('id')
    content = data.get('content')
    session_token = data.get('session_token')
    webhook_data = data.get('webhook_data', {})

    print(f"Received message from chatbot: {content}")
    print(f"Webhook data: {webhook_data}")

    # Message processing here...

    # Confirmation of receipt
    return jsonify({'success': True})

if __name__ == '__main__':
    app.run(port=5000, debug=True)
<?php
// Get data from request
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);

// Get headers
$timestamp = $_SERVER['HTTP_X_SIGNATURE_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_SIGNATURE_HASH'] ?? '';

// Webhook secret from admin panel
$webhookSecret = 'secret123';

// Signature verification
$expectedSignature = hash_hmac('sha256', $timestamp . '.' . $payload, $webhookSecret);

if (!hash_equals($expectedSignature, $signature)) {
    header('HTTP/1.1 401 Unauthorized');
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

// Data processing
$messageId = $data['id'] ?? null;
$content = $data['content'] ?? '';
$sessionToken = $data['session_token'] ?? '';
$webhookData = $data['webhook_data'] ?? [];

// Logging
error_log("Received message from chatbot: " . $content);
error_log("Webhook data: " . json_encode($webhookData));

// Process the message here...

// Confirmation of receipt
header('Content-Typee: application/json');
echo json_encode(['success' => true]);
?>
8

Webhook Verification

To ensure security and verify that the webhook comes from our system, we recommend checking the signature headers:

  • X-Signature-Timestamp - timestamp in Unix format
  • X-Signature-Hash - HMAC-SHA256 signature

Verification Algorithm

The signature verification algorithm consists of the following steps:

  1. Retrieve headers X-Signature-Timestamp and X-Signature-Hash from the request
  2. Retrieve the request body as a raw string (payload)
  3. Combine timestamp and payload, separating them with a dot: {timestamp}.{payload}
  4. Calculate HMAC-SHA256 of the combined string, using the webhook secret as the key
  5. Compare the calculated HMAC with the header X-Signature-Hash, using secure string comparison

Signature Verification Code Example (Python)

import hmac
import hashlib

def verify_webhook(request, webhook_secret):
    timestamp = request.headers.get('X-Signature-Timestamp')
    signature = request.headers.get('X-Signature-Hash')
    payload = request.body  # As a JSON string

    expected_signature = hmac.new(
        webhook_secret.encode(),
        f"{timestamp}.{payload}".encode(),
        digestmod=hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(expected_signature, signature)

Signature Verification Code Example (Node.js)

const crypto = require('crypto');

function verifyWebhook(req, webhookSecret) {
  const timestamp = req.headers['x-signature-timestamp'];
  const signature = req.headers['x-signature-hash'];
  const payload = JSON.stringify(req.body);

  const expectedSignature = crypto
    .createHmac('sha256', webhookSecret)
    .update(`${timestamp}.${payload}`)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(signature, 'hex')
  );
}
Security: Always verify webhook signatures to prevent spoofing attacks. Use timing-attack-resistant comparison functions such as hmac.compare_digest() in Python or crypto.timingSafeEqual() in Node.js.

Obtaining the Webhook Secret

The webhook secret used for signature verification can be obtained in two ways:

  1. It is returned during session creation in the JSON response in the webhook.secret field
  2. It can be found in the admin panel in the chatbot settings
Tip: Store the webhook secret in a secure location, such as environment variables or a secrets manager. Never place it directly in the code.
9

Webhook Data

You can pass any data in the parameter webhook_data, which will be returned in the webhook response. This is useful for:

  • Identifying which conversation the response relates to
  • Tracking business context (e.g. department, product category)
  • Routing responses to appropriate systems or users
  • Passing additional metadata to your application

How It Works

Webhook Data can be passed both during session creation and with each message sent:

  • Data passed during session creation - will be attached to all webhook responses for that session
  • Data passed during message sending - will replace session data only for the response to this specific message
Data Structure: Webhook Data must be a valid JSON object. The maximum webhook data size is 16 KB.

Use Case Examples

1. Tracking Conversation Source

{
  "webhook_data": {
    "source": "landing_page",
    "campaign": "spring_sale_2026",
    "referrer": "google"
  }
}

2. Passing User Data

{
  "webhook_data": {
    "user_id": "u-123456",
    "user_type": "registered",
    "account_level": "premium"
  }
}

3. CRM System Integration

{
  "webhook_data": {
    "crm_ticket_id": "T-78901",
    "customer_segment": "enterprise",
    "priority": "high"
  }
}
Tip: Use webhook data to pass contextual information that may be useful in processing responses, but should not be visible to the user.
10

Error Codes

The API may return the following HTTP error codes:

CodeNameDescription
400Bad RequestInvalid request parameters
401UnauthorizedMissing authentication
403ForbiddenNo access to the resource (e.g. invalid API key)
404Not FoundResource does not exist (e.g. invalid chatbot identifier)
429Too Many RequestsQuery limit exceeded
500Internal Server ErrorServer error

Error Response Format

In case of an error, the API will return a JSON response with the following structure:

{
  "success": false,
  "error": "Error description",
  "code": "ERROR_CODE" // Optional error code
}

Detailed Error Codes

Error CodeHTTPDescription
INVALID_API_KEY401Invalid API key
MISSING_PARAMETER400Missing required parameter
INVALID_SESSION401Invalid or expired session token
CHATBOT_NOT_FOUND404Chatbot with the specified identifier does not exist
RATE_LIMIT_EXCEEDED429Request limit exceeded
WEBHOOK_ERROR500Webhook-related error
SERVER_ERROR500Internal server error
Error Handling: Implement handling for all possible error codes in your application. For 429 (Too Many Requests) errors, the header Retry-After or the retry_after field in the response indicates the number of seconds after which the request can be retried.
11

Best Practices

When integrating with the chatbot API, it is worth following these best practices:

Security

  1. Verify session identifiers

    Store session identifiers in a secure location and verify they belong to the appropriate user.

  2. Always verify webhook signatures

    Webhook signatures ensure that data comes from our system and has not been modified.

  3. Use HTTPS

    All communications with the API should be conducted through HTTPS to ensure data encryption.

  4. Rotate API keys regularly

    We recommend periodic API key rotation to minimize the risk of unauthorized access.

Performance and Reliability

  1. Monitor API Usage

    Track API usage to avoid exceeding limits and identify usage patterns.

  2. Optimize webhooks

    Ensure your webhook server responds quickly to avoid timeouts. We recommend delegating heavy operations to asynchronous tasks.

Session Management

  1. Use unique client identifiers

    Parameter client_id helps in tracking sessions and troubleshooting.

  2. Store conversation context

    If necessary, save the conversation history on your side to maintain context, even if the session expires.

Integration

  1. Use webhook_data

    Parameter webhook_data allows passing business context and facilitates integration of responses with your system.

  2. Test in Development Environment

    Always test integration in a development environment before going to production.

12

Rate Limiting

Rate limiting is a mechanism that limits the number of API requests one user can make in a given time period. This protects the system from excessive load and ensures fair resource utilization for all API users.

How Rate Limiting Works:

  • Limit per User: Each user has their own limit (not shared with others)
  • Time Window: 60 seconds
  • Automatic Reset: Counter resets every minute
  • Configurable Limit: Each user can have a different limit set by the administrator

What This Means for API Requests:

When a user reaches their request limit within a minute, the API will return an error 429 Too Many Requests. The response to error 429 will include information about the time after which the request can be retried.

Example Response When Limit Exceeded:

{
      "success": false,
      "error": "Rate limit exceeded",
      "code": "RATE_LIMIT_EXCEEDED",
      "retry_after": 45
    }

Field retry_after indicates the number of seconds after which the request can be retried.

Rate Limiting and Service Quality: Rate limiting does not affect the quality of service for users in normal usage. Standard limits are set at a level that enables natural conversations while protecting against automated attacks or excessive system usage.

Handling Rate Limiting in Code:

We recommend implementing a retry mechanism in case of receiving error 429:

async function apiRequestWithRetry(url, options, maxRetries = 3) {
      for (let attempt = 0; attempt <= maxRetries; attempt++) {
        try {
          const response = await fetch(url, options);
          
          if (response.status === 429) {
            const data = await response.json();
            const retryAfter = data.retry_after || 60;
            
            if (attempt < maxRetries) {
              console.log(`Rate limit hit, retrying after ${retryAfter} seconds...`);
              await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
              continue;
            }
            throw new Error('Rate limit exceeded, max retries reached');
          }
          
          return response;
        } catch (error) {
          if (attempt === maxRetries) throw error;
        }
      }
    }
import time
    import requests
    from requests.exceptions import RequestException
    
    def api_request_with_retry(url, headers, data, max_retries=3):
        for attempt in range(max_retries + 1):
            try:
                response = requests.post(url, headers=headers, json=data)
                
                if response.status_code == 429:
                    retry_after = response.json().get('retry_after', 60)
                    
                    if attempt < max_retries:
                        print(f"Rate limit hit, retrying after {retry_after} seconds...")
                        time.sleep(retry_after)
                        continue
                    raise Exception('Rate limit exceeded, max retries reached')
                
                return response
                
            except RequestException as e:
                if attempt == max_retries:
                    raise e
<?php
    function apiRequestWithRetry($url, $headers, $data, $maxRetries = 3) {
        for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 429) {
                $responseData = json_decode($response, true);
                $retryAfter = $responseData['retry_after'] ?? 60;
                
                if ($attempt < $maxRetries) {
                    error_log("Rate limit hit, retrying after {$retryAfter} seconds...");
                    sleep($retryAfter);
                    continue;
                }
                throw new Exception('Rate limit exceeded, max retries reached');
            }
            
            return $response;
        }
    }
    ?>

Increasing Rate Limiting Limits:

If the standard rate limiting limits are not sufficient for your use case (e.g. for very high-traffic integrations or specialized applications), you can request an increase.

How to Increase Limits: To increase rate limiting limits for your API, contact the ChatbotAssistant site administration. In your message, describe your use case, expected traffic, and justification for higher limits.
Best Practices:
  • Implement retry mechanism with appropriate delay
  • Monitor response code 429 in your application
  • Respect the retry_after value returned by the API
  • Consider using queues or caching for high-traffic applications