# Swedish Hockey Live API — app integration

Base URL: `https://api.shl.labnat.se/api/v1`

## Access

An API token is required for all data routes, including `/health` and
`/capabilities`. Request access from **scout_ante on Discord** or
**[anton@scoutante.se](mailto:anton@scoutante.se)**. Tokens are issued manually;
there is no public registration or token creation endpoint.

Send the token in one of these HTTP headers:

```http
X-API-Key: YOUR_API_TOKEN
```

or:

```http
Authorization: Bearer YOUR_API_TOKEN
```

Never put tokens in the URL. Missing, invalid, expired or revoked tokens return
HTTP **401** with contact details. `GET /api/v1/auth/verify` validates a token.
The homepage and this documentation are public and contain no hockey data.

Routes also work without `/api/v1` (for example `/leagues/ha/games`), but use
the versioned base URL for integrations. GET requests only; CORS allows GET,
HEAD and OPTIONS, including `X-API-Key` and `Authorization` headers.
JSON responses use `Cache-Control: no-store`. Lists are in `data: []`;
details are in `data: {}`.

Numeric IDs come from this API, not the upstream providers. Preserve the
`external_id` only as source metadata.

## Routes

| Route | Data |
|---|---|
| `/health` | Server/database status and latest collector runs |
| `/capabilities` | Data coverage and currently unavailable features |
| `/leagues` | Available leagues (`shl`, `ha`) |
| `/leagues/{league}/standings` | Table with `team_id`, rank, name, logo, gp, w, otw, l, otl, gf, ga, diff, points |
| `/leagues/{league}/teams` | Team IDs, names, abbreviations and logos |
| `/leagues/{league}/players` | Player statistics; `sort=points`, `goals`, `assists` or `gp` |
| `/leagues/{league}/goalkeepers` | Goalkeeper statistics |
| `/leagues/{league}/games` | Matches, filtered by season/date/status/team |
| `/leagues/{league}/games/live` | Alias for matches with `status=live` |
| `/games/{id}` | A single match, including `statistics` when available |
| `/games/{id}/events` | SHL play-by-play events (chronological) with availability metadata |
| `/teams/{id}` | Team details, including `standing` (object or null) |
| `/teams/{id}/games` | Team matches; same filters as league matches |
| `/teams/{id}/players` | HA: current roster, including players without statistics; SHL: imported players |
| `/teams/{id}/goalkeepers` | Imported goalkeepers for this team |
| `/teams/{id}/standings` | Table row for this team |
| `/players/{id}` | Player details, `stats` and `goalkeeper_stats` (object or null) |

Detail routes also work under `/leagues/{league}`, for example
`/leagues/shl/games/{id}`. A mismatched league or nonexistent ID returns 404.
There is no standalone `/events` route; use `/games/{id}/events`.

## Filters and pagination

All seasonal lists accept `season=2026/2027`. Default is the configured season.
Player, goalkeeper and match lists accept `limit` (1–200) and `offset` (default 0).
Continue fetching pages until a page contains fewer than `limit` items.
League lists also accept `team_id`.

Match filters:

- `date=YYYY-MM-DD`, interpreted in `Europe/Stockholm`.
- `date_from=YYYY-MM-DD` and `date_to=YYYY-MM-DD`, inclusive.
- `status=scheduled|live|finished|postponed|cancelled`.
- `order=asc|desc`. Default is ascending for `status=scheduled`, descending otherwise.

SHL scheduled scores are `null` when the source says `N/A`; display a dash
instead of an invented 0–0 result.

Examples:

```text
/leagues/ha/games?date=2026-09-30
/leagues/shl/players?sort=goals&limit=25
/teams/{id}/games?status=scheduled&order=asc&limit=1
/teams/{id}/games?status=finished&order=desc&limit=5
/leagues/shl/players?limit=200&offset=200
```

Invalid dates, sort keys or query shapes return 400 with `{"error":"..."}`.
Unexpected backend/database failures return 503. Unsupported methods return 405.

## Match fields

Existing `home_team` and `away_team` remain name strings. Use the IDs to join:

