Developers

Build on League Dispatcher with the official SDKs for TypeScript, Python and .NET, generated from our OpenAPI description.

Experimental The SDKs and the public API are experimental

Any release may include breaking changes, without a deprecation period, while we shape the API with early users. Keep the package you tested with in your project and read the release notes before upgrading.

Browse the API reference

Every public operation and model, grouped by area, with examples (in English).

Get started

  1. Get an API token

    A league admin turns on API access and creates a token with the permissions your integration needs (paid plans). How to create a token

  2. Install the SDK

    The SDKs are downloaded from this site, not from npm, PyPI or NuGet, and only the latest version is online. Download the package into a vendor folder of your project, install it from there and commit that folder, so your builds keep working after a new release. Each SDK uses its platform's usual HTTP library (fetch, httpx, HttpClient); its other dependencies come from npm, PyPI or NuGet as usual.

    TypeScript · 1.0.146

    curl -fL --create-dirs -o vendor/leaguedispatcher-sdk-1.0.146.tgz https://leaguedispatcher.com/sdk/leaguedispatcher-sdk-1.0.146.tgz
    npm install ./vendor/leaguedispatcher-sdk-1.0.146.tgz

    leaguedispatcher-sdk-1.0.146.tgz · SHA-256 953780d712cae88525270d4c34d875bb06f7eefc89a1ab650c86320b583cc70e

    Python · 1.0.146

    curl -fL --create-dirs -o vendor/leaguedispatcher-1.0.146-py3-none-any.whl https://leaguedispatcher.com/sdk/leaguedispatcher-1.0.146-py3-none-any.whl
    pip install ./vendor/leaguedispatcher-1.0.146-py3-none-any.whl

    leaguedispatcher-1.0.146-py3-none-any.whl · SHA-256 49b94528f0cd3aea9f4f1e121ef0324224dc00dd4a3710572ecdfe316e121fd7

    .NET · 1.0.146

    curl -fL --create-dirs -o vendor/LeagueDispatcher.Sdk.1.0.146.nupkg https://leaguedispatcher.com/sdk/LeagueDispatcher.Sdk.1.0.146.nupkg
    dotnet new nugetconfig
    dotnet nuget add source ./vendor --name leaguedispatcher --configfile nuget.config
    dotnet add package LeagueDispatcher.Sdk --version 1.0.146

    LeagueDispatcher.Sdk.1.0.146.nupkg · SHA-256 6d361db7a76fd0053c37b96cf55ffa4a506e1a87aed1b821fb32ca45e75869f1

  3. Connect

    Send the token in the X-Api-Key header, from your server. The samples below read it from the LEAGUE_DISPATCHER_API_TOKEN environment variable.

Samples

Every sample is compiled against the published SDKs, so it works as shown.

Create a client

Authenticate with your API token. The token is only sent to the host you call.

import { ApiKeyAuthenticationProvider, ApiKeyLocation } from '@microsoft/kiota-abstractions';
import { DefaultRequestAdapter } from '@microsoft/kiota-bundle';
import { createLeagueDispatcherClient, type LeagueDispatcherClient } from '@leaguedispatcher/sdk';

export function createClient(): LeagueDispatcherClient {
  const token = process.env.LEAGUE_DISPATCHER_API_TOKEN;
  if (!token) throw new Error('Set LEAGUE_DISPATCHER_API_TOKEN to a league API token.');
  const baseUrl = process.env.LEAGUE_DISPATCHER_BASE_URL ?? 'https://api.leaguedispatcher.com/v1';

  // The token goes in the X-Api-Key header, over HTTPS, and only to the host you call.
  const auth = new ApiKeyAuthenticationProvider(token, 'X-Api-Key', ApiKeyLocation.Header, new Set([new URL(baseUrl).hostname]));
  const adapter = new DefaultRequestAdapter(auth);
  adapter.baseUrl = baseUrl;
  return createLeagueDispatcherClient(adapter);
}

