RestAPI.com Real-time Support
Introduction
RestAPI.com offers real-time support for detecting database changes as they happen. In addition to listening for collection changes, you can now use channels for direct, client-to-client messaging – bypassing the API entirely. If needed, you can also send messages via the API using the /api/_rt/send endpoint to trigger WebSocket messages from server-side functions.
Setting Up Real-time Connections
All endpoints are root relative under /api. Choose between Azure Web PubSub and SignalR based on your needs.
Azure Web PubSub Setup
To use Azure Web PubSub, install the client library:
npm install @azure/web-pubsub-client
Then, set up the connection as shown:
import { WebPubSubClient } from "@azure/web-pubsub-client";
const wsResponse = await fetch("/api/_rt/ws");
const { url } = await wsResponse.json();
const ws = new WebPubSubClient(url);
ws.on("group-message", (data) => {
console.log("Received WS message:", data);
});
ws.on("connected", async (e) => {
console.log("Connected with connectionId:", e.connectionId);
// Optionally join a channel immediately after connecting:
const joinRes = await fetch("/api/_rt/join", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
connectionId: e.connectionId,
channel: "exampleChannel"
})
});
const joinData = await joinRes.json();
console.log("Joined channel:", joinData);
});
await ws.start();
SignalR Connection Setup
For SignalR, request the connection info from:
import { HubConnectionBuilder, LogLevel } from "@microsoft/signalr";
const signalRResponse = await fetch("/api/_rt/signalr");
const connectionInfo = await signalRResponse.json();
const connection = new HubConnectionBuilder()
.withUrl(connectionInfo.url, {
accessTokenFactory: () => connectionInfo.accessToken,
})
.withAutomaticReconnect()
.configureLogging(LogLevel.Information)
.build();
connection.on("change", (messageData) => {
console.log("Received change:", messageData);
});
await connection.start();
console.log("SignalR connected with connectionId:", connection.connectionId);
Channel-based Communication
Channels enable direct, client-to-client messaging without routing through the API. This means clients can talk directly to each other via WebSocket. Meanwhile, the /api/_rt/send endpoint lets you trigger messages via the API (for instance, from a server-side function) to clients. Note that for WebPubSub, you use the ws.sendToGroup method with a channel identifier that includes the API name (e.g.myapi:channel).
Creating a Channel
To create a channel, POST to /api/_rt/create with your connectionId. The response returns both a simple channel identifier and a fully-qualified channel string.
// Create a channel
const createRes = await fetch("/api/_rt/create", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ connectionId: connection.connectionId })
});
const channelData = await createRes.json();
console.log("Channel created:", channelData);
// channelData: { channel, channelWithApi }
Joining a Channel
To join an existing channel, POST to /api/_rt/join with your connectionId and the channel identifier.
// Join a channel
const joinRes = await fetch("/api/_rt/join", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
connectionId: connection.connectionId,
channel: "exampleChannel"
})
});
const joinData = await joinRes.json();
console.log("Joined channel:", joinData);
// joinData: { channel, channelWithApi }
Sending a Message via the API
Use the /api/_rt/send endpoint to send a message via the API. This is useful when you want a server-side function to send a WebSocket message directly to clients.
// Send a message via the API
await fetch("/api/_rt/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
channel: channelData.channel,
body: { text: "Hello from server-side!" }
})
});
console.log("Message sent via API");
Direct Client-to-Client Messaging
Channels allow for direct messaging between clients. With SignalR, clients listen for messages on the "change" event, and with WebPubSub, you can use ws.sendToGroup to send messages directly. Note that when using WebPubSub, the channelWithApi property (e.g., myapi:channel) must be used as the group identifier.
// Direct messaging example using SignalR
connection.on("change", (messageData) => {
console.log("Direct channel message received via SignalR:", messageData);
});
// Direct messaging example using WebPubSub
ws.on("group-message", (data) => {
console.log("Direct channel message received via WS:", data);
});
// Send a direct message using WebPubSub's sendToGroup method.
// The channelWithApi property (e.g., "myapi:channel") is used to target the group.
await ws.sendToGroup(joinData.channelWithApi, { text: "Direct message from client via WS" }, "json");
console.log("Direct WS message sent");
Conclusion
RestAPI.com's real-time features now offer flexible channel-based messaging for direct client-to-client communication, alongside server-driven messaging via the API. Whether you choose Azure Web PubSub or SignalR, these tools help you build responsive, real-time applications with ease.