Skip to content

Embed Widget API Reference ​

REST API Endpoints ​

Create Embed Token ​

Create a new embed token for your widget.

POST /embed/create

Authentication: Required (Bearer token)

Request Body:

FieldTypeRequiredDescription
agentIdstringAt least oneText chat agent ID
voiceAgentIdstringAt least oneVoice/bidi agent ID
allowedDomainsstring[]NoDomain allowlist (default: ["localhost"])
modestringNo"text", "voice", or "both" (auto-detected from agents)
greetingstringNoGreeting message
colorstringNoBrand color hex (default: "#6366f1")
positionstringNo"bottom-right" or "bottom-left"
agentNamestringNoDisplay name in widget header
titlestringNoHeader title (overrides agentName display)
subtitlestringNoSecondary text under the title (e.g., "Powered by AI")
logoUrlstringNoURL of circular avatar image in header
initialPromptstringNoAuto-sent to agent on first load — agent's reply becomes the opening message
placeholderstringNoInput box placeholder text (default: "Ask me anything...")
sizestringNoWidget size: "compact" (340×480), "standard" (400×580), "large" (440×640)
autoOpenbooleanNoAuto-open widget panel on page load (default: false)
autoOpenDelaynumberNoDelay in milliseconds before auto-open (default: 0, max: 30000)
rateLimitPerDaynumberNoMax requests per day (default: 1000)
rateLimitPerIpnumberNoMax requests per IP (default: 10)
minutesLimitnumberNoVoice minutes limit (null = unlimited)
creditLimitnumberNoCredit usage limit (null = unlimited)

TIP

You must provide at least one of agentId or voiceAgentId. Providing both enables the dual-mode widget with text/voice toggle tabs.

Response:

json
{
  "data": {
    "embedTokenId": "emb-a1b2c3d4-...",
    "embedToken": "emb_pk_live_...",
    "agentId": "text-agent-uuid",
    "voiceAgentId": "voice-agent-uuid",
    "allowedDomains": ["yourdomain.com", "localhost"],
    "config": {
      "greeting": "Hi! How can I help?",
      "color": "#6366f1",
      "position": "bottom-right",
      "mode": "both",
      "agentName": "AI Assistant"
    },
    "snippet": "<script src=\"https://cdn.universalapi.co/embed/widget.js\"\n  data-text-agent=\"text-agent-uuid\"\n  data-voice-agent=\"voice-agent-uuid\"\n  data-token=\"emb_pk_live_...\"\n  async></script>",
    "status": "active"
  }
}

Get Widget Config ​

Fetch widget configuration for a given embed token. This is a public endpoint — no user auth required. Validates the token and Origin header.

GET /embed/config?token=emb_pk_live_...

Response:

json
{
  "data": {
    "agentId": "text-agent-uuid",
    "voiceAgentId": "voice-agent-uuid",
    "agentName": "AI Assistant",
    "greeting": "Hi! How can I help?",
    "color": "#6366f1",
    "position": "bottom-right",
    "mode": "both"
  }
}

List Embed Tokens ​

List all embed tokens for the authenticated user.

GET /embed/list

Authentication: Required

Response:

json
{
  "data": {
    "tokens": [
      {
        "embedTokenId": "emb-a1b2c3d4-...",
        "tokenPrefix": "emb_pk_live_",
        "agentId": "text-agent-uuid",
        "voiceAgentId": "voice-agent-uuid",
        "allowedDomains": ["yourdomain.com"],
        "config": { ... },
        "minutesUsed": 12.5,
        "minutesLimit": null,
        "status": "active",
        "createdAt": 1714000000
      }
    ],
    "count": 1
  }
}

Update Embed Token ​

Update settings for an existing embed token.

PUT /embed/{embedTokenId}

Authentication: Required

Request Body (all fields optional):

FieldTypeDescription
allowedDomainsstring[]New domain allowlist
rateLimitPerDaynumberNew daily rate limit
rateLimitPerIpnumberNew per-IP rate limit
configobjectUpdated widget config (greeting, color, mode, etc.)
statusstring"active" or "revoked"