```typescript
type Game = {
  id: number;
  external_id: string;
  league: 'shl' | 'ha';
  season: string;
  home_team_id: number;
  away_team_id: number;
  home_team: string;
  away_team: string;
  home_team_short_name: string | null;
  away_team_short_name: string | null;
  home_team_logo_url: string | null;
  away_team_logo_url: string | null;
  home_score: number | null;
  away_score: number | null;
  start_time: string;       // Legacy local SQL datetime, not JS Date input.
  start_time_iso: string;   // ISO 8601 with timezone offset; use this in Expo.
  status: 'scheduled' | 'live' | 'finished' | 'postponed' | 'cancelled';
  period: string | null;
  clock: string | null;              // Period time as last published by the source.
  clock_changed_at: string | null;   // ISO; when the importer saw `clock` change. Live only.
  clock_running: boolean;            // Live, not intermission, clock changed within 45 s.
  intermission: boolean | null;      // SHL live only; null otherwise.
  arena: string | null;
  updated_at: string;
  updated_at_iso: string;   // Time this record was imported, not source event time.
  events_available: boolean;          // true when /events has been imported for this match.
  events_updated_at: string | null;   // ISO; last event import.
  statistics_available: boolean;
  statistics_updated_at: string | null;
  statistics: GameStatistics | null;  // Only filled on /games/{id}; always null in lists.
};

type TeamGameStats = {      // Each value is number | null; null = not published.
  goals: number | null;
  shots_on_goal: number | null;
  saves: number | null;
  penalty_minutes: number | null;
  faceoffs_won: number | null;
  hits: number | null;
  blocked_shots: number | null;
  power_play_goals: number | null;
  power_play_opportunities: number | null;
  short_handed_goals: number | null;
};

type GameStatistics = {
  home: { team_id: number; total: TeamGameStats | null; periods: ({ period: number } & TeamGameStats)[] };
  away: { team_id: number; total: TeamGameStats | null; periods: ({ period: number } & TeamGameStats)[] };
};
```

## Match events

`/games/{id}/events` returns SHL events in match order (period, then clock).
Shots are not events; they are counted in `statistics`. HA has no event source.

```typescript
type GameEvent = {
  id: number;                 // Local ID.
  external_id: string;        // Stable source ID; use it to dedupe and for notifications.
  type: 'goal' | 'penalty' | 'goalkeeper' | 'timeout' | 'shootout_attempt' | 'period_end';
  period: string;             // "1", "2", "3", "4" = overtime, "SO" = shootout.
  clock: string | null;       // Elapsed time in period, MM:SS; null for period_end and shootout.
  team_id: number | null;
  team_side: 'home' | 'away' | null;
  player: string | null;      // Scorer, penalised player or goalkeeper.
  player_number: string | null;
  home_score: number | null;  // Score after the goal; only on goals.
  away_score: number | null;
  details: null
    | { assists: { name: string; number: string | null; external_id: string | null }[];
        strength: string | null;      // Source code, e.g. "EQ", "PP1", "SH1".
        empty_net: boolean | null; penalty_shot: boolean | null; player_external_id?: string }
    | { offence: string | null;       // Source code, e.g. "TRIP", "HOOK".
        penalty: string | null;       // e.g. "2 min".
        penalty_type: string | null;  // e.g. "Minor".
        player_external_id?: string }
    | { entering: boolean; player_external_id?: string }   // goalkeeper in/out
    | { scored: boolean; game_winning: boolean | null; attempt: number | null;
        player_external_id?: string };                       // shootout_attempt
  updated_at: string;
};
```

The deciding shootout goal is also a `goal` in period `"SO"` with the final
score; the other attempts are `shootout_attempt`. In `statistics`, period 4 is
overtime and period 99 is the shootout, as numbered by the source. A live
match's `period` can likewise be `"SO"`, with `clock` null.

`meta.available` is true once events have been imported for the match, even
when the list is still empty at the start of a match. Events the source
withdraws (for example a disallowed goal) disappear from the list, so
compare `external_id`s rather than counting rows. Events and statistics are
refreshed with the live score while a match is on and for ten minutes after it
ends; earlier finished matches are filled in by the schedule job.

## Goalkeepers

`/leagues/{league}/goalkeepers` returns identity, team ID/name/logo, position,
number, `gp`, `games_played`, `saves`, `shots_against`, `save_percentage`,
`goals_against`, `goals_against_average`, `wins`, `losses`, `shutouts`,
`minutes_played`, and `updated_at`.

`gp` is the provider's GP value; use `games_played` (GPI) for appearances.
`save_percentage` is a JSON number on a 0–100 scale (e.g. 93.10), or null when
undefined. `goals_against_average` is numeric or null. Missing values must not
be displayed as zero. HA save percentage is computed from actual saves and
shots against; GAA is not averaged across multiple teams without playing-time
weights. HA playing time is unavailable and remains null.

