Довідник API
Створюйте власні інтеграції з Asyntai REST API
Потрібен платний тариф: Доступ до API доступний на тарифах Starter, Standard та Pro. Переглянути ціни
Огляд
The Asyntai API allows you to integrate AI-powered customer support into any application. Send messages and receive intelligent responses grounded in your website content and knowledge base.
Автентифікація
Усi запити API потребують автентифiкацiї за допомогою вашого ключа API. Ви можете отримати ключ API на сторiнцi Налаштування API.
Додайте ваш ключ API до запитів одним з цих методів:
- Заголовок Authorization (рекомендовано):
Authorization: Bearer YOUR_API_KEY - Заголовок X-API-Key:
X-API-Key: YOUR_API_KEY
Зберігайте ваш ключ API в таємниці. Будь-хто з вашим ключем може отримати доступ до вашого облiкового запису через API. Нiколи не показуйте його в клiєнтському кодi.
Базова URL-адреса
https://asyntai.com/api/v1/
Кінцеві точки
POST /chat/
Надішліть повідомлення та отримайте відповідь, згенеровану ШI.
Тіло запиту
{
"message": "What are your business hours?",
"session_id": "user_123", // optional
"website_id": 1 // optional
}
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
message |
string | Так | Повідомлення користувача для надсилання ШI |
session_id |
string | Ні | Унiкальний iдентифiкатор розмови. Використовуйте той самий session_id для збереження iсторiї розмови. |
website_id |
integer | Ні | Конкретний ID сайту. Якщо не вказано, використовується ваш основний сайт. |
Відповідь
{
"success": true,
"response": "Our business hours are Monday-Friday, 9 AM to 5 PM EST.",
"session_id": "user_123"
}
Приклад (cURL)
curl -X POST https://asyntai.com/api/v1/chat/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"message": "What are your business hours?", "session_id": "user_123"}'
Приклад (Python)
import requests
response = requests.post(
"https://asyntai.com/api/v1/chat/",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json={
"message": "What are your business hours?",
"session_id": "user_123"
}
)
data = response.json()
print(data["response"])
Приклад (JavaScript)
const response = await fetch("https://asyntai.com/api/v1/chat/", {
method: "POST",
headers: {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify({
message: "What are your business hours?",
session_id: "user_123"
})
});
const data = await response.json();
console.log(data.response);
GET /websites/
Список усіх сайтів, пов'язаних з вашим обліковим записом.
Відповідь
{
"success": true,
"websites": [
{
"id": 1,
"name": "My Website",
"domain": "example.com",
"is_primary": true
}
]
}
Приклад (cURL)
curl https://asyntai.com/api/v1/websites/ \
-H "Authorization: Bearer YOUR_API_KEY"
POST /websites/
Create a new AI agent. This does the same thing as adding a website in your dashboard: it makes the agent, reads your site, and writes the first draft of the AI instructions.
Use this to set up customers from your own software. You get back the widget ID and the code to put on the website.
Тіло запиту
| Поле | Тип | Опис |
|---|---|---|
domain |
string | Required. The website address, for example example.com |
name |
string | Optional. A display name for the agent. Useful when one website has several agents. |
crawl |
boolean | Optional, true by default. Set it to false to create the agent without reading the website. Nothing is crawled and no instructions are written. |
force |
boolean | Optional, false by default. Set it to true to add a website you already have. The copy is stored with a number after it. |
Відповідь
{
"success": true,
"website": {
"id": 42,
"domain": "example.com",
"name": "Support agent",
"widget_id": "asyntai_ab12cd34ef56",
"is_primary": true,
"crawl_started": true,
"instructions_status": "generating",
"job_id": "8f2c1e90-..."
},
"embed_code": "<script>...</script>"
}
Приклад (cURL)
curl -X POST https://asyntai.com/api/v1/websites/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"domain": "example.com", "name": "Support agent"}'
Reading a website takes a few minutes, so this call answers straight away. Check when the agent is ready with the next endpoint.
Errors
| Code | Meaning |
|---|---|
403 |
You have reached the number of websites your plan allows. The answer tells you the limit. |
409 |
Your account already has this website. Send force as true to add it again. |
GET /websites/{id}/
Get one website and see whether it is ready. Use this after you create an agent, to wait until the website has been read and the AI instructions are written.
Відповідь
{
"success": true,
"website": {
"id": 42,
"domain": "example.com",
"name": "Support agent",
"widget_id": "asyntai_ab12cd34ef56",
"is_primary": true,
"created_at": "2026-08-11T09:12:00+00:00",
"ready": true,
"instructions": {
"status": "completed",
"has_instructions": true,
"characters": 3421
},
"crawl": {
"job_id": "8f2c1e90-...",
"status": "completed",
"pages_crawled": 47,
"pages_found": 50,
"max_pages": 50,
"completed_at": "2026-08-11T09:15:31+00:00",
"error": ""
},
"knowledge_items": 47
},
"embed_code": "<script>...</script>"
}
The ready field is true when nothing is still running. A crawl that failed also counts as ready, because it has finished. Look at the crawl status to see what happened.
Приклад (cURL)
curl https://asyntai.com/api/v1/websites/42/ \
-H "Authorization: Bearer YOUR_API_KEY"
GET PATCH /websites/{id}/settings/
Read or change the chat widget settings for one website. These are the same settings you see on the Customize page: colours, the name of the assistant, the first message, lead capture, and everything else.
Reading the settings
A GET request returns every setting with its current value, plus a locked list. Locked shows the settings your plan cannot change, and which plans they need.
{
"success": true,
"settings": {
"ai_support_name": "AI Assistant",
"widget_color": "#6366f1",
"initial_message": "Hi, how can I help you?",
"hide_branding": false,
"...": "..."
},
"locked": {
"hide_branding": ["pro", "enterprise"],
"widget_style": ["pro", "enterprise"]
}
}
Changing the settings
A PATCH request changes only the settings you send. Everything you leave out stays as it is.
curl -X PATCH https://asyntai.com/api/v1/websites/42/settings/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"ai_support_name": "Ava", "widget_color": "#0f172a", "use_emoji": true}'
{
"success": true,
"updated": ["ai_support_name", "use_emoji", "widget_color"],
"settings": { "...": "..." },
"locked": { "...": "..." }
}
Plans
Each setting needs its own plan, the same as in the dashboard. For example, hiding the Asyntai branding needs the Pro plan, and voice input needs Standard.
| Plan needed | Налаштування | Examples |
|---|---|---|
| Any paid plan | 25 | widget_color, ai_support_name, initial_message |
| Starter та вище | 22 | profile_picture, conversation_starters_enabled |
| Standard та вище | 25 | speech_to_text_enabled, image_vision_enabled, escalation_enabled |
| Pro | 6 | hide_branding, widget_style |
If you send a setting your plan does not allow, the whole request is refused with code 403 and nothing is saved. The same happens if any value is wrong, for example a colour that is not a hex code. Your settings never end up half changed.
GET PUT /websites/{id}/instructions/
Read or replace the AI instructions for one website. These are the rules that tell the assistant who it is, what it may say, and what it must not say. They are the same instructions you edit in the dashboard.
Reading
{
"success": true,
"instructions": "You are the support agent for Acme Tools...",
"characters": 1979,
"version": 7,
"mode": "instructions",
"ask_questions": true,
"generation_status": "completed",
"being_edited_by": null
}
Replacing
A PUT request replaces the whole text, the same as saving in the dashboard. There is no append mode. To add a paragraph, read the instructions, add your text, then write it back.
curl -X PUT https://asyntai.com/api/v1/websites/42/instructions/ \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"instructions": "You are the support agent for Acme Tools...", "version": 7}'
Тіло запиту
| Поле | Тип | Опис |
|---|---|---|
instructions |
string | Required. The complete new text. It replaces everything that was there. |
version |
number | Optional but recommended. The version you read. If somebody changed the instructions since then, your write is refused instead of overwriting their work. |
mode |
string | Optional. Either instructions or general. |
ask_questions |
boolean | Optional. Whether the assistant asks a follow-up question at the end of its answers. |
force |
boolean | Optional, false by default. Needed only when your new text is less than half the length of the current text. |
How your instructions are protected
Instructions can take hours to write, so a write can be refused to protect them:
| Code | Meaning |
|---|---|
400 |
Your new text is less than half the length of the current text. This catches a script that sends empty or cut-off text over instructions somebody spent hours on. Send force as true if you meant it. |
409 |
The instructions changed after you read them. Read them again, apply your change, then write. |
423 |
Somebody is editing the instructions in the dashboard right now. The answer tells you who. Try again in a couple of minutes. |
Every change also saves a copy of the previous text, so an earlier version can always be restored from the dashboard.
GET /conversations/
Отримати історію розмови для конкретного сеансу.
Параметри запиту
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
session_id |
string | Так | ID сеансу для отримання історії |
limit |
integer | Ні | Максимальна кількість повідомлень для повернення (за замовчуванням: 50, макс: 100) |
Відповідь
{
"success": true,
"session_id": "user_123",
"messages": [
{
"role": "user",
"content": "What are your business hours?",
"timestamp": "2024-01-15T10:30:00Z"
},
{
"role": "assistant",
"content": "Our business hours are Monday-Friday, 9 AM to 5 PM EST.",
"timestamp": "2024-01-15T10:30:01Z",
"sender_type": "ai",
"agent_name": null,
"response_time_ms": 1840.5
}
]
}
Запитання та відповідь на нього зберігаються в одному записі, тому обидва мають однаковий timestamp. Не віднімайте одне від одного, щоб виміряти швидкість відповіді, бо результат завжди буде нульовим. Використовуйте response_time_ms — це реальний час відповіді в мілісекундах.
sender_type дорівнює ai, коли відповів чат-бот, і human, коли чат перебрав один із ваших операторів. agent_name містить відображуване ім'я цього оператора.
Приклад (cURL)
curl "https://asyntai.com/api/v1/conversations/?session_id=user_123&limit=20" \
-H "Authorization: Bearer YOUR_API_KEY"
GET /sessions/
Список ваших останнiх сеансiв чату. Використовуйте це для виявлення ID сеансiв, якi потiм можна передати до /conversations/ для отримання повної iсторiї повiдомлень.
Параметри запиту
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
limit |
integer | Ні | Кількість останніх сеансів для повернення (за замовчуванням: 20, макс: 100) |
website_id |
string | Ні | Фільтрувати сеанси за конкретним ID сайту |
source |
string | Ні | Фільтр за джерелом сесії: widget, api, whatsapp, instagram, messenger, gorgias, freshchat, zapier |
Відповідь
{
"success": true,
"sessions": [
{
"session_id": "session_abc123def",
"source": "widget",
"message_count": 5,
"first_message": "What are your business hours?",
"first_message_at": "2024-01-15T10:30:00Z",
"last_message_at": "2024-01-15T10:35:00Z",
"first_response_time_ms": 1840.5,
"first_human_response_at": null,
"started_at": "2024-01-15T10:29:58Z",
"ended_at": "2024-01-15T10:41:12Z",
"taken_over_at": null,
"website_domain": "example.com"
}
]
}
Поля міток часу для звітності
| Поле | Опис |
|---|---|
started_at |
Коли відвідувач відкрив чат. Доступно лише для сеансів віджета, бо сеанси, створені через API, ніколи не відкривають віджет. |
first_message_at |
Коли було збережено перше повідомлення розмови. |
first_response_time_ms |
Скільки часу зайняла перша відповідь, у мілісекундах. Використовуйте це для часу першої відповіді. |
first_human_response_at |
Коли один із ваших операторів надіслав першу відповідь. Значення дорівнює null, коли чат-бот вів усю розмову. |
taken_over_at |
Коли оператор перебрав чат у чат-бота. |
last_message_at |
Коли було збережено останнє повідомлення розмови. |
ended_at |
Коли відвідувач залишив чат. Чат не має стану «вирішено» чи «закрито», бо відвідувач завжди може повернутися і поставити інше запитання. |
Усі мітки часу подано в UTC та у форматі ISO 8601. Часовий пояс змінити не можна. Перетворіть значення у власному інструменті звітності.
Приклад (cURL)
curl "https://asyntai.com/api/v1/sessions/?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
GET /leads/
Отримати зібрані ліди — адреси електронної пошти та номери телефонів, надіслані відвідувачами під час чат-розмов.
Параметри запиту
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
limit |
integer | Ні | Кількість лідів для повернення (за замовчуванням: 50, макс: 100) |
website_id |
string | Ні | Фільтрувати ліди за конкретним ID веб-сайту |
Відповідь
{
"success": true,
"leads": [
{
"session_id": "session_abc123def",
"email": "[email protected]",
"phone": "+1234567890",
"page_url": "https://example.com/pricing",
"started_at": "2024-01-15T10:30:00Z"
}
]
}
| Поле | Тип | Опис |
|---|---|---|
session_id |
string | ID чат-сесії. Передайте його в /conversations/, щоб побачити повну історію чату. |
email |
рядок або null | Адреса електронної пошти, надана відвідувачем, або null якщо не була зібрана |
phone |
рядок або null | Номер телефону, наданий відвідувачем, або null якщо не був зібраний |
page_url |
рядок або null | URL сторінки, де відвідувач спілкувався в чаті |
started_at |
string | Мітка часу ISO 8601 початку чат-сесії |
Приклад (cURL)
curl "https://asyntai.com/api/v1/leads/?limit=20" \
-H "Authorization: Bearer YOUR_API_KEY"
Приклад (Python)
import requests
response = requests.get(
"https://asyntai.com/api/v1/leads/",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={"limit": 20}
)
leads = response.json()["leads"]
for lead in leads:
print(f"{lead['email'] or ''} | {lead['phone'] or ''}")
GET /account/
Отримати інформацію про ваш обліковий запис та статистику використання.
Відповідь
{
"success": true,
"account": {
"email": "[email protected]",
"plan": "starter",
"messages_used": 150,
"messages_limit": 2500
}
}
Приклад (cURL)
curl https://asyntai.com/api/v1/account/ \
-H "Authorization: Bearer YOUR_API_KEY"
Декілька сайтів? Кiнцевi точки бази знань за замовчуванням використовують ваш основний сайт. Якщо у вас декiлька сайтiв, передайте website_id для вибору конкретного. Ви можете знайти ID ваших сайтів за допомогою GET /websites/.
Щоденні ліміти завантаження: Завантаження в базу знань (текст, URL, таблицi) мають щоденний лiмiт символiв залежно вiд вашого тарифу. Це стосується загального обсягу контенту, завантаженого через усi кiнцевi точки бази знань за день.
| Тариф | Символів/день |
|---|---|
| Starter | 300 000 |
| Standard | 1 500 000 |
| Pro | 6 000 000 |
GET /knowledge/
Список записiв вашої бази знань. Це джерела контенту, якi ваш ШI-чатбот використовує для вiдповiдей на запитання.
Параметри запиту
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
limit |
integer | Ні | Кількість записів для повернення (за замовчуванням: 50, макс.: 100) |
website_id |
string | Ні | Фільтрувати за ID сайту (за замовчуванням - ваш основний сайт) |
Відповідь
{
"success": true,
"entries": [
{
"id": "abc-123-def",
"type": "text",
"title": "Business Hours",
"description": "Manual text content (150 words)",
"created_at": "2024-01-15T10:30:00Z"
},
{
"id": "ghi-456-jkl",
"type": "url",
"title": "About Us - Example",
"description": "Content from https://example.com/about",
"created_at": "2024-01-14T09:00:00Z"
}
]
}
Приклад (cURL)
curl "https://asyntai.com/api/v1/knowledge/?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
POST /knowledge/text/
Додайте власний текстовий контент до вашої бази знань. ШI буде використовувати це для вiдповiдей на запитання вiдвiдувачiв.
Тіло запиту
{
"title": "Return Policy",
"content": "We offer a 30-day return policy on all items. Items must be unused and in original packaging. Refunds are processed within 5-7 business days.",
"website_id": "123"
}
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
title |
string | Так | Назва для цього запису бази знань |
content |
string | Так | Текстовий контент (мін. 10 символів) |
website_id |
string | Ні | Цільовий сайт (за замовчуванням - ваш основний сайт) |
Відповідь
{
"success": true,
"id": "abc-123-def",
"title": "Return Policy",
"chunks_created": 1
}
Приклад (cURL)
curl -X POST "https://asyntai.com/api/v1/knowledge/text/" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"title": "Return Policy", "content": "We offer a 30-day return policy..."}'
POST /knowledge/url/
Додайте веб-сторiнку до вашої бази знань. Контент буде автоматично завантажено та вилучено.
Тіло запиту
{
"url": "https://example.com/faq",
"website_id": "123"
}
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
url |
string | Так | URL-адреса для завантаження контенту |
website_id |
string | Ні | Цільовий сайт (за замовчуванням - ваш основний сайт) |
Відповідь
{
"success": true,
"id": "abc-123-def",
"title": "FAQ - Example",
"url": "https://example.com/faq",
"chunks_created": 5
}
Приклад (cURL)
curl -X POST "https://asyntai.com/api/v1/knowledge/url/" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/faq"}'
POST /knowledge/spreadsheet/
Завантажте таблицю CSV або Excel (.xlsx) до вашої бази знань. Кожен рядок стає окремим записом бази знань, iдеально пiдходить для каталогiв товарiв, спискiв FAQ, таблиць цiн та довiдникiв.
Запит
Надсилайте як multipart/form-data (завантаження файлу), а не JSON.
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
file |
file | Так | Файл .csv або .xlsx. Перший рядок повинен мiстити заголовки стовпцiв. Макс. рядкiв на завантаження: Starter 500, Standard 2 000, Pro 10 000. Зайвi рядки обрiзаються. |
website_id |
string | Ні | Цільовий сайт (за замовчуванням - ваш основний сайт) |
Відповідь
{
"success": true,
"id": "abc-123-def",
"title": "products.csv",
"rows_processed": 15,
"chunks_created": 15
}
Приклад (cURL)
curl -X POST "https://asyntai.com/api/v1/knowledge/spreadsheet/" \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "[email protected]"
GET /knowledge/{id}/
Прочитайте один запис бази знань разом із текстом, збереженим для нього. Значення id береться з відповіді GET /knowledge/.
Вміст повертається для записів, які додали ви: тексту, файлів, таблиць, окремих URL-адрес і відео. Обхід сайту показано у списку, але його сторінки не повертаються, оскільки джерелом є ваш власний публічний сайт. У такому разі content дорівнює null, а поле reason пояснює причину.
Відповідь
{
"success": true,
"id": "abc-123-def",
"type": "text",
"title": "Business Hours",
"description": "Manual text content (150 words)",
"created_at": "2024-01-15T10:30:00Z",
"chunks_count": 3,
"content": "We are open Monday to Friday, 9am to 5pm...",
"content_available": true,
"char_count": 43
}
Приклад (cURL)
curl "https://asyntai.com/api/v1/knowledge/abc-123-def/" \
-H "Authorization: Bearer YOUR_API_KEY"
DELETE /knowledge/{id}/
Видалити запис бази знань. id можна знайти у вiдповiдi GET /knowledge/.
Відповідь
{
"success": true,
"message": "Knowledge base entry deleted"
}
Приклад (cURL)
curl -X DELETE "https://asyntai.com/api/v1/knowledge/abc-123-def/" \
-H "Authorization: Bearer YOUR_API_KEY"
Порада: Ви також можете керувати вебхуками з Налаштування API сторінки без написання коду.
GET /webhooks/
Список ваших зареєстрованих вебхуків.
Відповідь
{
"success": true,
"webhooks": [
{
"id": "abc-123-def",
"url": "https://example.com/webhook",
"events": ["message.received", "escalation.requested"],
"is_active": true,
"created_at": "2024-01-15T10:30:00Z"
}
]
}
Приклад (cURL)
curl "https://asyntai.com/api/v1/webhooks/" \
-H "Authorization: Bearer YOUR_API_KEY"
POST /webhooks/
Зареєструйте новий вебхук для отримання сповіщень про події в режимі реального часу.
Доступні події
| Подія | Опис |
|---|---|
message.received |
Відвідувач надіслав повідомлення та отримав відповідь |
conversation.started |
Розпочато новий сеанс чату |
escalation.requested |
ШI ініціював ескалацію до живого оператора |
takeover.started |
Живий оператор перехопив сеанс чату |
Тіло запиту
{
"url": "https://example.com/webhook",
"events": ["message.received", "escalation.requested"],
"website_id": "123"
}
| Параметр | Тип | Обов'язковий | Опис |
|---|---|---|---|
url |
string | Так | HTTPS URL-адреса для отримання POST-запитів вебхуків |
events |
array | Так | Список подій для підписки (див. таблицю вище) |
website_id |
string | Ні | Цільовий сайт (за замовчуванням - ваш основний сайт) |
Відповідь
{
"success": true,
"webhook": {
"id": "abc-123-def",
"url": "https://example.com/webhook",
"events": ["message.received", "escalation.requested"],
"secret": "whsec_abc123...",
"created_at": "2024-01-15T10:30:00Z"
}
}
Перевірка вебхуків: Кожен вебхук містить secret (показується лише при створенні). Кожен POST на вашу URL-адресу містить X-Webhook-Signature заголовок — HMAC-SHA256 тіла запиту, підписаний вашим секретним ключем.
Приклад (cURL)
curl -X POST "https://asyntai.com/api/v1/webhooks/" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/webhook", "events": ["message.received"]}'
DELETE /webhooks/{id}/
Видалити вебхук. id можна знайти у вiдповiдi GET /webhooks/.
Відповідь
{
"success": true,
"message": "Webhook deleted"
}
Приклад (cURL)
curl -X DELETE "https://asyntai.com/api/v1/webhooks/abc-123-def/" \
-H "Authorization: Bearer YOUR_API_KEY"
Відповіді з помилками
Усі відповіді з помилками мають такий формат:
{
"success": false,
"error": "Error message describing what went wrong"
}
| Код стану | Опис |
|---|---|
400 |
Невірний запит - Невалідні параметри або відсутні обов'язкові поля |
401 |
Не авторизовано - Невалідний або відсутній ключ API |
429 |
Занадто багато запитів - Досягнуто ліміту повідомлень для вашого тарифу |
503 |
Сервіс недоступний - Сервіс ШI тимчасово недоступний |
Обмеження частоти запитів
Використання API обмежене вашим тарифним планом:
- Free: 100 повідомлень/місяць
- Starter ($39/міс.): 2 500 повідомлень/місяць
- Standard ($139/міс.): 15 000 повідомлень/місяць
- Pro ($449/міс.): 50 000 повідомлень/місяць
Потрібна допомога?
Якщо у вас є запитання або виникли проблеми, зв'яжiться з нами за адресою [email protected].