Справочник API
Создавайте собственные интеграции с REST API Asyntai
Требуется платный план: Доступ к 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.
Аутентификация
Все API-запросы требуют аутентификации с помощью вашего API-ключа. Получить API-ключ можно на странице Настройки API.
Включите ваш API-ключ в запросы одним из следующих способов:
- Заголовок авторизации (рекомендуется):
Authorization: Bearer YOUR_API_KEY - Заголовок X-API-Key:
X-API-Key: YOUR_API_KEY
Храните ваш API-ключ в тайне. Любой, кто имеет ваш ключ, может получить доступ к аккаунту через API. Никогда не раскрывайте его в клиентском коде.
Базовый URL
https://asyntai.com/api/v1/
Конечные точки
POST /chat/
Отправьте сообщение и получите ответ, сгенерированный ИИ.
Тело запроса
{
"message": "What are your business hours?",
"session_id": "user_123", // optional
"website_id": 1 // optional
}
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
message |
строка | Да | Сообщение пользователя для отправки ИИ |
session_id |
строка | Нет | Уникальный идентификатор разговора. Используйте одинаковый session_id для сохранения истории переписки. |
website_id |
целое число | Нет | Конкретный 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 |
строка | Required. The website address, for example example.com |
name |
строка | 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 |
строка | 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 |
строка | 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 |
строка | Да | ID сессии для получения истории |
limit |
целое число | Нет | Максимальное количество сообщений для возврата (по умолчанию: 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/
Список ваших недавних сессий чата. Используйте это для поиска идентификаторов сессий, которые затем можно передать в /conversations/ для получения полной истории сообщений.
Параметры запроса
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
limit |
целое число | Нет | Количество недавних сессий для возврата (по умолчанию: 20, макс: 100) |
website_id |
строка | Нет | Фильтровать сессии по конкретному ID сайта |
source |
строка | Нет | Фильтр по источнику сессии: 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 |
целое число | Нет | Количество лидов для возврата (по умолчанию: 50, макс: 100) |
website_id |
строка | Нет | Фильтровать лиды по конкретному 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 |
строка | ID чат-сессии. Передайте его в /conversations/, чтобы увидеть полную историю чата. |
email |
строка или null | Адрес электронной почты, предоставленный посетителем, или null если не был собран |
phone |
строка или null | Номер телефона, предоставленный посетителем, или null если не был собран |
page_url |
строка или null | URL страницы, на которой посетитель общался в чате |
started_at |
строка | Временная метка 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"
Несколько сайтов? Конечные точки базы знаний по умолчанию привязаны к вашему основному сайту. Если у вас несколько сайтов, передайте website_id для указания конкретного. Идентификаторы сайтов можно найти с помощью GET /websites/.
Ежедневные лимиты загрузки: Загрузки в базу знаний (текст, URL, таблицы) ограничены суточным лимитом символов в зависимости от вашего тарифа. Это ограничение распространяется на весь контент, загруженный через все конечные точки базы знаний за день.
| Тариф | Символов/день |
|---|---|
| Starter | 300 000 |
| Standard | 1 500 000 |
| Pro | 6 000 000 |
GET /knowledge/
Список записей базы знаний. Это источники контента, которые ваш ИИ-чат-бот использует для ответов на вопросы.
Параметры запроса
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
limit |
целое число | Нет | Количество записей для возврата (по умолчанию: 50, макс.: 100) |
website_id |
строка | Нет | Фильтровать по 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/
Добавьте пользовательский текстовый контент в вашу базу знаний. ИИ будет использовать его для ответов на вопросы посетителей.
Тело запроса
{
"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 |
строка | Да | Заголовок для этой записи базы знаний |
content |
строка | Да | Текстовое содержимое (минимум 10 символов) |
website_id |
строка | Нет | Целевой сайт (по умолчанию — основной сайт) |
Ответ
{
"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/
Добавьте веб-страницу в вашу базу знаний. Содержимое будет загружено и извлечено автоматически.
Тело запроса
{
"url": "https://example.com/faq",
"website_id": "123"
}
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
url |
строка | Да | URL для получения содержимого |
website_id |
строка | Нет | Целевой сайт (по умолчанию — основной сайт) |
Ответ
{
"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) в базу знаний. Каждая строка становится отдельной записью — идеально для каталогов товаров, FAQ, прайс-листов и справочников.
Запрос
Отправляйте как multipart/form-data (загрузка файла), а не JSON.
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
file |
файл | Да | Файл .csv или .xlsx. Первая строка должна содержать заголовки столбцов. Максимум строк за загрузку: Starter — 500, Standard — 2 000, Pro — 10 000. Лишние строки обрезаются. |
website_id |
строка | Нет | Целевой сайт (по умолчанию — основной сайт) |
Ответ
{
"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 можно найти в ответе 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 |
ИИ инициировал передачу разговора живому оператору |
takeover.started |
Живой агент взял управление сессией чата |
Тело запроса
{
"url": "https://example.com/webhook",
"events": ["message.received", "escalation.requested"],
"website_id": "123"
}
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
url |
строка | Да | HTTPS URL для получения POST-запросов вебхука |
events |
массив | Да | Список событий для подписки (см. таблицу выше) |
website_id |
строка | Нет | Целевой сайт (по умолчанию — основной сайт) |
Ответ
{
"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 можно найти в ответе 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 |
Сервис недоступен — сервис ИИ временно недоступен |
Ограничения по запросам
Использование API ограничено вашим тарифом:
- Free: 100 сообщений/месяц
- Starter ($39/мес.): 2 500 сообщений/месяц
- Standard ($139/мес.): 15 000 сообщений/месяц
- Pro ($449/мес.): 50 000 сообщений/месяц
Нужна помощь?
Если у вас есть вопросы или возникли проблемы, свяжитесь с нами по адресу [email protected].