List the players

Read the league's roster: every player with their status.

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';

export async function listPlayers(client: LeagueDispatcherClient): Promise<void> {
  const roster = await client.players.get();

  for (const player of roster?.players ?? []) {
    console.log(`${player.name}: ${player.status}`);
  }
}

Add, rename and remove a player

Change one player at a time; the league creates the id of a new player. Edits made on other devices meanwhile are kept. The add sends an Idempotency-Key, so it can be retried safely.

import { randomUUID } from 'node:crypto';
import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import type { Player } from '@leaguedispatcher/sdk/models';

/** Makes a create safe to retry: a repeat with the same key answers what the first call created. */
const IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';

/**
 * Adds a player to the roster; the league creates the id and the player starts Not available.
 * When the answer is lost (timeout, dropped connection), call again with the same idempotencyKey:
 * the league answers the player it already added instead of adding a second one.
 */
export async function addPlayer(
  client: LeagueDispatcherClient,
  name: string,
  idempotencyKey: string = randomUUID(),
): Promise<Player | undefined> {
  return client.players.post({ name }, { headers: { [IDEMPOTENCY_KEY_HEADER]: idempotencyKey } });
}

export async function renamePlayer(client: LeagueDispatcherClient, playerId: string, name: string): Promise<void> {
  await client.players.byPlayerId(playerId).put({ name });
}

/** Removes the player from the roster (and from their court); their games stay. */
export async function removePlayer(client: LeagueDispatcherClient, playerId: string): Promise<void> {
  await client.players.byPlayerId(playerId).delete();
}

Check a player in

Mark a player as arrived and waiting for a game (needs Change Player Status).

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import { PlayerStatusObject } from '@leaguedispatcher/sdk/models';

export async function checkIn(client: LeagueDispatcherClient, playerId: string): Promise<void> {
  // Idle = arrived and waiting for a game.
  await client.gameDay.players.byPlayerId(playerId).status.put({ status: PlayerStatusObject.Idle });
}

Start the next game

Ask the league's matchmaking algorithm for the next game and start it (needs Dispatch).

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';

/** Returns the court the game started on, or undefined when no game can start. */
export async function dispatchNextGame(client: LeagueDispatcherClient): Promise<string | undefined> {
  // The league's matchmaking algorithm proposes the next game.
  const next = await client.gameDay.nextGames.get();
  const proposal = next?.propositions?.[0];
  if (!proposal?.courtId || !proposal.players) {
    console.log('No game can start right now.');
    return undefined;
  }

  await client.gameDay.courts.byCourtId(proposal.courtId).game.post({
    playerIds: proposal.players.map(p => p.id!),
    teams: proposal.teams,
  });
  console.log(`Game started on court ${proposal.courtId}`);
  return proposal.courtId;
}

Finish a game

Record the winners and the score of a game (needs Finish Game).

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';

export async function finishGame(client: LeagueDispatcherClient, courtId: string): Promise<void> {
  const state = await client.gameDay.get();
  const court = state?.courts?.find(c => c.id === courtId);
  if (!court?.players) throw new Error(`Court ${courtId} not found`);
  const names = new Map((state?.players ?? []).map(p => [p.id, p.name]));

  // The first half of the court's players won.
  const winnerIds = court.players.slice(0, court.players.length / 2);
  await client.gameDay.courts.byCourtId(courtId).game.finish.post({
    winners: {
      winnerScore: 21,
      looserScore: 15,
      players: winnerIds.map(id => ({ id, name: names.get(id) })),
    },
    // The game this finishes: a retry can never finish the next game on the court.
    gameStartTime: court.lastPlayDate,
  });
}

Recent games

List the games of the last week with their winners.

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import type { Game } from '@leaguedispatcher/sdk/models';

