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

# WebRTC Bridge reference

> Routes, request and response bodies, the events WebSocket and error codes for the WebRTC Bridge.

All routes are relative to the regional base URL, for example `https://webrtc-bridge.us-1.platform.polyai.app`. See [Endpoints](https://docs.poly.ai/api-reference/webrtc-bridge/introduction.md#endpoints).

## Create a call

`POST /api/v1/call`

Creates a call and returns the credentials the client needs to connect. Send this request from your backend.

**Headers**

| Header | Value |
| - | - |
| `Authorization` | `Bearer <WebRTC token>` |
| `Content-Type` | `application/json` |

**Body**

| Field | Required | Description |
| - | - | - |
| `mode` | Yes | Must be `"voice-agent"`. A JSON body without `mode` gets `403`. |
| `caller` | No | A label for the caller, for example a phone number or an email. It shows on the conversation. It is not used for authorization. |
| `variantId` | No | The variant to call. If you leave it out, the bridge uses the variant of the WebRTC token's connector. |

The bridge gets the account, project and environment from the WebRTC token. The project settings select the agent stack. The gateway `mode` values (`end-to-end`, `traditional` and the older aliases) are not accepted.

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{ "mode": "voice-agent", "caller": "+14155551234" }
```

**Response `200`**

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "callId": "LOCAL-3f6c2a9e-8f0b-4f7e-9a51-6b1d2f0c7a44",
  "creds": {
    "provider": "cloudflare",
    "connectUrl": "/api/v1/call/LOCAL-3f6c.../sdp",
    "token": "<call token>",
    "trackName": "agent-echo",
    "iceServers": [
      { "urls": ["stun:stun.cloudflare.com:3478"] },
      {
        "urls": [
          "turn:turn.cloudflare.com:3478?transport=udp",
          "turns:turn.cloudflare.com:443?transport=tcp"
        ],
        "username": "<username>",
        "credential": "<credential>"
      }
    ],
    "iceTransportPolicy": "all",
    "extra": {
      "eventsUrl": "/api/v1/call/LOCAL-3f6c.../events",
      "pullUrl": "/api/v1/call/LOCAL-3f6c.../sdp/pull",
      "renegotiateUrl": "/api/v1/call/LOCAL-3f6c.../sdp/renegotiate"
    }
  }
}
```

| Field | Description |
| - | - |
| `callId` | The call ID. Use it in every later route. It is also the conversation ID: use it to find the call in the Conversations API. You cannot set it. |
| `creds.token` | The call token. It is valid for this call only. |
| `creds.connectUrl` | Path for the microphone offer. |
| `creds.iceServers` | Pass these to `RTCPeerConnection`. The TURN credentials are valid for this call only. If the field is absent, use a public STUN server, for example `stun:stun.cloudflare.com:3478`. |
| `creds.iceTransportPolicy` | `"all"` or `"relay"`, or absent (use `"all"`). Use `"relay"` only when `iceServers` contains a TURN server. |
| `creds.extra.eventsUrl` | Path for the events WebSocket. |
| `creds.extra.pullUrl` | Path to pull the agent track. |
| `creds.extra.renegotiateUrl` | Path for the answer to the pull offer. |

The paths are relative to the base URL. Use the returned paths, not paths that you build yourself.

## Signaling routes

The signaling routes use the call token. Send it in the `X-Call-Token` header:

```
X-Call-Token: <call token>
Content-Type: application/json
```

### Send the microphone offer

`POST /api/v1/call/{callId}/sdp`

Send this within 30 seconds of provision. Gather ICE candidates first. The bridge does not accept trickled ICE candidates.

| Field | Required | Description |
| - | - | - |
| `sdp` | Yes | The SDP offer for the microphone track. |
| `mid` | No | The `mid` of the microphone transceiver. The bridge reads it from the SDP, and uses this field only if it cannot. |

**Response `200`**

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{ "sdp": "v=0\r\no=- ...\r\n" }
```

Set `sdp` as the remote description, with type `answer`.

### Pull the agent track

`POST /api/v1/call/{callId}/sdp/pull`

Send this when the peer connection is `connected`. The bridge does not read the body.

**Response `200`**

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "sdp": "v=0\r\no=- ...\r\n",
  "tracks": [{ "trackName": "agent-echo", "mid": "1" }]
}
```

Set `sdp` as the remote description, with type `offer`. Then create an answer and send it to the renegotiate route. If `sdp` is empty, there is nothing new to pull.

### Answer the pull offer

`POST /api/v1/call/{callId}/sdp/renegotiate`

| Field | Required | Description |
| - | - | - |
| `sdp` | Yes | Your SDP answer to the pull offer. |

A `2xx` response means the agent track is connected.

## End a call

`DELETE /api/v1/call/{callId}`

Send the call token in the `X-Call-Token` header. The response is `204`, also when the call does not exist or has already ended.

When the events WebSocket closes, the call also ends. You do not need to send both.

## Events WebSocket

`wss://<base host>{creds.extra.eventsUrl}`

Open this socket after you receive the `/sdp` answer. Keep it open for the whole call. **When an authenticated socket closes, the bridge ends the call.** The bridge does not keep events that it sends before the socket opens.

Open one socket for each call. The bridge closes a second socket for the same call.

### Authenticate

Send this message immediately after the socket opens:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{ "type": "auth", "token": "<call token>" }
```

If the bridge does not receive a valid auth message within 5 seconds, it closes the socket with `1008`. The call continues. Open a new socket and authenticate, or send `DELETE`.

### Keepalive

The bridge sends a WebSocket ping every 10 seconds. If it receives nothing from the client for 30 seconds, it ends the call. Your client must answer pings. Browsers do this automatically. Some native WebSocket libraries do not answer pings by default.

### Messages from the bridge

Each message is JSON with an `event` field:

| `event` | What to do |
| - | - |
| `repull` | The agent's tracks changed. Pull again: `POST .../sdp/pull`, then `POST .../sdp/renegotiate`. |
| Starts with `barge-in` | The caller interrupted the agent. Stop playing the agent audio, for example set the agent track's `enabled` to `false`. |
| `unmute` | Play the agent audio again. |
| `call_ended` | The call ended. `reason` is `agent_ended` (the agent ended the call) or `agent_failed`. The bridge then closes the socket. |
| `concurrency_limit_reached` | The account is at its limit of concurrent calls. The bridge ends this call. |

Ignore events that you do not recognise. New events can be added.

### Messages to the bridge

| Message | Description |
| - | - |
| `{ "type": "dtmf", "digits": "1" }` | Sends keypad digits to the agent. Allowed characters: `0`–`9`, `*`, `#`. Maximum 32 for each message. |

Send one DTMF message for each keypress. The agent applies its own timeout between digits. The bridge does not support `RTCDTMFSender` or RFC 4733 DTMF in the media. Send DTMF on the events socket only.

The bridge drops a DTMF message with characters that are not allowed, or with more than 32 digits. It does not send a reply. It ignores JSON messages that it does not recognise. A message that it cannot read, for example one larger than 32 KiB, ends the call.

### Close codes

| Code | Reason | Meaning |
| - | - | - |
| `1008` | `unauthorized` | The auth message was missing or the call token is not valid. |
| `1001` | `unknown call` | The call does not exist or has ended. |

When a call ends, the bridge closes the socket without a close code, so the browser reports `1006`. Use the `call_ended` event to find out why.

## Errors

| Status | Route | Meaning |
| - | - | - |
| `400` | Create a call | The body is empty or is not valid JSON, or `mode` has an unknown value. |
| `400` | `/sdp`, `/sdp/renegotiate` | `sdp` is empty, or the body is not valid JSON. |
| `401` | All HTTPS routes | The WebRTC token or the call token is missing or not valid, or the call token has expired. |
| `403` | Create a call | `mode` is missing or is `"echo"`. |
| `403` | `DELETE` | You sent a WebRTC token for a different project. Send the call token. |
| `404` | Signaling routes | The call does not exist or has ended. |
| `413` | Create a call | The request body is too large. |
| `429` | All | Too many requests from your IP address. The body is plain text. See [the rate limit](https://docs.poly.ai/api-reference/webrtc-bridge/introduction.md#call-the-bridge-from-your-backend). |
| `429` | Create a call | The account is at its limit of concurrent calls. The body is `{"error": "concurrency_limit_reached"}`. |
| `500` | Create a call | The bridge could not create the call. Retry once. |
| `502` | `/sdp`, or the first pull and renegotiate | The media service failed. **The call has ended.** Do not retry the route. Create a new call. |
| `502` | A pull or renegotiate after the agent audio is connected | The media service failed. The call continues. Wait for the next `repull` event. If renegotiation fails again and again, the bridge ends the call. |
| `503` | Create a call | The bridge is restarting or cannot take calls now. Retry after a short delay. |
| `503` | `/sdp` | The call is not ready yet. Retry after a short delay. |

Error bodies are plain text unless this table says otherwise.

## WebRTC configuration

| Setting | Value |
| - | - |
| Audio codec | Opus, 48 kHz |
| ICE | Use `creds.iceServers`. Gather all candidates before you send an offer. |
| Bundle | One peer connection carries the microphone and the agent tracks. |

## Troubleshooting

### `401` on the signaling routes

* Send the call token from this call's provision response, not the WebRTC token.
* Send the token in the `X-Call-Token` header.

### `403` when you create a call

* Set `mode` to `"voice-agent"`.

### Browser requests fail with a CORS error

The bridge does not accept cross-origin requests from your domain. Send the HTTPS requests from your backend. See [Call the bridge from your backend](https://docs.poly.ai/api-reference/webrtc-bridge/introduction.md#call-the-bridge-from-your-backend).

### The microphone does not work

* The user must allow the microphone. If they deny it, `getUserMedia` throws `NotAllowedError`. Do not create the call until you have the microphone.
* `getUserMedia` works only on HTTPS pages and on `localhost`.
* If no microphone is connected, `getUserMedia` throws `NotFoundError`.

### The call connects, but there is no agent audio

* Pull the agent track after the peer connection is `connected`.
* Answer the pull offer with `POST .../sdp/renegotiate`.
* Pull again when you receive a `repull` event.

### ICE does not connect

* Pass `creds.iceServers` to `RTCPeerConnection`. They include Cloudflare TURN.
* A corporate firewall can block UDP. TURN over TLS on TCP 443 (`turns:turn.cloudflare.com:443`) can get through most firewalls.
* If the network inspects TLS traffic, TURN over TLS can fail. Ask the network team to exempt `turn.cloudflare.com`.

### The audio is choppy or has a long delay

* Call `pc.getStats()`. Look at `packetsLost`, `jitter` and `roundTripTime` on the `inbound-rtp` and `remote-inbound-rtp` reports.
* Find the `candidate-pair` report that is `nominated`, and look up its local candidate. If `candidateType` is `relay`, the media goes through TURN. TURN adds delay.

### The call ends after a few seconds

* Keep the events WebSocket open. When it closes, the bridge ends the call.
* Answer WebSocket pings. See [Keepalive](#keepalive).
* Send the microphone offer within 30 seconds of provision. See [Time limits](https://docs.poly.ai/api-reference/webrtc-bridge/introduction.md#time-limits).
