Published on

Websocket Subscription API Approaches


I have been working with various websocket APIs lately and have been exposed to 2 approaches for subscriptions via websockets.

Approach 1 - Send a Subscribe Message and Listen on the Socket

Websockets simply take strings in their send function.

It is normally up to the API in question to specify what the message structure looks like and what the type is. To demonstrate I will assume this API expects messages to be JSON strings.

To subscribe to a channel called people I would do so with the following message:

  "op": "subscribe",
  "channels": ["people"]

Psuedocode to call this would look as below:

client = WebSocketClient("wss://some-endpoint:1347/api/realtime")

    "op": "subscribe",
    "channels": ["people"],

client.onConnected((message) => {
    // handle message here

Approach 2 - Specify Subscription when Connecting and Listen on the Socket

I prefer this approach as it is much cleaner and less verbose.

With this approach, you specify the subscriptions you want as query parameters to the websocket connection string.

Psuedocode to do this looks as below:

client = WebSocketClient('wss://some-endpoint:1347/api/realtime?subscribe=people')

client.onConnected((message) => {
  // handle message here