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

# Set Websocket

> Enables or disables the instance's WebSocket and sets the event filter and base64 media

**Auth:** `TokenAccount` or `TokenInstance` • **Rate limit:** `Global` (100/min) • **Idempotent:** yes (upsert)

## Description

Enables / disables the instance's WebSocket channel and sets the event filter. Unlike the webhook, there is **a single configuration** per instance (no `label`). This endpoint **does not open a connection**, it only authorizes the later upgrade at [`GET /ws/:instance`](/en/api/websocket).

## Examples

### Enable everything

Turns on the WebSocket without any filter: since `events` is omitted, the client receives all 6 event types, and `mediaBase64` stays `false`.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{"enabled": true}'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ enabled: true })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={"enabled": True}
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{"enabled": true}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Narrow filter

Enables the WebSocket receiving only `message.exchange` and `message.status` and turns on `mediaBase64: true` so frames with media already include the binary content base64-encoded.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled":     true,
      "events":      ["message.exchange", "message.status"],
      "mediaBase64": true
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      enabled:     true,
      events:      ["message.exchange", "message.status"],
      mediaBase64: true
    })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "enabled":     True,
          "events":      ["message.exchange", "message.status"],
          "mediaBase64": True
      }
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{
          "enabled":     true,
          "events":      ["message.exchange", "message.status"],
          "mediaBase64": true
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Disable the websocket

Turns off the WebSocket by sending `enabled: false`. The configuration row is preserved, `events` and `mediaBase64` are cleared, and new connections to `/ws/:instance` start being rejected.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{"enabled": false}'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ enabled: false })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={"enabled": False}
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{"enabled": false}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

## Success response

The response returns the `websocket` object with the configuration actually persisted (`enabled`, `events`, `mediaBase64`), mirrors the request body after the upsert. When `enabled=false`, `events` and `mediaBase64` come back cleared; connections already open at `/ws/:instance` remain until closed naturally, but new connections start being rejected with `400`.

```json 200 OK theme={null}
{
  "success": true,
  "message": "WebSocket configured successfully",
  "websocket": {
    "enabled":     true,
    "events":      ["message.exchange", "instance.state"],
    "mediaBase64": false
  }
}
```

## Path parameters

<ParamField path="instance" type="string" required>
  Instance name.
</ParamField>

## Headers

<ParamField header="token" type="string" required>
  `TokenAccount` or `TokenInstance`.
</ParamField>

<ParamField header="Content-Type" type="string" required>
  `application/json`
</ParamField>

## Request body

<ParamField body="enabled" type="boolean" required>
  Turns the WebSocket on/off. When `false`, `events` and `mediaBase64` are **cleared before saving**.
</ParamField>

<ParamField body="events" type="string[]" default="[]">
  Filter. Empty array = receive all 6 types. Values must be in `{message.exchange, message.status, call.update, group.flow, instance.state, label.update}`.
</ParamField>

<ParamField body="mediaBase64" type="boolean" default="false">
  When `true`, `message.exchange` events with media include `media.base64` in the WS frames.
</ParamField>

## Notes

<Note>
  * **Does not persist events**: WebSocket is ephemeral. If no one is connected at the moment of the event, it's discarded (fast-path `HasClients` before any serialization work).
  * **No retry**: if the socket drops during send, the message is lost. For guaranteed delivery, use webhook.
  * **`enabled=false` does not disconnect already-open clients**: existing connections at `/ws/:instance` remain until closed naturally; new connections fail with `400`.
  * **No documented connection limit**: each instance can have N simultaneous clients (broadcast). The hub keeps a 256-message buffer per client; slow clients are disconnected automatically.
  * **Configuration at creation time**: the same block can be passed to [`POST /api/instance/new`](/en/api/instance/create) via `websocketEnabled`, `websocketEvents`, `websocketMediaBase64`.
</Note>

## Errors

| HTTP | `error.message`                         |
| ---- | --------------------------------------- |
| 400  | `Invalid request body`                  |
| 401  | `Invalid token`                         |
| 404  | `Instance not found`                    |
| 429  | `Rate limit exceeded. Try again later.` |
| 500  | `Failed to get instance`                |

Envelope:

```json theme={null}
{
  "success": false,
  "error": { "message": "Invalid request body" }
}
```

## Next

<CardGroup cols={2}>
  <Card title="Check WebSocket config" icon="eye" href="/en/api/events/websocket-read">
    `GET /api/events/getWebsocket/:instance`
  </Card>

  <Card title="Connect via WebSocket" icon="bolt" href="/en/api/websocket">
    `GET /ws/:instance`, protocol, auth, reconnection.
  </Card>
</CardGroup>
