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.
Table of Contents
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.
- Configuration and Authentication - preparing the chatbot in the ChatbotAssistant panel and obtaining the API key.
- Understanding the Workflow - familiarizing yourself with the asynchronous communication model based on webhooks.
- Endpoint Implementation - using the API to create sessions and send messages.
- Response Handling - creating a webhook endpoint to receive and verify responses from the chatbot.
- Applying Best Practices - implementing recommendations for security, performance, and error handling.
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 Management
You can manage your API keys in the admin panel:
- Generating new API keys
- Revoking access for compromised keys
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:
- 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
- In the chatbot creation panel, in the section Select Chatbot Features check the option API Integration
- You can also check the feature Website Widget during configuration API Integration
- 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.
- 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
- After filling in all the fields necessary for the chatbot to function, click the button Create Chatbot
- 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
- 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
Generating a New Webhook Secret:
At any time you can generate a new webhook secret. Just:
- Go to the section Dashboard, find the specific chatbot, click Options, then Webhook Settings.
- Under the section Webhook Secret check the box Generate new webhook secret and confirm the operation with the button Save Changes.
- After saving the changes, a new webhook secret will be automatically generated and visible in the webhook settings panel.
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
API Workflow
The API enables integration of the chatbot with your application or system. A typical workflow looks as follows:
- Authentication - using the API key in the request header
- Create Chat Session - initiating a new conversation with the chatbot
- Sending User Messages - passing the message content to the chatbot
- Receiving Chatbot Response via Webhook - processing the asynchronous response
All requests and responses use JSON format.
Data Flow Diagram
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.
Create Chat Session
/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
| Parameter | Type | Description | Required |
|---|---|---|---|
chatbot_id | String | Chatbot identifier | Yes |
Request Headers
| Header | Value | Description | Required |
|---|---|---|---|
X-API-Key | String | Your API key for authentication | Yes |
Content-Typee | application/json | Request Data Format | Yes |
Request Parameters (body)
| Parameter | Type | Description | Required |
|---|---|---|---|
webhook_data | Object | Any JSON data that will be passed back in the webhook | No |
client_id | String | Client identifier for tracking | No |
Example Request
{
"webhook_data": {
"conversation_id": "conv-456",
"department": "sales",
"custom_field": "value"
},
"client_id": "user_12345"
}Responses
{
"success": true,
"session": {
"token": "abc123def456"
},
"webhook": {
"url": "https://your-backend.com/webhooks/chatbot",
"secret": "secret123"
}
}{
"success": false,
"error": "Invalid request parameters"
}{
"success": false,
"error": "Invalid API key"
}{
"success": false,
"error": "Chatbot not found"
}Try It Out
Sending Messages
/api/chatbot/{chatbot_id}/sendThis 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
| Parameter | Type | Description | Required |
|---|---|---|---|
chatbot_id | String | Chatbot identifier | Yes |
Request Headers
| Header | Value | Description | Required |
|---|---|---|---|
X-API-Key | String | Your API key for authentication | Yes |
Content-Typee | application/json | Request Data Format | Yes |
Request Parameters (body)
| Parameter | Type | Description | Required |
|---|---|---|---|
session | String | Session token returned during its creation | Yes |
message | String | User message content | Yes |
webhook_data | Object | Any JSON data that will be passed back in the webhook | No |
Example Request
{
"session": "abc123def456",
"message": "Good morning, I have a question.",
"webhook_data": {
"message_reference": "msg-789",
"context": "homepage"
}
}Responses
{
"success": true,
"message_id": 456
}{
"success": false,
"error": "Missing required parameter: message"
}{
"success": false,
"error": "Invalid session token"
}{
"success": false,
"error": "Rate limit exceeded",
"retry_after": 60
}Try It Out
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:
| Field | Type | Description |
|---|---|---|
id | Integer | Message identifier |
role | String | Message author role ("assistant") |
content | String | Assistant response content |
timestamp | String | Timestamp in ISO format |
session_token | String | Session Token |
chatbot_id | Integer | Chatbot identifier |
webhook_data | Object | Data passed during session creation or message sending |
is_error | Boolean | Present only if an error occurred during processing |
Webhook Headers
The webhook contains the following headers that can be used to verify the source:
| Header | Description |
|---|---|
X-Signature-Timestamp | Timestamp in Unix format |
X-Signature-Hash | HMAC-SHA256 signature |
Content-Typee | application/json |
User-Agent | ChatbotAssistant-Webhook/1.0 |
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]);
?>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 formatX-Signature-Hash- HMAC-SHA256 signature
Verification Algorithm
The signature verification algorithm consists of the following steps:
- Retrieve headers
X-Signature-TimestampandX-Signature-Hashfrom the request - Retrieve the request body as a raw string (payload)
- Combine timestamp and payload, separating them with a dot:
{timestamp}.{payload} - Calculate HMAC-SHA256 of the combined string, using the webhook secret as the key
- 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')
);
}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:
- It is returned during session creation in the JSON response in the
webhook.secretfield - It can be found in the admin panel in the chatbot settings
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
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"
}
}Error Codes
The API may return the following HTTP error codes:
| Code | Name | Description |
|---|---|---|
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Missing authentication |
| 403 | Forbidden | No access to the resource (e.g. invalid API key) |
| 404 | Not Found | Resource does not exist (e.g. invalid chatbot identifier) |
| 429 | Too Many Requests | Query limit exceeded |
| 500 | Internal Server Error | Server 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 Code | HTTP | Description |
|---|---|---|
INVALID_API_KEY | 401 | Invalid API key |
MISSING_PARAMETER | 400 | Missing required parameter |
INVALID_SESSION | 401 | Invalid or expired session token |
CHATBOT_NOT_FOUND | 404 | Chatbot with the specified identifier does not exist |
RATE_LIMIT_EXCEEDED | 429 | Request limit exceeded |
WEBHOOK_ERROR | 500 | Webhook-related error |
SERVER_ERROR | 500 | Internal server error |
Retry-After or the retry_after field in the response indicates the number of seconds after which the request can be retried.Best Practices
When integrating with the chatbot API, it is worth following these best practices:
Security
- Verify session identifiers
Store session identifiers in a secure location and verify they belong to the appropriate user.
- Always verify webhook signatures
Webhook signatures ensure that data comes from our system and has not been modified.
- Use HTTPS
All communications with the API should be conducted through HTTPS to ensure data encryption.
- Rotate API keys regularly
We recommend periodic API key rotation to minimize the risk of unauthorized access.
Performance and Reliability
- Monitor API Usage
Track API usage to avoid exceeding limits and identify usage patterns.
- Optimize webhooks
Ensure your webhook server responds quickly to avoid timeouts. We recommend delegating heavy operations to asynchronous tasks.
Session Management
- Use unique client identifiers
Parameter
client_idhelps in tracking sessions and troubleshooting. - Store conversation context
If necessary, save the conversation history on your side to maintain context, even if the session expires.
Integration
- Use
webhook_dataParameter
webhook_dataallows passing business context and facilitates integration of responses with your system. - Test in Development Environment
Always test integration in a development environment before going to production.
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.
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.
- Implement retry mechanism with appropriate delay
- Monitor response code 429 in your application
- Respect the
retry_aftervalue returned by the API - Consider using queues or caching for high-traffic applications