Skip to navigation

TypeScript SDK

Install @statpad/sdk, call the REST API with types, and handle errors, retries and timeouts.

@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.

Install

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:

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

OptionDefaultWhat it does
apiKeyRequiredYour API key. The client sends it as Authorization: Bearer <key>.
baseUrlhttps://api.statpad.devThe API’s address.
fetchglobalThis.fetchThe fetch function the client calls, for proxies, logging or tests.
maxRetries2How 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. It returns { data, request, response }. data is the parsed body, and response is the raw Response, with its status and headers:

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:

PropertyMethods
leagueslistLeagues
gameslistGames, getGame, listGameRoster
playByPlaylistPlays, listPlayGroups
statisticsgetBoxScore, listPlayerStats, listLeaders
teamslistTeams, getTeam, getTeamRoster, getDepthChart
playersgetPlayer, listPlayerStats
leagueNewslistInjuries, listTransactions
changeslistGameChanges, 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:

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:

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 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
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);
}
404 not_found No game 01a1d60f-0000-7000-8000-000000000000 in nfl.

A StatpadError also has these fields:

FieldWhat it holds
statusThe HTTP status.
requestIdThe request’s id. Include it when you report a problem.
retryAfterThe seconds from the Retry-After header, when there is one.
resetsAtWith quota_exhausted, when the next period’s allowance starts.
minSeqWith 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 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
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:

304 true
68

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, and the SDK’s types for the messages’ contents. The Quickstart builds a stream client, and Live updates 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:

npm install @statpad/sdk@~0.1.0