Developers

API Reference

Every action in the dashboard is available over a JSON REST API. Authenticate once, send a Bearer token, and drive agents, chat, sources, CRM, analytics, and billing programmatically.

Base URL & conventions

All endpoints are served under /api on your instance host.

https://aisnsio-aisnschatwebsite.hf.space/api
  • Requests and responses are JSON (Content-Type: application/json), except CSV export and file-download endpoints.
  • Most write endpoints accept an agent selector as ?agent=<id> (query) or agentId (body). Omit it to use the workspace's first agent.
  • Upload endpoints under /api/sources accept up to 12 MB JSON (base64 file); all other routes cap at 1 MB.
  • Unknown /api/* paths return 404 {"error":"Unknown API route"}.

Authentication

Auth is a JWT (HS256, 30-day expiry) tied to your user + workspace. Obtain it by registering or logging in, then send it on every request.

The token is returned in the JSON body and set as an httpOnly cookie (aisns_token). The body token exists so the app works inside the Hugging Face iframe, where third-party cookies are blocked. Send it as Authorization: Bearer <token> — the Bearer header takes precedence over the cookie.

1. Get a token

curl -s -X POST https://aisnsio-aisnschatwebsite.hf.space/api/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"you@example.com","password":"••••••••"}'
# → { "user": { … }, "token": "eyJhbGciOi…" }

2. Call an authenticated endpoint

TOKEN="eyJhbGciOi…"
curl -s https://aisnsio-aisnschatwebsite.hf.space/api/agents \
  -H "Authorization: Bearer $TOKEN"

3. Send a chat message

curl -s -X POST https://aisnsio-aisnschatwebsite.hf.space/api/chat \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"agentId":1,"message":"How do refunds work?"}'
# → { "reply":"…", "conversationId":42, "engine":"live+rag", "credits": 1990 }
Password changes and admin resets bump an internal token_version, which instantly invalidates all previously issued tokens for that user. Two-factor (TOTP) can be required at login (see /api/auth/2fa/*). Note: workspace "API keys" (sk_live_*) can be generated in the dashboard for your records, but the current release authenticates with the JWT above — programmatic key auth is on the roadmap.
MethodEndpointAuthBody / notes
POST/api/auth/registerpublicemail, password (≥6), name?{user, token}
POST/api/auth/loginpublicemail, password, code? (2FA){user, token}
POST/api/auth/logoutpublicClears the session cookie.
GET/api/auth/mebearer/cookieCurrent session: {user, workspace, billing, impersonator}
POST/api/auth/forgotpublicemail — always {ok:true} (no account enumeration).
POST/api/auth/resetpublictoken, password — logs out all sessions.
POST/api/auth/2fa/setupbearer{secret, otpauth} (provision TOTP).
POST/api/auth/2fa/enable · /disablebearercode — turn 2FA on/off.
GET/api/auth/2fa/statusbearer{enabled}
PATCH/api/auth/themebearertheme (light|dark)

Errors & status codes

Errors are JSON: {"error":"message"}. Common codes:

CodeMeaning
400Bad request — missing/invalid field.
401Not authenticated — no/expired/invalid token.
402Billing required — subscription paused or out of credits.
403Forbidden — suspended account, wrong role, or admin-only.
404Not found — or not owned by your workspace.
409Conflict — e.g. email already registered.
429Rate limited — see Retry-After.

Rate limits

ScopeLimit
Auth (register / login / forgot / reset)20 per 5 min per IP
Public widget chat & lead capture30 per min per IP
Authenticated chat /api/chat60 per min per workspace

Agents & training

MethodEndpointBody / queryDescription
GET/api/agentsList workspace agents with conversation/source/lead counts.
POST/api/agentsname*, model?, system_prompt?, emoji, color, status, avatar_url, companyName, websiteCreate an agent (auto public_id + agent_email + default persona).
GET/api/agents/:idFetch a single agent.
PATCH/api/agents/:idname, model, temperature, system_prompt, welcome_message, visibility, status, emoji, color, avatar_urlUpdate agent fields.
DEL/api/agents/:idDelete an agent (cascades sources/conversations).
POST/api/agents/:id/testmessage*, instructions?, model?, temperature?Playground test with optional unsaved overrides → {reply, engine}.
POST/api/agents/:id/trainRe-index all sources; bumps last_trained_at.
GET/api/agents/:id/sourcesList the agent's knowledge sources.
POST/api/agents/:id/sourcestype*, name*, contentAdd + index a source.
DEL/api/agents/:id/sources/:sidRemove a source.
GET/api/agents/default-promptcompany, websiteBuild a default persona prompt.
GET/api/agents/prompt-libraryReady-made persona genres.
GET/api/agents/company-infourlScrape a site/social page for name, bio, logo.

All routes above require Authorization: Bearer and are scoped to your workspace.

Chat

MethodEndpointBody / queryDescription
POST/api/chatagentId, message*, conversationId?, stream?; ?stream=1 for SSEMain chat turn. Billing + credit gated (402 when out of credits). Captures leads/contacts, detects handoff, fires webhooks. Returns {reply, conversationId, engine, credits, creditCost, captured} or an SSE stream.

Knowledge sources

MethodEndpointBody / queryDescription
GET/api/sourcestype?, agentList sources (optionally filtered by type).
GET/api/sources/summaryagentKB size + training-status breakdown.
GET/api/sources/:idagentOne source with full content.
POST/api/sourcestype*, name, content, url, question, answer, dataBase64, mime, sizeKbAdd a source. Files → text-extracted (PDF/DOCX); websites → async crawl; text/Q&A → indexed.
POST/api/sources/socialurl*, platform?Train on a public social profile's bio; borrows the avatar.
PATCH/api/sources/:idname, content, question, answerEdit + re-index a source.
POST/api/sources/retrainagentRe-index all of an agent's sources.
DEL/api/sources/:idagentDelete + de-index a source.

Conversations & inbox

MethodEndpointBody / queryDescription
GET/api/conversationslimit, channel, agentList conversations.
GET/api/conversations/inboxagentShared inbox ordered by handoff need.
GET/api/conversations/:cidOne conversation + its messages.
POST/api/conversations/:cid/replytext*Human operator reply; takes over the conversation; delivers to Slack/WhatsApp.
PATCH/api/conversations/:cid/handoffaction (takeover|resolve|bot)Change handoff state.
PATCH/api/conversations/:cid/messages/:midfeedback (up|down|null)Thumbs on a single reply.
POST/api/conversations/:cid/messages/:mid/correctanswer*Save a corrected answer as a trained Q&A source.
PATCH/api/conversations/:cidfeedbackConversation-level thumbs.
DEL/api/conversations/:cidDelete one conversation.
DEL/api/conversationsagentDelete all conversations for an agent.
GET/api/conversations/channelsagentDistinct channels (filter dropdown).
GET/api/conversations/feedback-statsagentThumbs up/down rate.
GET/api/conversations/export.csvagentCSV export (≤5000).

Analytics & dashboard

MethodEndpointQueryDescription
GET/api/dashboard/overviewWorkspace KPIs + recent conversations.
GET/api/dashboard/usageMessages used vs tier allowance + per-agent breakdown.
GET/api/analytics/chatsagentVolume stats, 7-day series, top countries.
GET/api/analytics/topicsagentTopic buckets from first messages.
GET/api/analytics/sentimentagentPositive / neutral / negative breakdown.

AI advisor (Synthia)

Synthia analyzes the whole workspace and answers questions about growing the fleet. Replies (narrative + chat) are generated in the caller's UI language — pass lang (e.g. ja, fr, ar).

MethodEndpointAuthDescription
GET/api/assistant/analysis?lang=<code>bearerFleet health score, KPIs, rule-based recommendations, and an LLM narrative written in lang.
POST/api/assistant/chatbearerChat with Synthia. Body: { message, history, lang, attachments[] } — images/files as base64 data URLs (16 MB limit).

Contacts

MethodEndpointBody / queryDescription
GET/api/contactssearch, sort, dir, limit, page, agentPaginated contact search.
POST/api/contactsexternal_id, email, name, phoneCreate a contact.
PATCH/api/contacts/:cidexternal_id, email, name, phoneUpdate a contact.
DEL/api/contacts/:cidDelete a contact.
GET/api/contacts/exportagentCSV export.

Leads

MethodEndpointBody / queryDescription
GET/api/leadssearch, status, sort, dir, limit, pagePaginated / filtered leads.
GET/api/leads/statsagentPer-status pipeline counts.
POST/api/leadsname, email, phone, company, status, score, source, notesCreate a lead.
PATCH/api/leads/:lidsame fieldsUpdate a lead.
DEL/api/leads/:lidDelete a lead.
GET/api/leads/export.csvagentCSV export (≤5000).

Custom attributes

MethodEndpointBody / queryDescription
GET/api/attributesagentList custom contact attributes.
POST/api/attributesname*, type, label, descriptionCreate an attribute.
DEL/api/attributes/:idDelete an attribute.

Widget & builder

MethodEndpointBody / queryDescription
GET/api/widgetagentWidget config + ready-to-paste embed snippet.
PUT/api/widgetagent; ~19 config fieldsUpdate widget appearance/behaviour.
GET/api/widgetsagentList interactive builder widgets.
GET/api/widgets/:idOne builder widget.
POST/api/widgetsname, code, schema, functions, states, modeCreate a builder widget.
PATCH/api/widgets/:idsame fieldsUpdate a builder widget.
DEL/api/widgets/:idDelete a builder widget.

Channels & actions

MethodEndpointBody / queryDescription
GET/api/channelsagentDeploy-channel catalog + per-agent state (secrets stripped).
POST/api/channels/:channel/connectchannel credsConnect a channel (credentials live-validated).
POST/api/channels/:channel/testRe-validate stored channel credentials.
PATCH/api/channels/:channelenabled, configToggle / configure / disconnect a channel.
GET/api/actionsagentAction catalog + enabled/config state.
POST/api/actions/:type/toggleenabledEnable/disable an action.
POST/api/actions/:type/configconfig, enabled?Save action config.

Integrations

MethodEndpointBodyDescription
GET/api/integrationsConnector catalog + connection state (no secrets).
POST/api/integrations/:provider/connectprovider fieldsValidate credentials live and store encrypted.
POST/api/integrations/:provider/testRe-validate stored credentials.
POST/api/integrations/:provider/disconnectRemove a connection.

Webhooks (outbound)

Register HTTPS endpoints to receive events. Deliveries are signed so you can verify authenticity. Only public HTTPS URLs are accepted (SSRF-guarded).

MethodEndpointBody / queryDescription
GET/api/webhooksagentList webhooks.
POST/api/webhooksurl*, events*[]Create a webhook (e.g. leads.submit, message.created, handoff.requested).
POST/api/webhooks/:id/testSend a sample event.
DEL/api/webhooks/:idDelete a webhook.

Custom domains

MethodEndpointBody / queryDescription
GET/api/domainsagentList domains + the CNAME target to point at.
POST/api/domainsdomain*Add a custom domain (status = checking).
POST/api/domains/:id/refreshVerify the CNAME via DNS lookup.
DEL/api/domains/:idDelete a domain.

Agent settings

MethodEndpointBody / queryDescription
GET/api/settingsagentFull settings: general, ai, voice, security, helpdesk, emails, notifications.
PATCH/api/settingsagent; any settings sectionUpdate one or more settings sections.

Campaigns (outbound) Beta

MethodEndpointBody / queryDescription
GET/api/campaignsagentList campaigns + status counts.
POST/api/campaignsname*, channel, repliesMode, templateId, audienceCreate a campaign.
POST/api/campaigns/:id/sendMark a campaign sent.
GET/api/campaigns/templatesagentList templates.
POST/api/campaigns/templatesname*, type, bodyCreate a template.

Workspace & members

MethodEndpointBody / queryDescription
GET/api/workspace/generalWorkspace record.
PATCH/api/workspace/generalname, tierRename / change tier.
GET/api/workspace/membersList members.
POST/api/workspace/membersemail*, roleInvite a member (seat-limited; emails an invite).
PATCH/api/workspace/members/:midroleChange a member's role.
DEL/api/workspace/members/:midRemove a member.
GET/api/workspace/api-keysList API keys (secret not shown).
POST/api/workspace/api-keysnameCreate a key — full secret returned once.
DEL/api/workspace/api-keys/:kidDelete a key.

Billing & credits

MethodEndpointAuthDescription
GET/api/billing/pricingpublicPublic credit-bundle pricing.
GET/api/billing/walletbearerCurrent credit balance.
GET/api/billing/subscriptionbearerSubscription / trial status + plans.
POST/api/billing/checkoutbearerCreate a Stripe Checkout session for a bundle.
POST/api/billing/checkout/confirmbearerConfirm a paid session (idempotent credit grant).
POST/api/billing/subscribebearerStart a recurring subscription (Stripe/PayPal).
POST/api/billing/paypal/confirmbearerConfirm a PayPal subscription.
POST/api/billing/payment-methodbearerRegister a payment method → start free trial.
POST/api/billing/auto-rechargebearerConfigure auto-recharge threshold + bundle.
POST/api/billing/cancelbearerCancel the subscription; pause the bot.

/api/billing/webhook (Stripe) and /api/billing/paypal/webhook are provider callbacks — see Inbound webhooks.

Affiliate program

Referral links, campaign tracking, KYC + payouts, and brand creatives. Affiliates earn 10% of the fees their referred workspaces pay (USD accounting), with a 60-day cookie attribution window. Mutating calls require an editor (workspace owner or member).

MethodEndpointAuthDescription
GET/api/affiliatebearerEnrollment state + full dashboard (code, link, stats, tier, links, referrals, payouts, config).
POST/api/affiliate/enrolleditorJoin the program. Body: { displayName, socials, agree:true }.
PATCH/api/affiliateeditorUpdate profile: { displayName, socials, promoCode, notify }.
POST/api/affiliate/linkseditorCreate a named campaign link. Body: { name, channel }.
DEL/api/affiliate/links/:ideditorDelete a campaign link (the primary link cannot be deleted).
POST/api/affiliate/payout-methodeditorSet payout method. Body: { method:'paypal'|'crypto', dest, network }.
POST/api/affiliate/kyceditorUpload a government ID (base64 image/PDF). Sets KYC to pending for admin review.
POST/api/affiliate/payouteditorRequest a payout. Requires admin-verified KYC + payout method; $50 minimum. Body: { amount }.
GET/api/affiliate/leaderboardbearerTop 10 affiliates by earnings + the caller's rank.
GET/api/affiliate/assetsbearerBrand kit: colors, logo URLs, and personalized creative specs with captions + hashtags.

Public referral links /r/<code> record a click, set a 60-day aff_ref cookie, and redirect to the app. KYC verification + payout processing are operator actions under Admin.

Support

MethodEndpointBodyDescription
GET/api/support/ticketsYour tickets + categories.
POST/api/support/ticketssubject*, message*, category, priorityOpen a ticket.
GET/api/support/tickets/:idTicket + thread (owner or admin).
POST/api/support/tickets/:id/messagesbody*Reply on a ticket.

Public widget API no auth

These power the embeddable widget and are keyed by an agent's public id — no Bearer token. CORS-open, rate-limited per IP.

MethodEndpointBody / queryDescription
GET/api/public/:publicIdNon-secret widget config (name, welcome, colors, suggestions).
POST/api/public/:publicId/chatmessage (≤4000), conversationId?Anonymous chat vs a public agent. Billing/credit gated; captures leads; handoff detection.
POST/api/public/:publicId/leadname, email, phone, noteCapture a lead from the widget form.
GET/api/public/:publicId/pollconversationId, afterPoll for new operator messages since after.
GET/api/configNon-secret platform UI config.
GET/api/content/:pageLanding-page CMS content.
GET/api/healthLiveness + DB check.

Inbound webhooks signature-verified

These receive events from third parties. They verify a provider signature over the raw request body — do not send them yourself.

MethodEndpointVerificationDescription
POST/api/slack/eventsSlack HMAC (5-min replay guard)Slack Events API — DM/@mention → reply posted back.
GET/api/whatsapp/webhookverify_tokenMeta subscription handshake.
POST/api/whatsapp/webhookMeta HMAC (x-hub-signature-256)Inbound WhatsApp messages → reply via graph/relay.
POST/api/billing/webhookStripe HMAC (stripe-signature)Stripe subscription / payment events.
POST/api/billing/paypal/webhookPayPal verification APIPayPal subscription events.

Admin operator only

The entire /api/admin/* surface and /api/backups/* require an admin account (requireAdmin). These are for the platform operator (株式会社フリーボーン), not tenant integrations — listed here for completeness.

AreaEndpoints
Revenue & statsGET /api/admin/revenue, /stats, /activity, /llm-diagnostics
UsersGET/PATCH/DELETE /api/admin/users/:id, /password, /credits, /role, /subscription, /edit-session, /impersonate
Workspaces & agentsGET /api/admin/workspaces, /agents; PATCH/DELETE /api/admin/agents/:id
Content (CMS)GET/PUT /api/admin/content, POST /content/reset
Platform settings & bundlesGET/PUT /api/admin/settings, /bundles
TicketsGET /api/admin/tickets, PATCH /tickets/:id
AffiliatesGET /api/admin/affiliates, GET /affiliates/:id/kyc-doc, POST /affiliates/:id/kyc, GET /affiliate-payouts, POST /affiliate-payouts/:id
BackupsGET /api/admin/backup; GET/POST /api/backups, GET /api/backups/download/:name

Questions?

See the getting-started guide, or reach a human on the contact page.