/** Every game of the last week: the list comes in pages, so send each nextPageToken back until there is none. */
export async function listRecentGames(client: LeagueDispatcherClient): Promise<Game[]> {
  const fromDate = Date.now() - 7 * 24 * 60 * 60 * 1000;
  const games: Game[] = [];
  let pageToken: string | undefined;
  do {
    const page = await client.games.get({ queryParameters: { fromDate, pageToken } });
    games.push(...(page?.games ?? []));
    pageToken = page?.nextPageToken ?? undefined;
  } while (pageToken);
  return games;
}

export async function recentGames(client: LeagueDispatcherClient): Promise<void> {
  for (const game of await listRecentGames(client)) {
    const ended = new Date(game.endTime ?? 0).toLocaleString();
    const winners = (game.winners?.players ?? []).map(p => p.name).join(', ');
    console.log(`${ended}  ${winners} won ${game.winners?.winnerScore}-${game.winners?.looserScore}`);
  }
}

Handle errors

Every error comes with an HTTP status and a machine-readable code.

import type { LeagueDispatcherClient } from '@leaguedispatcher/sdk';
import type { ErrorResponse } from '@leaguedispatcher/sdk/models';

export async function handleErrors(client: LeagueDispatcherClient): Promise<void> {
  try {
    await client.tournaments.byTournamentId('unknown-tournament').get();
  } catch (err) {
    // Every error of the public API carries a machine-readable code.
    const error = err as ErrorResponse;
    console.log(`${error.responseStatusCode} ${error.code}: ${error.messageEscaped}`);
  }
}

Receive webhooks

Get every league event pushed to your server as it happens. Verify the signature with the official Standard Webhooks library (or HMAC-SHA256 in .NET), ignore retries you already handled using the webhook-id header, answer the verification challenge with the SDK's WebhookVerificationResponse, and read the body with the SDK models: it is the same payload the apps receive live. Everything in it is typed, with nothing to parse twice: actionName says which event it is, and the event's data is in its own field (state for the players and courts that changed, including a finished game; verification for the challenge; updatedAt when settings changed). events lists what happened, as the same records the events API returns. The .NET sample also shows an ASP.NET Core controller that decodes a finished game (score, winners and losers).

// Receives League Dispatcher webhooks: verifies the signature (Standard Webhooks, with the official
// standardwebhooks library), answers the verification challenge, skips retries already handled, and reads the payload
// with the SDK's models. The body is the same payload the app receives live: state events carry the players and courts
// that changed in payload.state.
import http from 'node:http';
import { JsonParseNode, JsonSerializationWriter } from '@microsoft/kiota-serialization-json';
import {
  createSignalREventPayloadFromDiscriminatorValue,
  serializeWebhookVerificationResponse,
  SignalRServerEventObject,
  type SignalREventPayload,
  type WebhookVerificationResponse,
} from '@leaguedispatcher/sdk/models';
import { Webhook, WebhookVerificationError } from 'standardwebhooks';

export interface WebhookEvent {
  payload: SignalREventPayload;
  /**
   * Set for a WebhookVerification: the JSON body (a WebhookVerificationResponse) to answer with, status 200. The
   * endpoint gets no other event until it has answered one.
   */
  verificationAnswer?: string;
}

export class WebhookReceiver {
  private readonly webhook: Webhook;
  // A retry carries the same webhook-id. Keep the ids in a shared store with an expiry when you run several instances.
  private readonly seen = new Set<string>();

  /** secret: the whsec_... signing secret shown when the webhook was added. */
  constructor(secret: string) {
    this.webhook = new Webhook(secret);
  }

