---
name: statpad
description: Rules for code that calls the Statpad live sports data API (api.statpad.dev, the stream at stream.statpad.dev, @statpad/sdk). Use when writing, reviewing or debugging a Statpad integration, such as a scoreboard, a stream client that follows live games, a poller for the changes feed, or anything that stores Statpad data.
---

# Statpad

Statpad serves live sports data over REST (`https://api.statpad.dev/v1`) and a WebSocket stream (`wss://stream.statpad.dev/v1/stream`). Both send the same JSON. These rules cover what integrations most often get wrong. Each section ends with the docs page that has the detail and the code.

## Look things up

Look up every field name, parameter, limit and error code before you write it. The docs are at `https://statpad.dev/docs`:

- Search them with the docs MCP server at `https://statpad.dev/docs/_mcp/server` when it's connected.
- Read the index at `https://statpad.dev/docs/llms.txt`, which lists every guide and API reference page.
- Append `.md` to any docs page URL for its Markdown, such as `https://statpad.dev/docs/streaming.md`.
- Test parsers and stream clients against real recorded responses, which need no key: `https://statpad.dev/docs/replay.md`.

Call `GET /v1/leagues` for the leagues a key can read instead of hard-coding a list.

## Keys

- Keep the API key on a server, in an environment variable such as `STATPAD_API_KEY` or a secret manager. Browser code, mobile apps and repositories are readable by anyone, so a key never goes there. The REST API sends no CORS headers, so browsers can't call it anyway.
- Send it as `Authorization: Bearer <key>` on REST and on the stream.
- Serve your own users from your backend. One server-side stream subscription feeds any number of them, while a connection per end user runs out the plan's connection limit.
- Every key on an account shares one request rate and one monthly allowance. More keys add no capacity.
- For live scores on a public web page, use an embed key (`statpad_pk_...`) with Statpad's embed widgets. It doesn't work on `/v1` or the stream.

Detail: `https://statpad.dev/docs/keys.md`.

## TypeScript

Use `@statpad/sdk`. It needs Node 20 or newer and is ESM only, so load it with `import`. Every method takes `{ path, query, headers, signal }` and returns `{ data, request, response }`.

- Errors throw `StatpadError`. Branch on `err.code`, which is stable, and treat `title` and `detail` as text for people.
- The client retries `rate_limited`, `internal`, `unavailable` and network errors itself. It sets no timeout, so pass `signal: AbortSignal.timeout(10_000)`.
- A `304` returns `data` as `undefined` without throwing. Check `response.status` before reading `data`.
- `paginate(method, options)` walks cursor lists.
- The SDK has no stream client. Use `ws` for the WebSocket and the SDK's types (`Change`, `Play`, `LiveState`) for the payloads.

From other languages, call REST directly. The stream is plain JSON over a WebSocket.

Detail: `https://statpad.dev/docs/sdk.md`.

## Follow a game

1. Read the game over REST, `GET /v1/{league}/games/{id}`. The response has a `seq`.
2. Open the stream. After the server's `welcome`, subscribe from that seq: `{ "type": "subscribe", "streams": ["game:<id>"], "resume": { "game:<id>": <seq> } }`. The stream then sends every change after the read, with none missing and none repeated.
3. Apply each change, then record its `seq` as the last applied seq.
4. After any disconnect, reconnect and resume from the last applied seq.

The game read holds the game, its live state, both teams and the venue, not plays, drives, roster or player stats. To hold those too, either fill them from their own REST reads and resume from the lowest `seq` among the reads, or subscribe without `resume` for a snapshot of the whole game stream.

A league stream (`league:<alias>`) has no REST read to resume from. Subscribe without `resume` to get a snapshot. Buffer `snapshot` messages until one has `last: true`, replace that stream's state with them, then apply changes after the snapshot's `seq`.

Detail: `https://statpad.dev/docs/streaming.md` and `https://statpad.dev/docs/many-games.md`.

## Store state

