> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://statpad.dev/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://statpad.dev/docs/_mcp/server.

# TypeScript SDK

> Install and use @statpad/sdk, the TypeScript client for the Statpad REST API. Covers the return shape, method groups, pagination, errors, retries, timeouts, conditional requests and versioning.

`@statpad/sdk` is the TypeScript client for the Statpad REST API. It has a typed method for every endpoint and a TypeScript type for every schema. The source and its README are at [statpad-dev/statpad-node](https://github.com/statpad-dev/statpad-node).

## Install

```bash
npm install @statpad/sdk
```

The SDK needs Node.js 20 or newer. It has no dependencies and uses the standard `fetch`.

The package is ESM only. Load it with `import`:

```ts
import { Statpad } from "@statpad/sdk";

const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });
```

From CommonJS, use `await import("@statpad/sdk")`. `require("@statpad/sdk")` fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`.

Call Statpad from your server. The API doesn't accept requests from browsers, and a key in a web page or an app is readable by anyone who has it.

## Options

| Option       | Default                   | What it does                                                          |
| ------------ | ------------------------- | --------------------------------------------------------------------- |
| `apiKey`     | Required                  | Your API key. The client sends it as `Authorization: Bearer <key>`.   |
| `baseUrl`    | `https://api.statpad.dev` | The API's address.                                                    |
| `fetch`      | `globalThis.fetch`        | The `fetch` function the client calls, for proxies, logging or tests. |
| `maxRetries` | `2`                       | How many times to retry a failed request.                             |

## Methods

Each method takes an object with `path`, `query` and `headers`, with the same names as in the [API Reference](/docs/api-reference). It returns `{ data, request, response }`. `data` is the parsed body, and `response` is the raw `Response`, with its status and headers:

```ts
const { data: game, response } = await statpad.games.getGame({ path: { league: "nfl", game_id: gameId } });
console.log(response.status, game.game.status);
```

The client groups its methods the same way as the API Reference:

| Property     | Methods                                                  |
| ------------ | -------------------------------------------------------- |
| `leagues`    | `listLeagues`                                            |
| `games`      | `listGames`, `getGame`, `listGameRoster`                 |
| `playByPlay` | `listPlays`, `listPlayGroups`                            |
| `statistics` | `getBoxScore`, `listPlayerStats`, `listLeaders`          |
| `teams`      | `listTeams`, `getTeam`, `getTeamRoster`, `getDepthChart` |
| `players`    | `getPlayer`, `listPlayerStats`                           |
| `leagueNews` | `listInjuries`, `listTransactions`                       |
| `changes`    | `listGameChanges`, `listChangedEntities`                 |

`listPlayerStats` is in two groups. Both call the same endpoint.

The package exports a type for every schema, such as `Game`, `LiveState`, `Change` and `ErrorCode`:

```ts
import type { Game } from "@statpad/sdk";
```

## Pagination

`paginate` takes a list method and its options. It requests each next page until `next_cursor` is `null`, and yields whole pages, so you keep each page's `teams`, `players` and `seq`:

```ts
import { paginate } from "@statpad/sdk";

for await (const page of paginate(statpad.playByPlay.listPlays, { path: { league: "nfl", game_id: gameId } })) {
  for (const play of page.data) console.log(play.description);
}
```

`listGameChanges` pages by `after_seq`, so `paginate` doesn't accept it. [Lists, pagination and dates](/docs/pagination) covers both kinds of paging.

## Errors

An error response throws a `StatpadError`. Branch on its `code`, which is stable. `title` and `detail` are for people and can change:

**`errors.mts`**

```ts title="errors.mts"
import { Statpad, StatpadError } from "@statpad/sdk";

const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });

try {
  await statpad.games.getGame({
    path: { league: "nfl", game_id: "01a1d60f-0000-7000-8000-000000000000" },
    signal: AbortSignal.timeout(10_000),
  });
} catch (err) {
  if (!(err instanceof StatpadError)) throw err;
  console.log(err.status, err.code, err.detail);
}
```

```text
404 not_found No game 01a1d60f-0000-7000-8000-000000000000 in nfl.
```

A `StatpadError` also has these fields:

| Field        | What it holds                                                    |
| ------------ | ---------------------------------------------------------------- |
| `status`     | The HTTP status.                                                 |
| `requestId`  | The request's id. Include it when you report a problem.          |
| `retryAfter` | The seconds from the `Retry-After` header, when there is one.    |
| `resetsAt`   | With `quota_exhausted`, when the next period's allowance starts. |
| `minSeq`     | With `resync_required`, the oldest seq the stream still holds.   |

A 2xx response whose body isn't JSON also throws a `StatpadError`, with that status and no `code`. This happens when something other than the API answers, such as a captive portal.

Two failures happen before there's a response, so they don't throw a `StatpadError`:

* A network error throws the `TypeError` from `fetch`, after the retries run out.
* An aborted request throws the signal's reason. For `AbortSignal.timeout()`, that's a `DOMException` named `TimeoutError`.

[Errors](/docs/errors) lists every code.

## Retries and timeouts

The client retries these failures:

* `429` with code `rate_limited`
* `500`, code `internal`
* `503`, code `unavailable`
* Network errors

It retries up to `maxRetries` times, 2 by default, so a request makes at most 3 attempts. Between attempts, it waits the seconds in `Retry-After`. Without that header, it backs off exponentially with random jitter. Set `maxRetries: 0` to turn retries off.

It never retries `quota_exhausted`. The allowance comes back only when the period renews.

Every endpoint is a read, so a retry never repeats a write.

The client sets no timeout. To bound a request, pass an `AbortSignal` as `signal`, as in the example above. The signal covers every attempt and the waits between them.

## Conditional requests

Reads of a game, its plays, drives, roster and box score return an `ETag`. So do reads of teams, players, team rosters, depth charts and injuries. Send it back in `If-None-Match`. If nothing changed, the API answers `304` with no body.

The client doesn't throw on a `304`. It returns `data` as `undefined`, so check the status before you read `data`:

**`etag.mts`**

```ts title="etag.mts"
import { Statpad } from "@statpad/sdk";

const statpad = new Statpad({ apiKey: process.env.STATPAD_API_KEY! });
const path = { league: "nfl", game_id: process.argv[2] };

const first = await statpad.statistics.getBoxScore({ path });
const etag = first.response.headers.get("ETag") ?? undefined;

const next = await statpad.statistics.getBoxScore({ path, headers: { "If-None-Match": etag } });
console.log(next.response.status, next.data === undefined);
const box = next.response.status === 304 ? first.data : next.data;
console.log(box.players.length);
```

Against a test server holding a recorded NFL game, it prints:

```text
304 true
68
```

> **Warning**
>
> The type of `data` doesn't include `undefined`, so TypeScript won't warn you when you read `data` from a `304`.

A `304` saves the transfer, but it still counts as one request against your allowance.

## The stream

The SDK has no stream client yet. Use any WebSocket library, such as [`ws`](https://github.com/websockets/ws), and the SDK's types for the messages' contents. The [Quickstart](/docs/quickstart#follow-it-live) builds a stream client, and [Live updates](/docs/streaming) adds backoff, dead-connection checks and error handling.

## Versioning

The SDK follows semantic versioning. Until 1.0, a minor release can include breaking changes, so pin the minor version:

```bash
npm install @statpad/sdk@~0.1.0
```