The short answer
- Polling: you ask a REST endpoint for the latest state on a timer. Simplest to build, works on every plan, and its delay is your refresh interval.
- WebSocket: you hold one connection open and the server pushes every change the moment it is published. The fastest option, and the right one for live screens.
- Webhooks: the server sends an HTTP POST to your URL for each event you chose. No connection to keep alive, which suits alerts, bots and back-office jobs.
Polling: ask again and again
Polling is plain REST. Your code calls an endpoint such as GET /v2/livescores, draws the answer, waits and calls again. Nothing stays open between calls, so it runs anywhere a timer runs: a small server, a cron job, a serverless function.
The trade-off is delay and volume. A change that happens just after a poll waits a full interval before you see it, and every call costs one request whether or not anything changed. On Free (10 requests a minute, 1,000 a day) a 15-second interval covers about four hours of live play a day, so two habits matter: cache one answer on your server for every visitor, and poll slower when meta.count says nothing is live.
// poll.mjs (Node 18+): one request every 15 s while matches are live
const KEY = process.env.DATASPORTSAPI_API_KEY;
const URL = "https://api.datasportsapi.com/v2/livescores?sport=football";
// render(data) stands for your own drawing code.
async function poll() {
let next = 15_000;
try {
const res = await fetch(URL, { headers: { Authorization: `Bearer ${KEY}` } });
if (res.status === 429) {
// rate_limited or quota_exceeded: wait as long as the API asks
next = Number(res.headers.get("Retry-After") ?? 60) * 1000;
} else if (res.ok) {
const { data, meta } = await res.json();
render(data);
if (meta.count === 0) next = 300_000; // nothing live: check every 5 min
}
} catch (err) {
console.error(err); // network error: try again on the next tick
}
setTimeout(poll, next);
}
poll();WebSocket: one connection, every change pushed
A WebSocket is a connection that stays open after the first handshake, so the server can write to you whenever it has news. Opening one takes two steps. First POST /v2/stream/ticket with your key: it returns a one-time ticket and the wss:// URL to open, valid for 30 seconds. Using a ticket keeps the API key out of socket URLs and logs.
Once connected, the server greets you with a welcome frame. You subscribe to channels such as livescores, sport:tennis, league:{id} or fixture:{id}. Each subscription starts with a snapshot of the current state. After that come fixture frames, carrying a complete match that has just joined the channel, and delta frames, carrying only the fields that changed. Merge deltas into the copy you hold, nested objects key by key.
// stream.mjs (Node 22+, which has WebSocket built in)
const KEY = process.env.DATASPORTSAPI_API_KEY;
const fixtures = new Map(); // fixture id → the latest full Fixture
let lastSeq = null;
async function getTicket() {
const res = await fetch("https://api.datasportsapi.com/v2/stream/ticket", {
method: "POST",
headers: { Authorization: `Bearer ${KEY}` },
});
if (!res.ok) throw new Error(`ticket refused: ${res.status}`); // 403 below Business
return (await res.json()).data; // { ticket, url, expiresInSeconds }
}
function merge(target, changes) {
for (const [key, value] of Object.entries(changes)) {
const both = value && typeof value === "object" && !Array.isArray(value)
&& target[key] && typeof target[key] === "object";
if (both) merge(target[key], value);
else target[key] = value; // null and arrays replace
}
}
async function connect() {
const { url } = await getTicket();
const ws = new WebSocket(url);
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.seq != null) lastSeq = msg.seq;
if (msg.type === "welcome") {
const sub = { type: "subscribe", channel: "livescores" };
if (lastSeq != null) sub.lastSeq = lastSeq; // replay what we missed
ws.send(JSON.stringify(sub));
} else if (msg.type === "snapshot") {
fixtures.clear();
for (const f of msg.data ?? []) fixtures.set(f.id, f);
} else if (msg.type === "fixture") {
fixtures.set(msg.id, msg.data); // a match just joined the channel
} else if (msg.type === "delta") {
const f = fixtures.get(msg.id);
if (f) merge(f, msg.changes);
} // other frame types (ping, subscribed, error, …) can be skipped
render([...fixtures.values()]);
};
ws.onclose = (event) => {
// 1012 = server restarting: come back at once. Otherwise wait a little.
setTimeout(() => connect().catch(console.error), event.code === 1012 ? 0 : 3000);
};
}
connect().catch(console.error);That is the core. A production client adds three things, all described in the connect reference: send resync when a channel's seq skips a number; treat the socket as dead when no frame, not even a ping, has arrived for 2.5 heartbeats (a laptop waking from sleep leaves sockets like that); and reload over REST whatever you display after a long gap. The official SDKs do all of this for you.
Recovery is the stream's strong point. Reconnect with the last seq you hold and the server replays up to five minutes of missed frames, then confirms with a subscribed frame; after a longer outage you get a fresh snapshot instead. Frames are not requests, so a busy Saturday costs the same as a quiet Tuesday: one request per ticket. The cost is infrastructure. You need a process that stays up, which rules out most serverless functions, and Business allows three concurrent connections per account (Enterprise five). For a website, hold the socket on your server and fan the updates out to browsers, rather than opening one connection per visitor.
Webhooks: the server calls you
With webhooks the direction flips. You add an https:// endpoint in the dashboard, choose filters (event type, sport, league ids, fixture ids, combined with AND), and each event arrives at your URL as a separate JSON POST. fixture.score and fixture.status cover every live match your filters match; fixture.events and fixture.lineups are sent for the fixtures you name. The changes inside each event have the same shape as a WebSocket delta.
Your endpoint has two duties. Check the DSA-Signature header on every request: it reads t=<unix seconds>,v1=<hex>, where v1 is an HMAC-SHA256 of <t>.<raw body> keyed with the endpoint's signing secret. And answer with a 2xx within 10 seconds, so do the slow work after replying or hand it to a queue.
// webhook.mjs (Node 18+): verify, answer fast, deduplicate
import { createServer } from "node:http";
import crypto from "node:crypto";
const SECRET = process.env.DSA_WEBHOOK_SECRET; // shown once, when the endpoint is created
const seen = new Set(); // in production, a table with a unique key on the event id
function verify(header, rawBody) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const age = Date.now() / 1000 - Number(parts.t);
if (!parts.t || !parts.v1 || !(age < 300)) return false; // refuse old or malformed
const expected = crypto.createHmac("sha256", SECRET).update(`${parts.t}.${rawBody}`).digest("hex");
const a = Buffer.from(parts.v1);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b); // constant time
}
createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8"); // the raw body, before any parsing
if (!verify(req.headers["dsa-signature"] ?? "", raw)) {
res.writeHead(401).end();
return;
}
res.writeHead(204).end(); // reply first, work afterwards
const event = JSON.parse(raw);
if (seen.has(event.id)) return; // a retry of something already handled
seen.add(event.id);
handle(event); // fixture.score, fixture.status, fixture.events, fixture.lineups, ping
});
}).listen(8080); // put it behind HTTPS: endpoints must be public https:// hostsIf your endpoint fails or answers late, the delivery is retried after 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours, then marked failed; an endpoint that fails every attempt for 24 hours is disabled until you switch it back on. Because of retries, the same event can arrive twice, and deliveries can arrive out of order. Deduplicate on the event id (also sent as DSA-Event-Id) and use createdAt to ignore an update older than the one you already applied.
Side by side
| Polling | WebSocket | Webhooks | |
|---|---|---|---|
| Who starts the exchange | Your code, on a timer | The server, over a socket you opened | The server, by calling your URL |
| Delay after a change | Up to one refresh interval | Pushed as soon as published | Pushed per event, plus your endpoint's response time |
| Request cost | One per call, changed or not | One per ticket; frames are free | You make no calls to receive events |
| After an outage | The next call returns the current state | Reconnect with lastSeq: up to 5 minutes replayed, else a fresh snapshot | Retries for about 8½ hours, then failed |
| What you run | Anything with a timer, serverless included | A long-lived process | A public HTTPS endpoint that answers within 10 s |
| Security | API key on your server | Key used only to mint a 30-second ticket | HMAC signature on every request |
| Plan | Every plan, Free included | Business and Enterprise | Business and Enterprise |
Which one to choose
| You are building | Use | Why |
|---|---|---|
| A prototype, a hobby site or anything on Free | Polling | No extra infrastructure, and it works on the free key |
| A live scoreboard, app or match centre | WebSocket, held on your server | The shortest delay, and traffic does not grow with the number of goals |
| Push notifications, Discord or Slack bots, emails | Webhooks | One request per event, no socket to keep alive, fine on serverless |
| Settling predictions or updating records at full time | Webhooks on fixture.status | You only care about a few moments per match |
| Lineup alerts before kick-off | Webhooks on fixture.lineups | Sent for the fixtures you name, starting roughly 90 minutes ahead |
| Formula 1, MotoGP or cycling sessions | Polling /v2/races/{id} | The stream does not carry race sports yet |
Most production systems combine them. A typical setup loads today's fixtures over REST, keeps one WebSocket open for the live updates, reloads over REST after a long disconnect, and uses webhooks for jobs that should run even when no screen is open. Polling stays useful as a fallback and for data that changes slowly, such as standings, which update once a day.
Where to go next
- Start polling on a free key with the live score app tutorial.
- Read the stream's frames, channels and close codes in the WebSocket docs.
- Set up an endpoint and its filters with the webhooks docs.
- Compare the plans' limits and real-time features on pricing.