- Every change carries the entity's full current state. On `upsert`, replace what you hold under `entity_type` and `entity_id`. On `delete`, remove it. Replace whole entities, because a field-by-field merge keeps fields the new state no longer has.
- Keep one state map per stream. Game roster entries and player stats use the player's id as `entity_id`, so two games' entries collide in a shared map.
- Key stored data by id and keep the highest `version` of each entity. A lower version is stale, so ignore it. This matters wherever REST reads and stream changes overlap.
- Expect corrections. Plays often come back as new versions: 83 of the 270 play changes in the recorded NFL sample are corrections. Corrections keep arriving for up to 3 hours after the final. Replacing by id applies them with no extra code.

## Stay connected

- Back off between reconnects: wait about 1 second, double the wait after each failure up to 30 seconds, and add random jitter. Reset the count when a `subscribed` arrives.
- The server sends `heartbeat` every 5 seconds. Close a connection that has sent nothing for 20 seconds, then reconnect and resume.
- Close code `1008` means the key is invalid or revoked, or the plan has no streaming. Stop until the key or plan changes. For every other close code, back off, reconnect and resume.
- A stream `error` that names a `stream` ends only that subscription, and the connection stays open. Act on its `code`:

| `code` | Do |
| --- | --- |
| `slow_consumer`, `internal` | Subscribe again from the last applied seq. |
| `unavailable` | Wait a few seconds, then subscribe again. |
| `rate_limited` | Wait `retry_after` seconds, then subscribe again. |
| `resync_required`, `invalid_resume` | Your seq can't be resumed. If you mirror the whole stream, subscribe again without `resume` and replace that stream's state with the snapshot. This is the only way to recover a `league:` stream. If you keep only the game and its live state, read the game over REST, replace those, and resume from its `seq`. |
| `quota_exhausted` | Stop until the period resets. Then resume from the last applied seq, or subscribe for a snapshot if you applied nothing yet. `resume_from` is missing when the refused subscribe was a snapshot. |
| `too_many_subscriptions` | The `message` says which cap you hit. Past the connection's 100, open another connection. Past the account's plan cap, unsubscribe from games that have ended. |
| `forbidden`, `unknown_stream`, `bad_request` | Stop. The same request fails the same way. |

Detail: `https://statpad.dev/docs/streaming.md#stay-connected` has the whole client, and `https://statpad.dev/docs/errors.md` has every code.

## Developer plan

Developer is REST only, with no stream connections. Poll the game's changes feed instead: `GET /v1/{league}/games/{id}/changes?after_seq=<last applied seq>` returns the same changes the stream sends. While the last applied seq is behind `head_seq`, request the next page at once. Otherwise wait a few seconds. On `410` with `resync_required`, read again over REST everything you store for the game, such as the game, its plays and its box score, replace it, and continue from the lowest `seq` among those reads. For statuses and scores only, poll `GET /v1/{league}/games` instead.

Detail: `https://statpad.dev/docs/streaming.md#without-the-stream`.

## Requests and the allowance

- Every `2xx` and `304` response counts against the monthly allowance. Errors don't count, but they still use the request rate.
- The stream draws on the same allowance. A subscribe counts once, and each change delivered counts once per subscription.
- Stop on `quota_exhausted`. Only the next period brings the allowance back.
- Send a stored `ETag` in `If-None-Match` to skip unchanged bodies. A `304` still counts.

Detail: `https://statpad.dev/docs/get-started/rate-limits.md`.

## Lists and dates

- Lists page by cursor. Pass `next_cursor` back as `cursor` until it's `null`, and never build or edit a cursor. In TypeScript, `paginate` yields whole pages.
- Read each page's `teams` or `players` together with that page's items, because they cover only that page.
- To follow a game after paging its plays, drives or roster, resume from the first page's `seq`.
- The game changes feed pages by `after_seq`, not by cursor, so `paginate` rejects it.
- `GET /v1/{league}/games` takes either `date`, a calendar day in `tz` (default `America/New_York`), or `from` and `to`, at most 31 days apart with `to` exclusive. Never both.
- Timestamps are RFC 3339 in UTC. A season's `year` is the year it starts, so the NBA's 2026-27 season is `2026`.

Detail: `https://statpad.dev/docs/pagination.md`.