  /**
   * Returns the event, or null for a retry of an event already received.
   * Throws WebhookVerificationError when the request is not a fresh delivery from League Dispatcher.
   */
  receive(headers: Record<string, string>, body: string): WebhookEvent | null {
    this.webhook.verify(body, headers);
    const id = headers['webhook-id'];
    if (this.seen.has(id)) return null;
    this.seen.add(id);

    const payload = new JsonParseNode(JSON.parse(body)).getObjectValue<SignalREventPayload>(createSignalREventPayloadFromDiscriminatorValue);
    if (payload.actionName === SignalRServerEventObject.WebhookVerification && payload.verification) {
      return { payload, verificationAnswer: verificationAnswer({ challenge: payload.verification.challenge }) };
    }
    return { payload };
  }
}

/** Sends the challenge back, unchanged, as the SDK's WebhookVerificationResponse. */
function verificationAnswer(response: WebhookVerificationResponse): string {
  const writer = new JsonSerializationWriter();
  writer.writeObjectValue(undefined, response, serializeWebhookVerificationResponse);
  return new TextDecoder().decode(writer.getSerializedContent());
}

/**
 * A minimal HTTP endpoint: 200 with the answer to a verification, 204 once an event is handled (or a retry), 401 when
 * the request is not from League Dispatcher.
 */
export function serve(port: number, secret: string, onEvent: (event: WebhookEvent) => void): http.Server {
  const receiver = new WebhookReceiver(secret);
  return http.createServer((req, res) => {
    let body = '';
    req.setEncoding('utf8');
    req.on('data', chunk => { body += chunk; });
    req.on('end', () => {
      try {
        const event = receiver.receive(req.headers as Record<string, string>, body);
        if (event?.verificationAnswer) {
          res.writeHead(200, { 'content-type': 'application/json' }).end(event.verificationAnswer);
          return;
        }
        if (event) onEvent(event);
        res.writeHead(204).end();
      } catch (err) {
        res.writeHead(err instanceof WebhookVerificationError ? 401 : 500).end();
      }
    });
  }).listen(port);
}

Good to know

Base URL
https://api.leaguedispatcher.com/v1. The SDKs use it by default.
Authentication
A league API token in the X-Api-Key header. The token identifies its league, so no other header is needed. Keep it server-side.
Permissions
A token can call an operation only if it was given the permission that operation needs; otherwise the API answers 403 FORBIDDEN.
Errors
4xx and 5xx responses carry an ErrorResponse with a code (for example API_TOKEN_INVALID, API_ACCESS_DISABLED, PLAN_FEATURE_UNAVAILABLE, RATE_LIMITED) and a message for logs.
Rate limits
Requests are rate limited per token. On 429 RATE_LIMITED, wait as long as the Retry-After header says, then retry.
Safe retries
When an answer is lost (timeout, dropped connection), send the request again. Creates and the start or finish of a game day take an Idempotency-Key header: send a new UUID for each action and the same one on its retries, and the league answers what the first call did instead of doing it twice. Dispatching a game and the other actions on an existing court, tournament or season recognize their own repeat without a key; to retry a game finish, resend the same gameStartTime (the court's lastPlayDate as read), without which a retry can finish the court's next game.
Versioning
The SDKs are released with every League Dispatcher release and carry its version. Any release, even a patch, may contain breaking changes, and so may the public API. Only the latest version can be downloaded. Real-time updates reach your server through webhooks (below).
Webhooks
Admins add up to 2 HTTPS endpoints in Setup > API access. Each one must first answer a verification: a WebhookVerification delivery whose verification.challenge your server sends back in the same response ({"challenge": "..."}); until then it gets no event. Each delivery is a POST with webhook-id (the same on every retry), webhook-timestamp, a signature header (Standard Webhooks HMAC, or a shared secret you choose, in a header you name), X-League-Id and X-League-Name. Deliveries are best effort: failures are retried a few times, the order is not guaranteed, and after 5 failures in a row deliveries stop for a minute, then one retry decides: the wait doubles after each failed retry (up to an hour), and an endpoint that keeps failing is paused. Events skipped meanwhile are not resent: read the current state through the API after a gap.

The SDKs are generated from our public OpenAPI description, which you can also use with your own tools: download openapi.public.yaml