Skip to navigation

Build a scoreboard

Turn a game read into a score line, a period, a clock and a box score.

A scoreboard line shows a game’s status, score, period and clock. This page shows how to read each one, then builds a box score from three REST reads.

The examples read the sample games, so they run without a key. In your app, the same objects come from statpad.games.getGame, the box score and roster endpoints, or the stream.

Game status

game.status has 11 values. Group them into four phases and render each phase its own way:

phase.mts
import type { GameStatus } from "@statpad/sdk";
export type Phase = "pregame" | "live" | "final" | "off";
export const phases: Record<GameStatus, Phase> = {
scheduled: "pregame",
time_tbd: "pregame",
created: "pregame",
inprogress: "live",
halftime: "live",
delayed: "live",
complete: "final",
closed: "final",
suspended: "off",
postponed: "off",
cancelled: "off",
};
StatusPhaseWhat it means
scheduledPregameThe game has a start time.
time_tbdPregameThe game has a day but no start time yet.
createdPregameThe game’s data is available, but play hasn’t started.
inprogressLiveThe teams are playing.
halftimeLiveThe game is at halftime.
delayedLivePlay has stopped for now, such as for rain.
completeFinalThe game is over. Statpad can still correct its stats.
closedFinalThe feed has validated the final stats.
suspendedOffPlay stopped and will resume later.
postponedOffThe game won’t happen at its scheduled time.
cancelledOffThe game won’t happen.

A complete game still changes. Statpad keeps polling a game for corrections for 3 hours after the final, and each correction arrives as a new version, like any other change. Statpad’s feed doesn’t send created or closed today, but handle them so your code keeps working when it does.

A postponed game works one of two ways, depending on the league. It either goes back to scheduled at its new time under the same id, or it stays postponed and its makeup is a new game. A makeup game’s rescheduled_from_id names the game it replaces, when Statpad knows it.

Start times

scheduled_at is the start time in UTC. A time_tbd game has no start time, so its scheduled_at is the start of the game’s day in US Eastern time. startLabel shows only the date for such a game:

start.mts
import type { Game } from "@statpad/sdk";
export function startLabel(game: Game): string {
const start = new Date(game.scheduled_at);
const zone = "America/New_York";
if (game.status === "time_tbd") return `${start.toLocaleDateString("en-US", { timeZone: zone, dateStyle: "medium" })}, time TBD`;
return start.toLocaleString("en-US", { timeZone: zone, dateStyle: "medium", timeStyle: "short" });
}

For the NFL sample’s start time, and for a time_tbd game on the same day, startLabel returns:

scheduled 2026-11-10T01:15:00Z Nov 9, 2026, 8:15 PM
time_tbd 2026-11-09T05:00:00Z Nov 9, 2026, time TBD

A game whose date isn’t fixed yet, such as an NFL flex game, can still move to another day.

The period

live_state.period is a number. The league’s period_kind and regulation_periods, from GET /v1/leagues, turn it into a label:

Leagueperiod_kindregulation_periodsAfter regulation
NFL, NCAAFquarter4Each later period is an overtime.
NBAquarter4Each later period is a 5-minute overtime.
NCAABhalf2Each later period is a 5-minute overtime.
NHLperiod3Period 4 is overtime. In the regular season, period 5 is the shootout. In the playoffs, every later period is another overtime.
Soccerhalf2Periods 3 and 4 are the halves of extra time. Period 5 is the penalty shoot-out.

Baseball’s period_kind is inning, and period_half says whether it’s the top or the bottom of the inning. Statpad serves no baseball league yet.

period.mts
import type { Game, League, LiveState } from "@statpad/sdk";
const suffixes: Record<string, string> = { one: "st", two: "nd", few: "rd", other: "th" };
const ordinal = (n: number) => n + suffixes[new Intl.PluralRules("en", { type: "ordinal" }).select(n)];
export function periodLabel(league: League, game: Game, live: LiveState): string {
const period = live.period;
if (period === null) return "";
if (league.sport === "baseball") return `${live.period_half === "top" ? "Top" : "Bottom"} ${ordinal(period)}`;
if (period <= league.regulation_periods) return `${ordinal(period)} ${league.period_kind}`;
if (league.sport === "soccer") return period === 5 ? "Penalties" : "Extra time";
if (league.sport === "hockey" && period === 5 && game.game_type !== "playoff") return "Shootout";
const overtime = period - league.regulation_periods;
return overtime === 1 ? "OT" : `${overtime}OT`;
}

