> ## Documentation Index
> Fetch the complete documentation index at: https://humain.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# REST — text session setup

> Open a text session, authenticate the realtime connection, and close it — over plain HTTPS. Conversation turns themselves run over WebSocket.

## How it works

There is no REST endpoint for sending a message and getting a reply — text conversation turns
run exclusively over a WebSocket (see [WebSocket streaming](https://humain.mintlify.site/connections/websocket-streaming.md)).
HTTP is used for three things around that connection: opening the session, minting a
short-lived ticket so a browser can authenticate the WebSocket upgrade, and closing the session.

```mermaid theme={null}
sequenceDiagram
  participant D as Device
  participant S as Humain API (server)
  participant AG as Humain API (agent_url)

  D->>S: POST /v1/sessions {"mode":"text"}
  S-->>D: 201 {"session_id":"...","agent_url":"..."}

  D->>S: POST /v1/sessions/{sid}/ws-ticket
  S-->>D: 201 {"ticket":"...","expires_in":30}

  D->>AG: GET /v1/sessions/{sid}/ws?ticket=...
  AG-->>D: 101 Switching Protocols

  loop Conversation turns (over the WebSocket)
    D->>AG: {"type":"message","content":"..."}
    AG-->>D: {"type":"response","content":"...","message_id":"..."}
  end

  D->>AG: POST /v1/sessions/{sid}/end
  AG-->>D: 204
```

> [!NOTE]
>
> `agent_url` is the base URL for every real-time call — the WebSocket upgrade, and `end`. In
> most deployments it is the same public API host behind a reverse proxy; always use the value
> returned rather than assuming it matches the host you called to open the session.

The `ws-ticket` step is **only needed for browser clients** — browsers cannot set an
`Authorization` header on a WebSocket handshake. Non-browser clients (native apps, servers,
embedded devices) can skip it and send `Authorization: Bearer` directly on the WS upgrade.

## Step-by-step integration

**1. Open a session**

Call `POST /v1/sessions` with `mode: "text"`. Store the returned `session_id` and `agent_url`.

```bash cURL theme={null}
curl -X POST https://api.humain.ai/v1/sessions \
  -H "Authorization: Bearer hk_live_your_credential_here" \
  -H "Content-Type: application/json" \
  -d '{"mode":"text"}'
# → {"session_id":"3fa85f64-5717-4562-b3fc-2c963f66afa6","agent_url":"https://api.humain.ai"}
```

```javascript JavaScript theme={null}
const { session_id, agent_url } = await fetch('https://api.humain.ai/v1/sessions', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer hk_live_your_credential_here',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ mode: 'text' }),
}).then(r => r.json());
```

```python Python theme={null}
resp = client.post('/v1/sessions', json={'mode': 'text'})
data = resp.json()
session_id, agent_url = data['session_id'], data['agent_url']
```

```go Go theme={null}
body := strings.NewReader(`{"mode":"text"}`)
req, _ := http.NewRequestWithContext(ctx, "POST",
    "https://api.humain.ai/v1/sessions", body)
req.Header.Set("Authorization", "Bearer hk_live_your_credential_here")
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
```

**2. Mint a WebSocket ticket (browser clients only)**

Browsers cannot set an `Authorization` header on a WebSocket upgrade. POST here first and
pass the returned ticket as `?ticket=` on the WS URL instead. Non-browser clients skip this
step and use the Bearer header directly on the upgrade request.

```bash cURL theme={null}
curl -X POST https://api.humain.ai/v1/sessions/$SESSION_ID/ws-ticket \
  -H "Authorization: Bearer hk_live_your_credential_here"
# → {"ticket":"wst_...","expires_in":30}
```

```javascript JavaScript theme={null}
const { ticket } = await fetch(
  `${agent_url}/v1/sessions/${session_id}/ws-ticket`,
  { method: 'POST', headers: { 'Authorization': `Bearer ${token}` } }
).then(r => r.json());

const ws = new WebSocket(
  `${agent_url.replace('https://', 'wss://')}/v1/sessions/${session_id}/ws?ticket=${ticket}`
);
```

Tickets are single-use and expire in `expires_in` seconds (default 30) if unused. See
[WebSocket streaming](https://humain.mintlify.site/connections/websocket-streaming.md) for the full connection and message
protocol — that page covers sending/receiving turns, error frames, and reconnection.

**3. End the session**

Always call `end` on `agent_url` when the conversation finishes.

```bash cURL theme={null}
curl -X POST $AGENT_URL/v1/sessions/$SESSION_ID/end \
  -H "Authorization: Bearer hk_live_your_credential_here"
# → 204 No Content
```

```javascript JavaScript theme={null}
await fetch(`${agent_url}/v1/sessions/${session_id}/end`, {
  method: 'POST',
  headers: { 'Authorization': 'Bearer hk_live_your_credential_here' },
});
```

```python Python theme={null}
client.post(f'{agent_url}/v1/sessions/{session_id}/end')
```

```go Go theme={null}
req, _ := http.NewRequestWithContext(ctx, "POST",
    agentURL+"/v1/sessions/"+sessionID+"/end", nil)
req.Header.Set("Authorization", "Bearer hk_live_your_credential_here")
http.DefaultClient.Do(req)
```

Calling `end` on an already-closed session returns `400 SESSION_ENDED`.

## Advanced topics

> [accordion] Handling guardrail rejections
>
> If the user's input triggers a guardrail rule, the WebSocket sends
> `{"type":"error","code":"TURN_ERROR","message":"INPUT_REJECTED: ..."}` instead of a
> response frame. Display a neutral message to the user and do not retry automatically —
> see [WebSocket streaming](https://humain.mintlify.site/connections/websocket-streaming.md#error-frames) for the full error
> frame format.
>
> ```javascript theme={null}
> ws.onmessage = (event) => {
>   const frame = JSON.parse(event.data);
>   if (frame.type === 'error') {
>     if (frame.message?.startsWith('INPUT_REJECTED')) {
>       displayToUser("I'm not able to help with that request.");
>       return; // Don't retry
>     }
>   }
> };
> ```

> [accordion] Retrying on provider errors
>
> A `PROVIDER_ERROR`-prefixed message means the LLM is temporarily unavailable. Close and
> reopen a new WebSocket connection with exponential back-off: wait 1 s, then 2 s, then 4 s.
> Cap at 3 retries. If still failing, surface a generic error.

> [accordion] Sandbox mode
>
> Sessions opened with an `hk_test_` credential echo the user's message back verbatim over
> the WebSocket — no LLM call is made and no usage is billed. Useful for testing your
> integration end-to-end before going live. See [Sandbox mode](https://humain.mintlify.site/concepts/sandbox-mode.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.