Delete (Revoke) Embed Token ​

Soft-delete an embed token. The widget stops working immediately.

DELETE /embed/{embedTokenId}

Authentication: Required


Embed Chat (Streaming Credentials) ​

Get streaming credentials for text chat. The widget calls this internally.

POST /embed/chat

Request Body:

json
{
  "token": "emb_pk_live_...",
  "context": { "siteId": "acme", "plan": "pro" },
  "endUserId": "customer-42"
}

context (optional, JSON object up to 4 KB) and endUserId (optional, up to 128 characters) belong to this visitor's session. They come from the visitor's browser, so they reach MCP servers only as the untrusted client part of the signed session context. Usage is broken down per endUserId in GET /embed/{id}/usage.

Owner-minted session (trusted context) ​

POST /embed/{embedTokenId}/session      (owner auth)
{ "context": { "tenant": "acme" }, "endUserId": "cust-42", "ttlSeconds": 3600 }

Call this from your site's backend for a signed-in visitor, then pass data.bearerToken to the widget (data-session-token="uapi_es_..." or UniversalAPIWidget.setSessionToken(token)). Its context and endUserId are trusted: they are signed into the session context as ctx and endUserId. ttlSeconds: 60–86400 (default 3600).

Response:

json
{
  "data": {
    "agentId": "text-agent-uuid",
    "bearerToken": "uapi_es_...",
    "streamUrl": "https://stream.api.universalapi.co/agent/{agentId}/chat"
  }
}

The widget uses these credentials to stream directly from the agent API. The uapi_es_* session token lasts one hour and only works for chatting with the widget owner's agents and for MCP calls. It never grants access to the owner's account. Revoking the embed token ends its sessions.

Errors: when the widget's allowance, lifetime limit or credit pool is used up, the endpoint (and the stream API) answers 402; when one visitor sends more than rateLimitPerIp messages in a minute, it answers 429.

json
{ "error": "This widget has used its credit allowance for this period",
  "code": "allowance_exhausted", "resets_at": "2026-12-01T00:00:00Z", "period": "2026-11-01" }

Codes: allowance_exhausted, credit_limit_reached, minutes_limit_reached, pool_empty, rate_limited.


Limits, allowance and model pin ​

POST /embed/create and PUT /embed/{embedTokenId} accept:

FieldTypeDescription
allowanceobject or nullPer-period budget: { "credits": 5000, "voiceMinutes": 60, "period": "month", "resetDay": 1, "webhookUrl": "https://..." }. period is "month" (reset on resetDay, 1–28, UTC) or "day". Resets automatically.
creditLimitnumber or nullLifetime credit cap for this widget
minutesLimitnumber or nullLifetime voice-minute cap
rateLimitPerIpnumberChat messages per visitor IP per minute (default 10)
modelIdstring or nullModel used for every chat through this widget, e.g. claude-haiku-latest (applies to agents that read BEDROCK_MODEL_ID)
sessionContextobject or nullDefault session context (4 KB) when the page sends none
poolIdstring or nullCredit pool that pays for this widget's usage

Webhook: when usage crosses 80 % and 100 % of the allowance, UniversalAPI POSTs { "type": "embed.allowance.threshold", "threshold": 80, "usage": {...} } once per period. Verify X-UAPI-Signature: v1=<hex> as HMAC-SHA256 of "<X-UAPI-Timestamp>." + body with the webhookSecret returned when you set webhookUrl.

Get Embed Usage ​

GET /embed/{embedTokenId}/usage[?period=2026-10-01]
json
{
  "data": {
    "period": { "id": "2026-11-01", "type": "month", "start": "2026-11-01T00:00:00Z", "resets_at": "2026-12-01T00:00:00Z" },
    "creditsUsed": 812.4, "creditsRemaining": 4187.6,
    "voiceMinutesUsed": 12, "voiceMinutesRemaining": 48, "turns": 230,
    "perEndUser": { "customer-42": { "credits": 31.2, "voiceMinutes": 0, "turns": 9 } },
    "lifetime": { "creditsUsed": 9120.3, "creditLimit": null, "voiceMinutesUsed": 140, "voiceMinutesLimit": null },
    "pool": { "poolId": "pool-...", "name": "acme", "balance": 12000 }
  }
}