These are its labels for a regular-season game in each league. The soccer line also shows a cup game’s extra time and penalties:

epl 1st half, 2nd half, Extra time, Extra time, Penalties
nba 1st quarter, 2nd quarter, 3rd quarter, 4th quarter, OT, 2OT
ncaab 1st half, 2nd half, OT, 2OT
nfl 1st quarter, 2nd quarter, 3rd quarter, 4th quarter, OT
nhl 1st period, 2nd period, 3rd period, OT, Shootout

The clock

The clock depends on the sport:

  • Football, basketball and hockey. clock_seconds is the time left in the period. A basketball clock rounds up, so 0 means the period is over. A hockey shootout has no clock, so its clock_seconds is null.
  • Soccer. The clock counts up, so clock_seconds is always null. The match minute is in live_state.soccer. Its minute and added_minute are the clock as shown, so 90’+6’ is minute 90 and added minute 6. Both are null after full time.
  • Baseball. There’s no clock, so clock_seconds is always null. Show the inning, the outs and the count from live_state.baseball instead.

Football, basketball and hockey feeds don’t say whether the clock is running, so clock_running is null there. In soccer, it’s true while a half or a period of extra time is under way.

clock.mts
import type { LiveState } from "@statpad/sdk";
export function soccerMinute(soccer: { minute: number | null; added_minute: number | null }): string {
if (soccer.minute === null) return "";
return soccer.added_minute ? `${soccer.minute}'+${soccer.added_minute}'` : `${soccer.minute}'`;
}
export function clock(live: LiveState): string {
if (live.soccer) return soccerMinute(live.soccer);
const seconds = live.clock_seconds;
if (seconds === null) return "";
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
}

Soccer plays carry the same minute and added_minute, so soccerMinute also labels events. These are the last two goals in the Premier League sample’s plays.json:

90'+2' Goal: Joshua Zirkzee (Manchester United), left foot, assisted by Patrick Dorgu. Manchester United 3, Aston Villa 4.
90'+6' Goal: Patrick Dorgu (Manchester United), header, assisted by Bruno Fernandes. Manchester United 4, Aston Villa 4.

The score line

scoreLine puts the pieces together, with startLabel for games that haven’t started. It takes a response from GET /v1/{league}/games/{id} and the game’s league:

scoreboard.mts
import type { GameDetail, League } from "@statpad/sdk";
import { phases } from "./phase.mts";
import { startLabel } from "./start.mts";
import { periodLabel } from "./period.mts";
import { clock } from "./clock.mts";
export function scoreLine(league: League, { game, live_state: live, away_team: away, home_team: home }: GameDetail): string {
const matchup = `${away.alias} at ${home.alias}`;
const score = `${away.alias} ${game.away_score}, ${home.alias} ${game.home_score}`;
switch (phases[game.status]) {
case "pregame":
return `${matchup}, ${startLabel(game)}`;
case "live":
if (game.status === "halftime") return `${score}, halftime`;
if (!live) return score;
return `${score}, ${[periodLabel(league, game, live), clock(live)].filter(Boolean).join(" ")}`;
case "final":
return `${score}, final`;
case "off":
return `${matchup}, ${game.status}`;
}
}

live_state is null until a game has live data, so a live game without one shows only the score. A hockey shootout has no clock, so its line ends at the period label. On the sample games, scoreLine returns:

nfl-bills-at-vikings/game-live.json BUF 13, MIN 6, 4th quarter 7:02
nfl-bills-at-vikings/game.json BUF 23, MIN 6, final
nhl-panthers-at-capitals/game.json FLA 3, WSH 4, final
ncaab-wagner-at-uconn/game.json WAG 41, CONN 83, final
epl-man-utd-aston-villa/game.json AVL 4, MAN 4, final

The game read’s period_scores is an empty list today, so there’s no score by period yet. Coverage by league lists the fields that aren’t filled.

A schedule from GET /v1/{league}/games has each game’s status and score, but no live state. To show the period and clock for a list of games, read each game or follow it on the stream. Follow many games covers both.

Coverage

