> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.telekesher.dev/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.telekesher.dev/_mcp/server.

# Create a sidecar WebSocket audio relay

POST https://api.telekesher.dev/v1/sessions/{uuid}/websocket-relay
Content-Type: application/json

Attach a live, bidirectional sidecar audio relay between this session and an
external WebSocket server. Audio streams both ways for the life of the
relay.The relay is a singleton subresource: only one may exist per session. Creating a
second returns `409`. After a `websocket_relay.disconnected` or `websocket_relay.failed`
event the session is free again: retrying this request creates a fresh
relay, replacing any remnant of the previous one.Asynchronous operation;
outcomes arrive as `websocket_relay.*` webhook events. For per-call relays, those
events include this create request's `operation_uuid` when correlation is available.Use this endpoint when your WebSocket server should observe or participate in one existing call. It creates a sidecar relay attached to that call. If your server should instead be an independent participant, [create a standalone WebSocket session](api:voice-api:POST/v1/sessions:connectWebsocket).**Triggered webhooks:** `websocket_relay.connected`, `websocket_relay.disconnected`,
`websocket_relay.failed`, `websocket_relay.message_received`,
`websocket_relay.audio_playback_completed`

Reference: https://docs.telekesher.dev/api/web-socket/create-web-socket-relay

## Authentication

- `Authorization` header (bearer token, required) — Application auth. Send `Authorization: Bearer <app_uuid>:<api_key>` using any active key in the app's collection. See [Authentication](https://voice-platform.docs.buildwithfern.com/api/authentication) for details.

## Request

### Path parameters

- `uuid` (string, required) — [Session](/api/sessions) identifier.

### Headers

- `Idempotency-Key` (string, optional) — Optional key for safely retrying mutating requests. See [Idempotency](https://voice-platform.docs.buildwithfern.com/idempotency) for details.

### Body (application/json)

- `media_format` (object, required) — Audio formats in both directions. `from_session` is audio sent from the session to the WebSocket server; `to_session` is audio sent from the WebSocket server to the session.
  - `from_session` (object, required)
    - `encoding`: `pcm_s16le` (pcm_s16le)
      - `sample_rate` (integer, required) — Sample rate in Hz; for example, `16000` (16 kHz). Must be a multiple of 8000 from 8000 through 192000.
  - `to_session` (object, required)
    - `encoding`: `pcm_s16le` (pcm_s16le)
      - `sample_rate` (integer, required) — Sample rate in Hz; for example, `16000` (16 kHz). Must be a multiple of 8000 from 8000 through 192000.
- `url` (string, required) — WebSocket relay URL. Both `ws://` and `wss://` URLs are accepted. The host must resolve to a permitted public address.
- `operation_uuid` (string, optional) — Optional command correlation UUID. Reuse it within 10 minutes only when retrying the same pause, resume, or relative-seek admission; reuse for a different command is rejected. It is not a general idempotency key or a resource name.
- `connection_headers` (map from string to string, optional) — Customer-controlled HTTP header name→value map sent when opening the connection to the WebSocket server (e.g. auth). The platform owns User-Agent, Origin, Host, Connection, Upgrade, Sec-WebSocket-*, Content-Length, Transfer-Encoding, Proxy-*, Forwarded, X-Forwarded-*, X-Real-IP, and CF-Connecting-IP. The platform sets User-Agent and derives Origin from the target URL. Header names must be valid HTTP field names; bounded count and total size; values may not contain line breaks.
- `start_muted` (boolean, optional, default: false) — If true, the user's audio is not sent to the WebSocket server until `websocket-relay/unmute`.

## Response

### 202

Command accepted for async execution

- `operation_uuid` (string, required)
- `status` (enum, required)
  - Allowed values: `in_progress`, `completed`
- `already_ended` (true, optional) — Optional. Set to `true` on idempotent terminal commands when the session was already in a terminal state at the time the request was received. Absent otherwise.

## Examples

**Request**

```json
{
  "media_format": {
    "from_session": {
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    },
    "to_session": {
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    }
  },
  "url": "wss://websocket.example.com/audio",
  "connection_headers": {
    "Authorization": "Bearer ..."
  }
}
```

**Response**

```json
{
  "operation_uuid": "550e8400-e29b-41d4-a716-446655440000",
  "status": "in_progress"
}
```

**SDK Code**

```python WebSocket_createWebSocketRelay_example
import requests

url = "https://api.telekesher.dev/v1/sessions/uuid/websocket-relay"

payload = {
    "media_format": {
        "from_session": {
            "encoding": "pcm_s16le",
            "sample_rate": 16000
        },
        "to_session": {
            "encoding": "pcm_s16le",
            "sample_rate": 16000
        }
    },
    "url": "wss://websocket.example.com/audio",
    "connection_headers": { "Authorization": "Bearer ..." }
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript WebSocket_createWebSocketRelay_example
const url = 'https://api.telekesher.dev/v1/sessions/uuid/websocket-relay';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"media_format":{"from_session":{"encoding":"pcm_s16le","sample_rate":16000},"to_session":{"encoding":"pcm_s16le","sample_rate":16000}},"url":"wss://websocket.example.com/audio","connection_headers":{"Authorization":"Bearer ..."}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go WebSocket_createWebSocketRelay_example
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.telekesher.dev/v1/sessions/uuid/websocket-relay"

	payload := strings.NewReader("{\n  \"media_format\": {\n    \"from_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    },\n    \"to_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    }\n  },\n  \"url\": \"wss://websocket.example.com/audio\",\n  \"connection_headers\": {\n    \"Authorization\": \"Bearer ...\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby WebSocket_createWebSocketRelay_example
require 'uri'
require 'net/http'

url = URI("https://api.telekesher.dev/v1/sessions/uuid/websocket-relay")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"media_format\": {\n    \"from_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    },\n    \"to_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    }\n  },\n  \"url\": \"wss://websocket.example.com/audio\",\n  \"connection_headers\": {\n    \"Authorization\": \"Bearer ...\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java WebSocket_createWebSocketRelay_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.telekesher.dev/v1/sessions/uuid/websocket-relay")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"media_format\": {\n    \"from_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    },\n    \"to_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    }\n  },\n  \"url\": \"wss://websocket.example.com/audio\",\n  \"connection_headers\": {\n    \"Authorization\": \"Bearer ...\"\n  }\n}")
  .asString();
```

```php WebSocket_createWebSocketRelay_example
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.telekesher.dev/v1/sessions/uuid/websocket-relay', [
  'body' => '{
  "media_format": {
    "from_session": {
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    },
    "to_session": {
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    }
  },
  "url": "wss://websocket.example.com/audio",
  "connection_headers": {
    "Authorization": "Bearer ..."
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp WebSocket_createWebSocketRelay_example
using RestSharp;

var client = new RestClient("https://api.telekesher.dev/v1/sessions/uuid/websocket-relay");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"media_format\": {\n    \"from_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    },\n    \"to_session\": {\n      \"encoding\": \"pcm_s16le\",\n      \"sample_rate\": 16000\n    }\n  },\n  \"url\": \"wss://websocket.example.com/audio\",\n  \"connection_headers\": {\n    \"Authorization\": \"Bearer ...\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift WebSocket_createWebSocketRelay_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "media_format": [
    "from_session": [
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    ],
    "to_session": [
      "encoding": "pcm_s16le",
      "sample_rate": 16000
    ]
  ],
  "url": "wss://websocket.example.com/audio",
  "connection_headers": ["Authorization": "Bearer ..."]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.telekesher.dev/v1/sessions/uuid/websocket-relay")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```