Mobile Chat API
Connect your own app to your bot and human agents over HTTP + SSE
Integrate your own mobile (or any third-party) app with your bot and human agents. Use one of the SDKs for JavaScript, Kotlin or Swift, or call the API directly over plain HTTP + SSE. Every endpoint lives under:
https://fastcom.ascendai.site/app/api/v1/chatThe SDKs take the part before /api, https://fastcom.ascendai.site/app, as their baseUrl.
All request and response bodies are JSON.
All endpoints return 401 for invalid or expired credentials and 429 (with a Retry-After header) when rate-limited.
SDKs
The SDKs wrap every step on this page for you. They fetch and refresh session tokens, send messages and media, answer rating cards, and keep the reply stream connected. The stream reconnects on its own after a dropped network, an expired token or a server restart.
| Language | Package | Source and full guide | Runs on |
|---|---|---|---|
| JavaScript / TypeScript | @fastcom/chat on npm | fastcom-chat-js | Browsers, React Native, Node 18+ |
| Kotlin | io.github.fastcomai:fastcom-chat on Maven Central | fastcom-chat-kotlin | Android, any JVM app |
| Swift | FastcomChat, via Swift Package Manager | fastcom-chat-swift | iOS 15+, macOS 12+, tvOS 15+, watchOS 8+ |
All three are open source under the MIT license. Each repository's README is the full guide for that SDK. Each step below also shows the SDK call next to the raw HTTP request.
Each SDK takes a tokenProvider: a function that asks your backend for a session token (see Step 2).
Return the /token response unchanged, and the SDK refreshes the token before it expires.
npm install @fastcom/chatimport { ChatClient } from '@fastcom/chat';
const chat = new ChatClient({
baseUrl: 'https://fastcom.ascendai.site/app',
tokenProvider: () => fetch('/your-backend/chat-token').then((r) => r.json()),
});
const stream = chat.connect({
onMessage: (message) => render(message),
onStateChange: (state) => showConnectionState(state),
});
await chat.sendMessage('Hi, where is my order?');On your backend, ChatServer mints the token with the secret key and also covers the Agent API:
import { ChatServer } from '@fastcom/chat';
const server = new ChatServer({ baseUrl: 'https://fastcom.ascendai.site/app', secretKey: process.env.CHAT_SECRET_KEY });
app.post('/your-backend/chat-token', async (req, res) => {
res.json(await server.mintToken({ endUserId: req.user.id, endUserName: req.user.name }));
});The Kotlin and Swift SDKs cover the app side only. Keep the secret key, token minting and the Agent API on your own server.
Stopping the stream and signing out
The stream keeps reconnecting until you stop it. When the user signs out, stop the stream and drop the cached token, so the next user does not reuse it.
stream.close();
chat.clearSession();The three credentials
| Credential | Example | Where it lives | What it can do |
|---|---|---|---|
| Publishable key | pk_live_… | Inside your app binary | Mint session tokens only, and only if the low-trust flow is enabled for the app |
| Secret key | sk_live_… | Your backend only, never in the app | Mint session tokens for your authenticated users; authenticate the Agent API |
| Session token | JWT (eyJ…) | In the app, in memory | The credential actually sent on /message, /stream, /config. Expires after 30 min |
Step 1: Create a mobile app and get keys
- In the dashboard, go to Dashboard → Mobile API and click New App.
- Optionally connect a bot (its AI agent will receive every inbound message).
- Copy the two keys from the reveal dialog. The secret key is shown only once, so store it in your backend's secret manager immediately. Keys can be rotated later from the app card.
Step 2: Mint a session token
Session tokens are short-lived JWTs (30 minutes) scoped to one (org, app, endUserId).
The app never holds a long-lived secret.
Flow 1: server-minted (recommended). Your backend authenticates its user, then mints a token with the secret key and hands it to the app:
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/token \
-H "Authorization: Bearer sk_live_..." \
-H "Content-Type: application/json" \
-d '{"endUserId": "user-42", "endUserName": "Jane Doe"}'Response:
{ "token": "eyJ...", "expiresIn": 1800, "tokenType": "Bearer" }endUserId(required, ≤128 chars) is your stable user id; it keys the conversation thread.endUserName(optional, ≤256 chars) is the display name shown in the inbox.
Flow 2: publishable-only (low trust).
If you have no backend, enable Publishable-key token minting on the app card and call the same endpoint with pk_live_….
The endUserId is self-declared (treat it like an anonymous visitor id).
This flow is strictly rate-limited, the token is marked low-trust, and low-trust sessions cannot upload media.
Refresh: tokens expire after 30 minutes.
On a 401, mint a new token and retry the request.
With an SDK: pass a tokenProvider that returns your backend's /token response, as in the SDK quickstart.
For Flow 2, pass the publishable key instead.
Each SDK refuses an sk_ key here, so a secret key can never ship inside your app.
const chat = new ChatClient({
baseUrl: 'https://fastcom.ascendai.site/app',
publishableKey: 'pk_live_...',
endUserId: deviceId,
endUserName: 'Jane',
});Step 3: Send a message
Send with the session token. Org, app, and end user all come from the token, and the body carries only the content, so nothing can be spoofed:
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/message \
-H "Authorization: Bearer <session token>" \
-H "Content-Type: application/json" \
-d '{"content": "Hi, where is my order?"}'Response (201):
{ "messageId": "...", "conversationWithId": "..." }contentis required, max 4096 chars for text (413if longer).messageTypeis optional and defaults to"TEXT"; for media messages see Sending media below.- The conversation is auto-created on first message and appears in the inbox under the MOBILE platform.
- If a bot is connected and active, its AI agent is triggered automatically.
With an SDK: sendMessage in all three, as in the SDK quickstart.
Sending media (images, audio, files)
Media is a two-step flow: upload the file, then send its URL as the message.
1. Upload a multipart/form-data body with a single file field:
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/upload \
-H "Authorization: Bearer <session token>" \
-F "file=@photo.jpg"Response (201):
{ "url": "https://storage.googleapis.com/…", "messageType": "IMAGE" }2. Send the returned URL and type to /message:
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/message \
-H "Authorization: Bearer <session token>" \
-H "Content-Type: application/json" \
-d '{"content": "<url from upload>", "messageType": "IMAGE"}'Rules:
- Allowed types:
image/jpeg,image/png,image/webp,image/gif(max 10 MB each);audio/mpeg,audio/mp4,audio/x-m4a,audio/ogg,audio/wav(max 25 MB);application/pdf(max 25 MB). The returnedmessageTypeis the classified category (IMAGE | AUDIO | FILE). - File contents are verified (magic-byte sniff), not just the declared
Content-Type. A mismatch or disallowed type returns415; an oversized file returns413. - Uploads require a server-minted session token.
Low-trust (publishable-key) sessions get
403. - On
/message, a non-TEXTcontentmust be a URL previously returned by/uploadfor your org. Anything else returns400. - Uploads are limited to 10/min per end user (
429withRetry-After).
With an SDK: sendMedia uploads the file and sends it in one call.
Use upload on its own if you want the URL first.
// A File or Blob in the browser, or { uri, name, type } on React Native.
await chat.sendMedia(file);Step 4: Receive replies over SSE
Bot and human replies arrive on a Server-Sent Events stream scoped to the session's (appId, endUserId):
GET /app/api/v1/chat/stream
Authorization: Bearer <session token>Clients that can't set headers (browser EventSource) can pass the token as a query param:
const es = new EventSource(
'https://fastcom.ascendai.site/app/api/v1/chat/stream?token=' + sessionToken,
);
es.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'message') {
// { messageId, content, messageType, isFromPage, platformMessageId, timestamp }
render(data);
}
};On connect you receive { "type": "connected", "appId", "endUserId" }.
Every subsequent event with type: "message" is a reply from the business (isFromPage: true).
Bot replies and human-agent replies look identical to the app.
Reconnect with a fresh token when the stream drops.
The server sends a : heartbeat comment line every 15 seconds.
EventSource ignores it.
If you read the stream yourself, treat about 45 seconds with no bytes at all as a dead connection and reconnect, because a mobile network can drop a connection without closing it.
The SDKs do this for you.
messageType on type: "message" events can be any of TEXT | IMAGE | FILE | AUDIO | VIDEO | LINK | STICKER | EMOJI.
For media types, content is the media URL.
Render it natively: an image view for IMAGE and STICKER, an audio player for AUDIO, a download link for FILE/VIDEO.
For TEXT, LINK and EMOJI it is plain text.
Treat any type you don't recognise as plain text, so a new type never breaks your app.
When the bot splits one reply into several messages, each of those events also carries:
| Field | Meaning |
|---|---|
groupId | The same value on every message from that one reply. |
groupIndex | This message's position in the reply, starting at 0. |
groupSize | How many messages the reply has. |
The fields are absent on a reply that is a single message. Use them to draw the parts together, for example as one bubble group.
A message event may also carry an optional interaction object.
Today the only type is rating_card (see Step 4b).
If your app does not recognise an interaction.type, ignore the field and show content as usual.
With an SDK: connect (JavaScript) or events() (Kotlin and Swift), as in the SDK quickstart.
The SDK message objects carry the group fields too.
Step 4b: Rating cards (optional)
When a conversation's ticket is closed, the business can ask the customer to rate it.
If the org has turned on the rating card for mobile apps, that question arrives as a normal type: "message" event with an interaction:
{
"type": "message",
"messageId": "f3c1…",
"content": "How would you rate our support today? Reply with a number from 1 to 5.",
"messageType": "TEXT",
"isFromPage": true,
"timestamp": "2026-10-27T10:00:00.000Z",
"interaction": {
"type": "rating_card",
"title": "How did we do?",
"subtitle": "Let us know how your conversation with us went.",
"question": null,
"scoreOption": "five_stars",
"comment": true,
"submitLabel": "Rate us",
"answer": null
}
}Draw it as a small form instead of the text bubble:
| Field | Meaning |
|---|---|
title, subtitle | Headline and a line under it. |
question | An extra question line, or null for none. |
scoreOption | How to draw the five choices: five_stars (★ 1–5), one_to_five (the numbers 1–5) or five_emojis (😞 🙁 😐 🙂 😄). The score sent back is always 1–5. |
comment | true to offer an optional comment box (up to 1000 characters). |
submitLabel | The submit button's text. |
answer | null while open; { "score": 4, "comment": "…", "at": "…" } once answered. Draw an answered card as a thank-you with the score, not as a form. |
content is the plain text question.
An app version that does not draw the card shows it as an ordinary message, and the customer's typed reply is still recorded as their rating.
A card never expires.
Submit an answer
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/rating \
-H "Authorization: Bearer <session token>" \
-H "Content-Type: application/json" \
-d '{ "messageId": "f3c1…", "score": 4, "comment": "Quick and helpful" }'
# → 200 { "status": "recorded", "answer": { "score": 4, "comment": "Quick and helpful", "at": "…" } }scoreis a whole number from 1 to 5;commentis optional.200withstatus: "already_rated"means the ticket already had a score (a second tap, or a typed answer first). The body carries the score that counted; draw the card answered with it.404means no such card in this end user's conversation.400means a bad body.
After an answer is recorded, every connected stream for that end user receives { "type": "rating", "messageId": "f3c1…", "answer": { … } }, so other devices can close the card.
The business may then send a short reply for that score, which arrives as a normal message.
Find a card the app missed
The card arrives on the stream, so an app that was closed at that moment never saw it. On app open, ask for the newest unanswered card:
curl https://fastcom.ascendai.site/app/api/v1/chat/rating \
-H "Authorization: Bearer <session token>"
# → 200 { "pending": null }
# → 200 { "pending": { "messageId": "f3c1…", "sentAt": "…", "type": "rating_card", "title": "…", … } }Show pending as a card (for example at the bottom of the chat) and submit it as above.
With an SDK: the message object tells you when to draw a card, a rating event tells you another device answered it, and two calls cover the pending card and the answer.
const stream = chat.connect({
onMessage: (m) => {
if (m.interaction?.type === 'rating_card') showRatingCard(m);
else showBubble(m.content, m.messageType);
},
onRating: (e) => markCardAnswered(e.messageId, e.answer),
});
const pending = await chat.getPendingRating();
if (pending) showRatingCard(pending);
// When the user taps a score:
await chat.submitRating({ messageId, score: 5, comment: 'Great' });Step 5: Fetch app config (optional)
GET /app/api/v1/chat/config
Authorization: Bearer <session token>Returns client-safe app info, useful for deciding whether to show "AI assistant" UI:
{ "appId": "...", "name": "My App", "botConnected": true, "botActive": true }With an SDK: getConfig() in JavaScript, config() in Kotlin and Swift.
Step 6: Agent API: reply from your own platform (optional)
Your own support tooling can read threads and reply as the business without using the inbox.
Secret key only: these calls are server-to-server, and publishable keys are rejected with 403.
With an SDK: in the JavaScript SDK, each call below is a method on ChatServer, which runs on your backend (see SDKs).
The Kotlin and Swift SDKs leave the Agent API out on purpose, because the secret key must never ship inside an app.
Reply to an end user (requires that the end user has messaged first, otherwise 404):
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/agent/reply \
-H "Authorization: Bearer sk_live_..." \
-H "Content-Type: application/json" \
-d '{"endUserId": "user-42", "content": "Your order ships today."}'
# → 201 { "messageId": "...", "conversationWithId": "..." }messageType is optional (default TEXT).
To reply with media, pass messageType: "IMAGE" | "FILE" | "AUDIO" | "VIDEO" and set content to a media URL from your org's chat storage (for example one received on a message.created webhook or read back from /agent/messages).
Foreign URLs are rejected with 400.
With the JavaScript SDK:
await server.reply({ endUserId: 'user-42', content: 'Your order ships today.' });Read the thread (newest first; page back by passing the oldest createdAt you have as before):
curl "https://fastcom.ascendai.site/app/api/v1/chat/agent/messages?endUserId=user-42&limit=50" \
-H "Authorization: Bearer sk_live_..."{
"conversationWithId": "...",
"messages": [
{
"id": "...",
"content": "...",
"messageType": "TEXT",
"isFromPage": false,
"platformMessageId": "...",
"status": "DELIVERED",
"createdAt": "2026-07-18T10:00:00.000Z"
}
],
"hasMore": false
}limit is clamped to 1–100 (default 50).
Human replies sent here appear live in the inbox and are not billed as interactions.
Billing is charged when an end-user message is handed to the AI agent, so a thread a human handles costs nothing.
With the JavaScript SDK:
const page = await server.getMessages({ endUserId: 'user-42', limit: 50 });
// Older messages: pass the oldest createdAt you have.
const older = await server.getMessages({ endUserId: 'user-42', before: page.messages.at(-1)?.createdAt });Toggle the AI agent per conversation
When a human takes over a thread, mute the AI agent for just that conversation (all others keep their bot). Same secret-key auth:
curl -X POST https://fastcom.ascendai.site/app/api/v1/chat/agent/bot \
-H "Authorization: Bearer sk_live_..." \
-H "Content-Type: application/json" \
-d '{"endUserId": "user-42", "enabled": false}'
# → 200 { "conversationWithId": "...", "botEnabled": false }enabled: false: inbound messages from this end user are still persisted, streamed, and shown in the inbox, but the AI agent is no longer triggered for them.enabled: true: hand the conversation back to the AI agent.- Requires an existing conversation (
404otherwise). The flag is the same one the inbox's manual bot toggle uses, so the dashboard and this API always agree.
With the JavaScript SDK:
await server.setBotEnabled('user-42', false); // a human takes over
await server.setBotEnabled('user-42', true); // hand back to the AI agentRead the current state without changing it:
curl "https://fastcom.ascendai.site/app/api/v1/chat/agent/bot?endUserId=user-42" \
-H "Authorization: Bearer sk_live_..."
# → 200 { "conversationWithId": "...", "botEnabled": true }With the JavaScript SDK:
const { botEnabled } = await server.getBotEnabled('user-42');To get notified of new customer messages in real time instead of polling, create a webhook subscribed to the message.created event.
See Webhooks.
Billing
One interaction is consumed when an end-user message is handed to the AI agent. That is the same unit and the same moment as the social channels, which meter in their inbound webhook. Concretely:
| Situation | Charged |
|---|---|
| End-user message, AI agent connected and enabled | 1, at dispatch |
| End-user message, agent muted for the conversation, disabled, or no webhook | 0, because the agent never saw it |
| Batched bot | 1 per end-user message, at batch completion |
The agent's reply, however many items it carries | 0, already charged |
Human reply from the inbox or /agent/reply | 0 |
A run that fails or never replies is still charged: the meter is on the work being requested, not on the answer coming back.
Rate limits & errors
| Action | Limit |
|---|---|
| Token minting | 120/min per secret key, 10/min per publishable key |
| Messages | 30/min per end user |
| Uploads | 10/min per end user |
App config (/config) | 60/min per end user |
Rating cards (/rating, read and answer combined) | 20/min per end user |
| Agent API (reply + messages + bot toggle) | 300/min per key |
| New end users (app-wide) | 300/hour per app by default |
| Messages (app-wide) | 2,000/hour and 20,000/day per app by default |
The app-wide limits count the whole app, across every end user.
They exist so that an integration that creates a new endUserId for every message (a test script, or a bug) can't run up the AI bill.
A "new end user" is one with no conversation on the app yet.
Windows are UTC clock hours and UTC days.
Your app's current limits and usage are on the Mobile API page; contact support to change them.
A message refused by an app-wide limit returns 429 with {"error": "App usage limit reached", "limit": "newUsersPerHour" | "messagesPerHour" | "messagesPerDay"} and a Retry-After of the seconds left in the window.
It is not stored, not sent to the AI and not billed, and your org's owners and admins are notified.
400: invalid JSON, or a required field is missing or has the wrong type. Theerrorfield says which.401: invalid or expired credential. For session tokens, mint a new one and retry.403: wrong key type (for example a publishable key on the Agent API), publishable minting disabled, or an upload attempted with a low-trust session token.404: app inactive or deleted, or no conversation exists yet for theendUserId.413: content or file too long or too large.415: upload file type not allowed, or file contents don't match the declared type.429: rate-limited; honor theRetry-Afterheader. Alimitfield in the body means an app-wide limit (above), which resets with its window rather than in a minute.500: the server could not finish the request, for example a failed upload or a rating that could not be saved. Retry after a short wait.- Revoked or rotated keys stop working immediately.
Every error body is JSON with an error message, except /stream, which answers errors in plain text.
With an SDK: every non-2xx response throws an error carrying status, the server's message, retryAfter (seconds, on a 429) and limit (set when an app-wide cap was hit).
The SDKs refresh the token and retry once on a 401, but they do not retry a 429 for you; use retryAfter to decide when to try again.
The error type is ChatApiError in JavaScript, ChatApiException (an IOException) in Kotlin and ChatAPIError in Swift.
import { ChatApiError } from '@fastcom/chat';
try {
await chat.sendMessage(text);
} catch (err) {
if (err instanceof ChatApiError && err.status === 429) {
showRetryLater(err.retryAfter);
} else {
throw err;
}
}Endpoint summary
| Method | Path | Auth | Purpose |
|---|---|---|---|
| POST | /api/v1/chat/token | sk_… or pk_… | Mint a session token |
| POST | /api/v1/chat/message | session token | End user sends a message |
| POST | /api/v1/chat/upload | session token (server-minted) | Upload media, get back { url, messageType } |
| GET | /api/v1/chat/stream | session token (header or ?token=) | SSE stream of replies |
| GET | /api/v1/chat/config | session token | Client-safe app config |
| POST | /api/v1/chat/rating | session token | Answer a rating card |
| GET | /api/v1/chat/rating | session token | The newest unanswered rating card, if any |
| POST | /api/v1/chat/agent/reply | sk_… | External agent replies as the business |
| GET | /api/v1/chat/agent/messages | sk_… | Read thread history |
| GET | /api/v1/chat/agent/bot | sk_… | Read the per-conversation AI agent toggle |
| POST | /api/v1/chat/agent/bot | sk_… | Turn the AI agent on/off for one conversation |