> For complete lifecycle-event payload schemas and examples, use the canonical overview: Session /api/sessions; Room lifecycle, members, and room playback /api/rooms; Session playback /api/playback; Recording /api/recording; DTMF /api/keypad-input; Messages /api/messages; WebSocket Session /api/web-socket. Use /api/event-delivery for transport behavior. Endpoint pages name relevant events, but these overviews are the canonical references.

# Create a WebSocket session

POST https://api.telekesher.dev/v1/sessions:connectWebsocket
Content-Type: application/json

Create a [WebSocket session](/api/sessions) with no phone leg.
The session acts as an independent participant and exchanges audio with the
configured external WebSocket server. Only `type: "websocket"` is supported.

The session starts in the `connecting` state. After the WebSocket connection
is established, the session advances to `answered`. Its lifetime is bound to
that connection. If the server disconnects or does not connect before the
timeout, the session ends and a `session.ended` webhook is emitted.

You can [add or remove the session from rooms](/api/room-members) and use all
supported session commands. Closing the WebSocket ends the session. This
endpoint creates a new session.

**Triggered webhooks:** `websocket.connected`, `websocket.disconnected`, `websocket.failed`,
`websocket.audio_playback_completed`, `session.ended`

See [WebSocket lifecycle events](/api/web-socket#lifecycle-events) for complete payload schemas and examples.

See [Session lifecycle events](/api/sessions#lifecycle-events) for complete payload schemas and examples.

Reference: https://docs.vorbal.dev/api/web-socket/connect-websocket

## 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

### 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)

- `type` (enum, required) — Session type to create. Only `websocket` is supported.
  - Allowed values: `websocket`
- `websocket` (object, required) — WebSocket audio connection configuration. Audio in both directions is raw mono PCM16 or G.711 mu-law, independently selected, and carried in binary WebSocket frames. Do not include a WAV header.
  - `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`: `mulaw` (mulaw)
        - `sample_rate` (enum, required) — Sample rate in Hz. G.711 mu-law requires `8000`.
          - Allowed values: `8000`
      - `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`: `mulaw` (mulaw)
        - `sample_rate` (enum, required) — Sample rate in Hz. G.711 mu-law requires `8000`.
          - Allowed values: `8000`
      - `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) — External WebSocket URL. Use canonical `ws://host/path` or `wss://host/path` form to use the default port (80 or 443), or include an explicit TCP port from 1 through 65535. Prefer `wss://` across untrusted networks. The host must resolve to a permitted public address.
  - `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) — If true, audio from the session starts muted. Omit this field or set it to `false` to start unmuted.

## Response

### 201

Session created. Born in the `connecting` state.

- `created_at` (datetime, required) — When the session was created, as an RFC 3339 / ISO 8601 UTC string (e.g. "2025-05-06T12:41:36.000Z"). Storage resolution is one second, so the millisecond fraction is always `.000`. Empty string if the originating timestamp is missing or unparseable.
- `session_uuid` (string, required) — Session identifier.
- `state` (enum, required) — Current lifecycle state of the session. `connecting` applies to a `websocket` session whose WebSocket server connection has not yet been established.
  - Allowed values: `new`, `connecting`, `ringing`, `early_media`, `answered`, `ended`
- `type` (enum, required) — The nature of the session: - `phone_in`: inbound phone call from a carrier - `phone_out`: outbound phone call placed with `dial` - `sip`: a registered SIP device - `webrtc`: a WebRTC client - `websocket`: a WebSocket session with no phone leg - `unknown`: could not be determined
  - Allowed values: `phone_in`, `phone_out`, `sip`, `webrtc`, `websocket`, `unknown`
- `caller_id` (string, optional) — Caller ID in canonical international E.164 format with leading `+` (e.g. `+972500000000`). Empty for `websocket` sessions (no phone leg).
- `did` (string, optional) — Called DID in canonical E.164 format with leading `+` (e.g. `+972740000000`). Empty for `websocket` sessions (no phone leg).

## Examples

**Request**

```json
{
  "type": "websocket",
  "websocket": {
    "media_format": {
      "from_session": {
        "encoding": "pcm_s16le",
        "sample_rate": 16000
      },
      "to_session": {
        "encoding": "pcm_s16le",
        "sample_rate": 16000
      }
    },
    "url": "wss://websocket.example.com:8443/audio",
    "start_muted": false
  }
}
```

**Response**

```json
{
  "created_at": "2026-06-29T10:30:00.000Z",
  "session_uuid": "acW68-f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "state": "connecting",
  "type": "websocket"
}
```

**SDK Code**

```python WebSocket_createSession_example
import requests

url = "https://api.telekesher.dev/v1/sessions:connectWebsocket"

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

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

print(response.json())
```

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

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

```go WebSocket_createSession_example
package main

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

func main() {

	url := "https://api.telekesher.dev/v1/sessions:connectWebsocket"

	payload := strings.NewReader("{\n  \"type\": \"websocket\",\n  \"websocket\": {\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:8443/audio\",\n    \"start_muted\": false\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_createSession_example
require 'uri'
require 'net/http'

url = URI("https://api.telekesher.dev/v1/sessions:connectWebsocket")

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  \"type\": \"websocket\",\n  \"websocket\": {\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:8443/audio\",\n    \"start_muted\": false\n  }\n}"

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

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

HttpResponse<String> response = Unirest.post("https://api.telekesher.dev/v1/sessions:connectWebsocket")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"type\": \"websocket\",\n  \"websocket\": {\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:8443/audio\",\n    \"start_muted\": false\n  }\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

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

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

```csharp WebSocket_createSession_example
using RestSharp;

var client = new RestClient("https://api.telekesher.dev/v1/sessions:connectWebsocket");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"type\": \"websocket\",\n  \"websocket\": {\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:8443/audio\",\n    \"start_muted\": false\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift WebSocket_createSession_example
import Foundation

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

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.telekesher.dev/v1/sessions:connectWebsocket")! 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()
```