Credit pools ​

Move credits from your balance into a named pool, then attach pools to embed tokens. A pooled widget's usage is charged to the pool, not your balance, so you can bundle "N edits a month" into your own plan while keeping one funded UniversalAPI account. No Stripe involved.

MethodPathBodyDescription
POST/pools{ "name", "credits" }Create a pool, moving credits from your balance
GET/pools—List your pools
GET/pools/{poolId}—Pool balance
POST/pools/{poolId}/allocate{ "credits" }Move more credits in
POST/pools/{poolId}/release{ "credits" } (all if omitted)Move credits back to your balance
DELETE/pools/{poolId}—Delete; the remaining balance returns to you
POST/embed/{embedTokenId}/allowance{ "credits" } or { "poolId" }Fund this widget's own pool (created on first use) or attach an existing pool

Not enough balance answers 402 with code: "insufficient_credits".


Script Tag Attributes ​

AttributeTypeRequiredDescription
data-text-agentstringAt least oneText chat agent ID
data-voice-agentstringAt least oneVoice/bidi agent ID
data-tokenstringYesEmbed token (emb_pk_live_...)
data-modestringNoOverride mode: "text", "voice", "both"
data-positionstringNo"bottom-right" (default) or "bottom-left"
data-colorstringNoBrand color hex
data-greetingstringNoGreeting text (shown as static first bubble in text mode)
data-titlestringNoHeader title (overrides agent name)
data-subtitlestringNoSecondary text under the title
data-logostringNoURL of circular avatar image in header
data-initial-promptstringNoAuto-sent to agent on load — response is opening message
data-placeholderstringNoInput box placeholder text
data-sizestringNo"compact", "standard" (default), "large"
data-default-tabstringNoWhich tab to show first in "both" mode: "text" (default) or "voice"
data-auto-openstringNoAuto-open the widget panel on page load. Any value (or empty) enables; "false" or "0" disables
data-auto-open-delaystringNoDelay in milliseconds before auto-opening (default: "0", max: "30000")
data-contextJSON stringNoSession context for this page (≤ 4 KB), forwarded to the agent and its MCP servers
data-end-user-idstringNoYour id for the signed-in visitor; usage is reported per end user
data-persist-conversationstringNo"session" keeps the conversation across page reloads (sessionStorage)
data-session-tokenstringNoA session minted by your backend with POST /embed/{id}/session (trusted context)

Auto-Open Reliability

The data-auto-open attribute uses a two-phase timing strategy (requestAnimationFrame + setTimeout) that ensures the widget opens after the page has fully rendered. This avoids race conditions with cookie consent banners, chat widgets, and other elements that compete for attention on page load. Use data-auto-open-delay to add extra time if needed (e.g., "1500" to wait 1.5 seconds for consent banners to finish animating).


JavaScript API (window.UniversalAPIWidget) ​

Methods ​

MethodArgumentsDescription
open()—Open the widget panel
close()—Close the widget panel
switchTo(tab)"text" or "voice"Switch active tab (only in "both" mode)
on(event, callback)event name, functionRegister event listener
getMode()—Returns "text", "voice", or "both"
getActiveTab()—Returns "text" or "voice"
isReady()—Returns true after widget has initialized
setContext(obj)objectSet this page's session context (next message starts a new session)
setEndUserId(id)stringSet the end-user id
setSessionToken(token)stringUse a session minted by your backend
getConversationId()—Current conversation id
resetConversation()—Start a new conversation (clears the persisted one)

Properties ​

PropertyTypeDescription
versionstringWidget version (e.g., "3.0.0")

Events ​

EventDataDescription
ready—Widget has loaded and is ready
open—Panel was opened
close—Panel was closed
voiceStart—Voice WebSocket connected, mic active
voiceEnd—Voice session ended
transcript{ text, role, is_final }Voice transcript received
limit{ status, error }Allowance or rate limit reached (402 / 429)

Universal API - The agentic entry point to the universe of APIs