Sort keys: `save_percentage` (default), `goals_against_average` (ascending),
`saves`, `shutouts`, `wins` (descending). Null values sort last.

## Coverage and live limitations

The app must inspect `meta` and `/capabilities`, rather than infer coverage
from a successful HTTP response.

- SHL: table, published player statistics, goalkeeper statistics and the **full
  regular-season schedule**, including upcoming matches and results. While a
  match is on, status, score, period and period time are polled from SHL's
  per-game overview; there is no streaming live feed.
- HA: full published current team rosters, table, schedule and results,
  point statistics for **top 25 points leaders**, and goalkeeper statistics
  from published leaderboards. `/teams/{id}/players` and `/leagues/ha/players` include all players from the
  published current team registers, including goalkeepers. Players without
  imported point statistics have `stats_available: false` and null statistics.
  Roster imports run every 600 seconds independently of leaderboard imports;
  `meta.rosters_last_successful_import` records their freshness.
  Player counts may change as teams update their registers.
- The full schedule refreshes every **120 seconds**. Matches that are live, or
  start within five minutes, refresh every **10 seconds**
  (`meta.live_refresh_interval_seconds`, `/capabilities`
  `live_refresh_interval_seconds`). Standings refresh every **300 seconds**;
  players and goalkeepers every **600 seconds**. Source caching can add delay.
- The app can poll live matches every 10 seconds. That is the import interval,
  not a guarantee that the source has published new data. `meta.last_successful_import` is the latest successful collector
  run, not the event timestamp or proof that the source itself is current.
- SHL has play-by-play events (goals with assists, penalties, goalkeeper
  changes, timeouts, period ends) and team statistics per match and period.
  `meta.events_available`/`meta.game_statistics_available` and
  `/capabilities` per league `events`/`game_statistics` show this. The
  top-level `events` and `game_statistics` stay false, since HA has neither.
- There is **no player statistics per match, shot map or push service**.
- SHL live matches have `period` (the source period number as a string) and
  `clock`: elapsed time in that period (`MM:SS`) as last published, e.g.
  `"19:36"`. SHL publishes it in steps of roughly 20–30 seconds and at
  stoppages, so it does not change every second. During an intermission
  `intermission` is true and `clock` shows the period's final time (`"20:00"`).
- To show a ticking clock, count up on the client while `clock_running` is
  true: `clock + min(now − clock_changed_at, 40 s)`, at most `"20:00"` in
  periods 1–3 (`/capabilities` `shl.clock_extrapolation_max_seconds`).
  When `clock_running` is false, show `clock` as published. Label the value as
  estimated: it keeps counting during a stoppage the source has not yet
  reported, so it may step back a few seconds at the next update.
  `clock` is null for finished and scheduled matches and for HA
  (`meta.clock_available`; `/capabilities` per league `match_clock`, where
  SHL is `'period_elapsed_at_import'`). The top-level `match_clock` stays
  false, since HA has no clock. Never show an estimate as source time, and
  never invent goal events from an empty response.
- An existing match without imported events (all HA matches, SHL matches
  not yet imported) responds with `data: []` and `meta.available: false`, not
  a 404. This means the feed is unavailable, not that the match had no events.
  An unknown match correctly returns 404.
- `live` in HA means the source marked a current period on an unfinished
  match. SHL is `live` when the per-game overview reports the match as ongoing
  or in an intermission, and `finished` when it reports the match as ended.
  Intermissions are marked with `intermission: true`.

If needed, show “Händelser saknas”, “Matchklocka saknas” or
“Senast importerad …” in the arena view. Preserve cached information and its
original timestamp when offline. Goal notifications may use new SHL event
`external_id`s, but the app only learns of them when it polls; there is no push.

## Roster and statistics are separate

A player must not disappear from the app because statistics are missing.
For HA rosters, render every item in `data`, including goalkeepers and
players with `stats_available: false`. Display null points, goals, assists
and appearances as unavailable (for example “—”), not as zero.
`stats_updated_at` indicates the last point-statistics import for that player;
`updated_at` in HA player lists indicates their roster import.
The league list is paginated; use `limit=200` and `offset` to fetch all players.
Current rosters do not imply full historical season squads.
