Connecting to the WebSocket
Examples in Node.js, browser, Python, and Go. Same auth in all four, same channels.
Node.js
import WebSocket from 'ws';
const ws = new WebSocket('wss://stream.sportapi.io/v1');
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'auth', token: process.env.SPORTAPI_KEY }));
ws.send(JSON.stringify({ type: 'subscribe', channel: 'nba.scores.live' }));
});
ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());
if (msg.type === 'update') console.log('Update:', msg.data);
});Browser (with a restricted key)
const ws = new WebSocket(
`wss://stream.sportapi.io/v1?token=${RESTRICTED_KEY}`
);
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'subscribe', channel: 'nba.scores.live' }));
};
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'update') render(msg.data);
};Python (using websockets)
import asyncio, json, os, websockets
async def run():
async with websockets.connect("wss://stream.sportapi.io/v1") as ws:
await ws.send(json.dumps({"type": "auth", "token": os.environ["SPORTAPI_KEY"]}))
await ws.send(json.dumps({"type": "subscribe", "channel": "nba.scores.live"}))
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "update":
print(msg["data"])
asyncio.run(run())Go (using gorilla/websocket)
import (
"github.com/gorilla/websocket"
"encoding/json"
"os"
)
c, _, _ := websocket.DefaultDialer.Dial("wss://stream.sportapi.io/v1", nil)
defer c.Close()
c.WriteJSON(map[string]string{"type": "auth", "token": os.Getenv("SPORTAPI_KEY")})
c.WriteJSON(map[string]string{"type": "subscribe", "channel": "nba.scores.live"})
for {
var msg map[string]any
if err := c.ReadJSON(&msg); err != nil { break }
if msg["type"] == "update" { /* handle */ }
}