game.coverage says how much of a game the feed covers:

coverageWhat the game has
fullPlay-by-play, drives, the box score and the live state.
basicNot described yet. No game uses it today.
score_onlyThe score alone, with no play-by-play.

Every game Statpad serves today is full. Check coverage anyway, and hide the play-by-play and box score for a game that isn’t full. Coverage by league lists the fields each league fills.

Build a box score

A box score takes three reads of the same game:

  • GET /v1/{league}/games/{id}/boxscore has one stat line per player.
  • GET /v1/{league}/games/{id}/roster has who dressed for the game, with jerseys. Its players list has their names.
  • GET /v1/{league}/games/{id} has the two teams.

A stat line carries only player_id and team_id, so join it to the roster’s players on the player’s id. Each line holds categories, such as passing and rushing. Each category holds stat codes, such as att and yards. A player has only the categories that apply to them, so treat every category and code as optional.

The box score’s teams list is empty today, so add up the player lines for team totals. Sum counts such as att and yards. Averages and longest plays don’t add up.

This script prints each team’s rushing lines and totals from the NFL sample:

boxscore.mts
import type { BoxScore, GameDetail, GameRosterList } from "@statpad/sdk";
const samples = "https://statpad.dev/samples/nfl-bills-at-vikings";
const get = async <T,>(file: string) => (await (await fetch(`${samples}/${file}`)).json()) as T;
const [game, box, roster] = await Promise.all([
get<GameDetail>("game.json"),
get<BoxScore>("boxscore.json"),
get<GameRosterList>("roster.json"),
]);
const names = new Map(roster.players.map((player) => [player.id, player.full_name]));
const codes = ["att", "yards", "touchdowns"];
for (const team of [game.away_team, game.home_team]) {
console.log(`${team.market} ${team.name}, rushing`);
const totals = codes.map(() => 0);
for (const line of box.players) {
const rushing = line.stats.rushing;
if (line.team_id !== team.id || !rushing) continue;
const values = codes.map((code) => Number(rushing[code] ?? 0));
values.forEach((value, i) => (totals[i] += value));
console.log(` ${(names.get(line.player_id) ?? "Unknown").padEnd(18)} ${values.join("\t")}`);
}
console.log(` ${"Team".padEnd(18)} ${totals.join("\t")}`);
}
node boxscore.mts
Buffalo Bills, rushing
James Cook III 31 107 1
Josh Allen 6 15 0
DJ Moore 1 11 0
Ty Johnson 1 1 0
Kyle Allen 3 -2 0
Ray Davis 2 2 0
Team 44 134 1
Minnesota Vikings, rushing
Aaron Jones Sr. 5 16 0
Carson Wentz 1 0 0
Jordan Mason 6 35 0
Team 12 51 0

A game roster read returns 100 entries per page by default. The sample game has 68 players, so one page holds them all. For a larger roster, page with paginate.

Keep it live

To update the box score during a game, seed the state map from Live updates with the three reads. Then apply the stream’s changes to it. The map’s key is entity_type and entity_id. For most types, entity_id is the entity’s own id. Three game-scoped types use another id:

entity_typeentity_id is
live_stateThe game’s id
game_rosterThe player’s id
player_game_statsThe player’s id

Seed the map with the same keys, so each change from the stream replaces what REST returned:

seed.mts
import type { BoxScore, GameDetail, GameRosterList } from "@statpad/sdk";
import { state } from "./on-change.mts";
export function seed(detail: GameDetail, box: BoxScore, roster: GameRosterList) {
const gameId = detail.game.id;
state.set(`game:${gameId}`, detail.game);
if (detail.live_state) state.set(`live_state:${gameId}`, detail.live_state);
for (const entry of roster.data) state.set(`game_roster:${entry.player_id}`, entry);
for (const line of box.players) state.set(`player_game_stats:${line.player_id}`, line);
}

Each of the three reads returns a seq. Subscribe from the lowest one, and the stream sends anything that changed after that read. A change you already hold leaves the same state when you apply it again.

On the NFL sample, the map seeded from the three files matches a map built from all 1,277 changes in changes.ndjson. Both hold the same 138 entries with the same payloads.

Game roster entries and stat lines use the player’s id as entity_id, so keep one map per game when you follow several games. Follow many games has a client that does this.