Développeurs

Construisez avec League Dispatcher grâce aux SDK officiels pour TypeScript, Python et .NET, générés à partir de notre description OpenAPI.

Expérimental Les SDK et l'API publique sont expérimentaux

Chaque version peut apporter des changements incompatibles, sans période de dépréciation, pendant que nous façonnons l'API avec les premiers utilisateurs. Gardez dans votre projet le paquet que vous avez testé et lisez les notes de version avant de mettre à jour.

Parcourir la référence de l’API

Toutes les opérations et tous les modèles publics, regroupés par domaine, avec des exemples (en anglais).

Pour commencer

  1. Obtenir un jeton API

    Un administrateur de la ligue active l'accès API et crée un jeton avec les permissions dont votre intégration a besoin (forfaits payants). Comment créer un jeton

  2. Installer le SDK

    Les SDK se téléchargent depuis ce site, et non depuis npm, PyPI ou NuGet, et seule la dernière version est en ligne. Téléchargez le paquet dans un dossier vendor de votre projet, installez-le depuis ce dossier et versionnez-le, pour que vos builds continuent de fonctionner après une nouvelle version. Chaque SDK utilise la bibliothèque HTTP habituelle de sa plateforme (fetch, httpx, HttpClient) ; ses autres dépendances viennent de npm, PyPI ou NuGet comme d'habitude.

    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. Se connecter

    Envoyez le jeton dans l'en-tête X-Api-Key, depuis votre serveur. Les exemples ci-dessous le lisent dans la variable d'environnement LEAGUE_DISPATCHER_API_TOKEN.

Exemples

Chaque exemple est compilé avec les SDK publiés : il fonctionne tel quel.

Créer un client

Authentifiez-vous avec votre jeton API. Le jeton n'est envoyé qu'à l'hôte appelé.

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);
}

Lister les joueurs

Lisez la liste des joueurs de la ligue avec leur statut.

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}`);
  }
}

Ajouter, renommer et retirer un joueur

Modifiez un joueur à la fois ; la ligue crée l’identifiant d’un nouveau joueur. Les modifications faites entre-temps sur d’autres appareils sont conservées. L’ajout envoie un en-tête Idempotency-Key : il peut être renvoyé sans risque.

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();
}

Enregistrer l'arrivée d'un joueur

Indiquez qu'un joueur est arrivé et attend une partie (permission Changer le statut des joueurs).

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 });
}

Lancer la partie suivante

Demandez la partie suivante à l'algorithme de la ligue et lancez-la (permission Répartition).

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;
}

Terminer une partie

Enregistrez les gagnants et le score d'une partie (permission Terminer la partie).

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,
  });
}

Parties récentes

Listez les parties de la dernière semaine avec leurs gagnants.

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}`);
  }
}

Gérer les erreurs

Chaque erreur fournit un statut HTTP et un code lisible par machine.

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}`);
  }
}

Recevoir des webhooks

Recevez chaque événement de la ligue sur votre serveur, en direct. Vérifiez la signature avec la bibliothèque officielle Standard Webhooks (ou HMAC-SHA256 en .NET), ignorez les nouvelles tentatives déjà traitées grâce à l'en-tête webhook-id, répondez au défi de vérification avec le WebhookVerificationResponse du SDK, et lisez le corps avec les modèles du SDK : ce sont les mêmes données que les applications reçoivent en direct. Tout y est typé, sans rien à analyser deux fois : actionName indique l'événement, et ses données sont dans leur propre champ (state pour les joueurs et les terrains qui ont changé, y compris une partie terminée ; verification pour le défi ; updatedAt quand des paramètres ont changé). events liste ce qui s'est passé, avec les mêmes enregistrements que l'API des événements. L'exemple .NET montre aussi un contrôleur ASP.NET Core qui décode une partie terminée (score, gagnants et perdants).

// 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);
}

Bon à savoir

URL de base
https://api.leaguedispatcher.com/v1. Les SDK l'utilisent par défaut.
Authentification
Un jeton API de ligue dans l'en-tête X-Api-Key. Le jeton identifie sa ligue : aucun autre en-tête n'est nécessaire. Gardez-le côté serveur.
Permissions
Un jeton ne peut appeler une opération que s'il a reçu la permission qu'elle exige ; sinon l'API répond 403 FORBIDDEN.
Erreurs
Les réponses 4xx et 5xx contiennent un ErrorResponse avec un code (par exemple API_TOKEN_INVALID, API_ACCESS_DISABLED, PLAN_FEATURE_UNAVAILABLE, RATE_LIMITED) et un message pour les journaux.
Limites de débit
Les requêtes sont limitées par jeton. Sur 429 RATE_LIMITED, attendez la durée indiquée par l'en-tête Retry-After, puis réessayez.
Nouvelles tentatives sans risque
Quand une réponse se perd (délai dépassé, connexion coupée), renvoyez la requête. Les créations ainsi que le début ou la fin d'une journée de jeu acceptent un en-tête Idempotency-Key : envoyez un nouvel UUID pour chaque action et le même à chacune de ses nouvelles tentatives, et la ligue renvoie ce que le premier appel a fait au lieu de le refaire. Lancer un match et les autres actions sur un terrain, un tournoi ou une saison existants reconnaissent leur propre répétition sans clé ; pour renvoyer la fin d'un match, renvoyez le même gameStartTime (le lastPlayDate du terrain tel que lu), sans lequel une nouvelle tentative peut terminer le match suivant du terrain.
Versions
Les SDK sont publiés avec chaque version de League Dispatcher et en portent le numéro. Chaque version, même corrective, peut contenir des changements incompatibles, tout comme l'API publique. Seule la dernière version peut être téléchargée. Les mises à jour en temps réel arrivent sur votre serveur par les webhooks (ci-dessous).
Webhooks
Les administrateurs ajoutent jusqu'à 2 points de terminaison HTTPS dans Configuration > Accès API. Chacun doit d'abord répondre à une vérification : un envoi WebhookVerification dont votre serveur renvoie le défi (verification.challenge) dans la même réponse ({"challenge": "..."}) ; d'ici là, il ne reçoit aucun événement. Chaque envoi est un POST avec webhook-id (identique à chaque nouvelle tentative), webhook-timestamp, un en-tête de signature (HMAC Standard Webhooks, ou un secret partagé de votre choix, dans un en-tête que vous nommez), X-League-Id et X-League-Name. Les envois sont faits au mieux : un échec est retenté quelques fois, l'ordre n'est pas garanti, et après 5 échecs consécutifs, les envois s'arrêtent une minute, puis un seul nouvel essai décide : l'attente double après chaque nouvel essai en échec (jusqu'à une heure), et un point de terminaison qui échoue sans cesse est mis en pause. Les événements ignorés entre-temps ne sont pas renvoyés : relisez l'état actuel par l'API après une interruption.

Les SDK sont générés à partir de notre description OpenAPI publique, que vous pouvez aussi utiliser avec vos propres outils : télécharger openapi.public.yaml