WebSockets

Pro Feature

This feature is only available on paid plans. Please schedule a demo or email us to get started.

Fern’s SDKs support sending and receiving messages over WebSockets. You can specify your WebSocket API Definition by using AsyncAPI or the Fern Definition.

How it works

1

Specify your WebSocket API Definition

See below for how to specify the contract for your WebSocket channel using AsyncAPI.

1 asyncapi: 2.6.0
2 info:
3 title: Chat API
4 version: 1.1.2
5 servers:
6 production:
7 host: wss.chat.com
8 channels:
9 /:
10 bindings:
11 ws:
12 query:
13 type: object
14 properties:
15 channel_id:
16 type: string
17 description: Unique identifier assigned to the channel
18 publish:
19 description: Send messages to the WebSocket
20 operationId: sendMessage
21 message:
22 oneOf:
23 - $ref: "#/components/messages/SendChat"
24 subscribe:
25 description: Receive messages from the WebSocket
26 operationId: receiveMessage
27 message:
28 oneOf:
29 - $ref: "#/components/messages/ReceiveChat"
30 components:
31 messages:
32 SendChat:
33 summary: Action triggered when the channel receives a new reaction-added event
34 payload:
35 $ref: '#/components/schemas/SendChat'
36 ReceiveChat:
37 summary: Action triggered when a successful WebSocket connection is established
38 payload:
39 $ref: '#/components/schemas/ReceiveChat'
40 schemas:
41 SendChat:
42 type: object
43 properties:
44 message:
45 type: string
46 ReceiveChat:
47 type: object
48 properties:
49 message:
50 type: string

If you have a Fern Definition, you can specify your websocket in a yaml file. See the example in chat.yml below:

chat.yml
1channel:
2 query-parameters:
3 channel_id:
4 type: string
5 docs: Unique identifier assigned to the channel
6 messages:
7 send:
8 payload:
9 message:
10 type: string
11 docs: The message to send over the WebSocket
12 receive:
13 payload:
14 message: string
2

Generate the SDK

1import { ChatClient } from "chat";
2
3const client = new ChatClient();
4
5const socket = client.chat.connect({
6 channelId: "123",
7 onOpen: () => {
8 console.log("Connected to the WebSocket");
9 },
10 onMessage: (message) => {
11 console.log(message);
12 },
13});
14
15await socket.send("Hello, world!");
16
17socket.on("close", () => {
18 console.log("WebSocket connection closed");
19});
20
21await socket.send("Bye, world!");
22
23socket.close();
Built with