guides

A typed TypeScript client for the PricedOdds odds API, run on Node 24

By · Published · Updated · 5 min read

A typed client for a sports odds API is a small wrapper around fetch with interfaces that match the JSON. The one below is 174 lines of TypeScript with no packages: it covers books, events, the odds of one game and the best price per selection, follows the next cursor across pages, waits and retries when the API answers 429, and turns error bodies into a typed PricedOddsError. Node 24 runs the .ts files directly, so there is nothing to compile or install. We ran it on November 25, 2026, 09:38 UTC against live NBA prices.

What do I need for a TypeScript odds client?

  • A PricedOdds API key, sent as Authorization: Bearer $PRICEDODDS_API_KEY.
  • Node 24. It runs TypeScript files by stripping the type annotations, as described in the Node.js TypeScript documentation. We ran the code on Node 24.22.1 without installing anything.
  • Optional: the typescript package, only if you want tsc to check the types. Node removes the types; it does not check them.

Type stripping only works with syntax that can be erased: no enum, no namespace with code and no constructor parameter properties such as constructor(private key: string). The client sticks to interfaces, type aliases and classes with normal fields, so it runs in Node and passes tsc with --erasableSyntaxOnly.

How is the client built?

  1. Types written by hand. Each interface (Book, GameEvent, Market, Selection, BestRow) follows a real response of the API. Fields that can be missing, such as fair on a selection, are optional, so the compiler makes you handle them.
  2. One private #get method. It builds the URL with URLSearchParams, adds the key, and returns the JSON as the type you ask for. The cast as T is a promise you make to the compiler, not a check at runtime; if you need runtime checks, validate the parts you use.
  3. Paging. List endpoints return data and a next cursor. #pages is an async generator that asks again with cursor until next is empty, so for await gives you every row without thinking about pages.
  4. Rate limits. On HTTP 429 it waits the seconds in Retry-After or RateLimit-Reset and tries again, up to three times. Every answer carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers; the limit of each plan, in requests per second, is on the pricing page.
  5. Errors. Error bodies have a code, a message, a fix and a request_id. The client throws them as PricedOddsError, so err.code is typed and instanceof tells API errors apart from network errors. The codes are listed in the error docs.

What is the code?

The client, pricedodds-client.ts:

// pricedodds-client.ts: a small typed client for the PricedOdds REST API.
// Node 24 runs it as is (it strips the types); no packages.

// ---- Response types, written by hand from real responses ----
export interface Book {
  id: string;
  name: string;
  type: string;            // "sportsbook", "exchange", "prediction_market"...
  region: string;
  is_sharp: boolean;
  reference_only: boolean;
  status: string;
  features: string[];      // e.g. "prematch", "live", "props"
  pickable: boolean;
  included: boolean;
}

export interface Team { id: string; name: string; abbr: string }

export interface GameEvent {
  id: string;
  sport: string;
  league: { id: string; name: string };
  home: Team;
  away: Team;
  startsAt: string;        // ISO 8601, UTC
  status: string;          // "scheduled", "live"...
  live: Record<string, unknown> | null;
  books: string[];
  markets_available: number;
}

export interface BookPrice {
  book: string;
  decimal: number;
  american: number;
  implied: number;
  updatedAt: string;
  changedAt: string;
}

export interface BestPrice { book: string; decimal: number; american: number }

export interface FairPrice {
  american: number;
  prob: number;
  decimal?: number;
  method?: string;
  sources?: string[];
}

export interface Selection {
  id: string;
  side: string;
  line: number | null;
  prices: BookPrice[];
  best: BestPrice;
  fair?: FairPrice | null;
}

export interface Market {
  id: string;
  market: string;          // "moneyline", "spread", "total"...
  period: string;          // "game", "1h", "1q"...
  selections: Selection[];
  margin: Record<string, number>;
}

export interface EventOdds { event: GameEvent; markets: Market[] }

export interface BestRow {
  event_id: string;
  matchup: string;
  startsAt: string;
  market: string;
  period: string;
  selections: {
    selection_id: string;
    side: string;
    line: number | null;
    best: BestPrice;
    fair?: FairPrice | null;
    ev?: number;
  }[];
}

interface Page<T> { data: T[]; next?: string | null; asOf: string }

interface ErrorBody {
  error: { code: string; message: string; fix?: string; docs_url?: string; request_id?: string };
}

// ---- Errors ----
export class PricedOddsError extends Error {
  readonly status: number;
  readonly code: string;
  readonly fix: string | undefined;
  readonly requestId: string | undefined;

  constructor(status: number, body: ErrorBody | null) {
    super(body?.error.message ?? `HTTP ${status}`);
    this.name = "PricedOddsError";
    this.status = status;
    this.code = body?.error.code ?? `http_${status}`;
    this.fix = body?.error.fix;
    this.requestId = body?.error.request_id;
  }
}

type Params = Record<string, string | undefined>;
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// ---- Client ----
export class PricedOdds {
  readonly #key: string;
  readonly #base: string;
  requests = 0;
  retries = 0;

  constructor(key: string, base = "https://api.pricedodds.com/v1") {
    this.#key = key;
    this.#base = base;
  }

  async #get<T>(path: string, params: Params = {}): Promise<T> {
    const url = new URL(this.#base + path);
    for (const [name, value] of Object.entries(params)) {
      if (value !== undefined) url.searchParams.set(name, value);
    }
    for (let attempt = 1; ; attempt++) {
      this.requests++;
      const res = await fetch(url, { headers: { Authorization: `Bearer ${this.#key}` } });
      if (res.status === 429 && attempt < 4) {
        // Wait what the server asks for, then try again.
        const wait = Number(res.headers.get("retry-after") ?? res.headers.get("ratelimit-reset") ?? 1);
        this.retries++;
        await sleep(Math.max(wait, 1) * 1000);
        continue;
      }
      if (!res.ok) {
        const body = (await res.json().catch(() => null)) as ErrorBody | null;
        throw new PricedOddsError(res.status, body);
      }
      return (await res.json()) as T;
    }
  }

  // Follows the `next` cursor until the last page.
  async *#pages<T>(path: string, params: Params): AsyncGenerator<T> {
    let cursor: string | undefined;
    do {
      const page = await this.#get<Page<T>>(path, { ...params, cursor });
      yield* page.data;
      cursor = page.next ?? undefined;
    } while (cursor);
  }

  async books(): Promise<Book[]> {
    return (await this.#get<Page<Book>>("/books")).data;
  }

  events(league: string): AsyncGenerator<GameEvent> {
    return this.#pages<GameEvent>("/events", { league });
  }

  async eventOdds(eventId: string, markets: string[]): Promise<EventOdds> {
    const path = `/events/${encodeURIComponent(eventId)}/odds`;
    return (await this.#get<{ data: EventOdds }>(path, { markets: markets.join(",") })).data;
  }

  best(league: string, markets: string[]): AsyncGenerator<BestRow> {
    return this.#pages<BestRow>("/best", { league, markets: markets.join(",") });
  }
}

A script that uses it, odds-client-demo.ts:

// odds-client-demo.ts: uses the typed client on one league.
// Usage: PRICEDODDS_API_KEY=... node odds-client-demo.ts
import { PricedOdds, PricedOddsError, type GameEvent } from "./pricedodds-client.ts";

const key = process.env.PRICEDODDS_API_KEY;
if (!key) throw new Error("Set PRICEDODDS_API_KEY");
const LEAGUE = process.env.LEAGUE ?? "nba";
const po = new PricedOdds(key);
const fmt = (american: number) => (american > 0 ? `+${american}` : `${american}`);

// 1. Books on the catalog
const books = await po.books();
console.log(`books: ${books.length}, types: ${[...new Set(books.map((b) => b.type))].join(", ")}`);

// 2. Every event of the league, across pages
const events: GameEvent[] = [];
for await (const event of po.events(LEAGUE)) events.push(event);
const upcoming = events
  .filter((e) => e.status === "scheduled")
  .sort((a, b) => a.startsAt.localeCompare(b.startsAt));
console.log(`${LEAGUE} events: ${events.length}, not started: ${upcoming.length}`);

// 3. Full-game odds of the next game, every book on the plan
const game = upcoming[0];
if (game) {
  const odds = await po.eventOdds(game.id, ["moneyline", "spread", "total"]);
  console.log(`${game.away.abbr} @ ${game.home.abbr}, starts ${game.startsAt}, ${odds.markets.length} markets`);
  for (const market of odds.markets.filter((m) => m.period === "game")) {
    for (const s of market.selections) {
      const fair = s.fair ? fmt(s.fair.american) : "n/a";
      console.log(`  ${market.market} ${s.side} ${s.line ?? ""}: best ${s.best.book} ${fmt(s.best.american)}, fair ${fair}, ${s.prices.length} books`);
    }
  }
}

// 4. Best price per selection for the whole league, all pages
let rows = 0, selections = 0;
for await (const row of po.best(LEAGUE, ["moneyline@game"])) {
  rows++;
  selections += row.selections.length;
}
console.log(`best moneyline: ${rows} rows, ${selections} selections`);

// 5. A typed error
try {
  for await (const _ of po.events("not-a-league")) break;
} catch (err) {
  if (!(err instanceof PricedOddsError)) throw err;
  console.log(`error: HTTP ${err.status} ${err.code}: ${err.message}`);
}

console.log(`requests: ${po.requests}, retried after 429: ${po.retries}`);

Put both files in one folder and run PRICEDODDS_API_KEY=$PRICEDODDS_API_KEY node odds-client-demo.ts. Set LEAGUE to any league id from the coverage page to use another league. The import ends in .ts because Node needs the real file name; with tsc, that needs allowImportingTsExtensions and noEmit.

What did a real run return?

We ran odds-client-demo.ts on November 25, 2026, 09:38 UTC, on Node 24.22.1 with LEAGUE=nba. Its output:

books: 16, types: sportsbook, social_sportsbook, exchange, prediction_market, offshore_sportsbook, sharp_reference
nba events: 50, not started: 50
MIA @ PHI, starts 2026-11-25T22:00:00.000Z, 21 markets
  moneyline home : best polymarket -104, fair -105, 15 books
  moneyline away : best novig +104, fair +105, 15 books
  spread home -1.5: best novig +102, fair +104, 13 books
  spread away 1.5: best polymarket -104, fair -104, 13 books
  total over 237.5: best polymarket -108, fair -104, 12 books
  total under 237.5: best novig +106, fair +104, 12 books
best moneyline: 29 rows, 58 selections
error: HTTP 400 unknown_league: Unknown league 'not-a-league'.
requests: 6, retried after 429: 0

The catalog returned 16 books of 6 types: sportsbook, social_sportsbook, exchange, prediction_market, offshore_sportsbook and sharp_reference. The NBA had 50 events, none started yet at that hour. For the next game, MIA @ PHI, the client printed the full-game moneyline, spread and total with the best price, the no-vig fair price and how many books priced each side. The best-price call for the whole league took 2 pages, and the generator joined them into 29 rows and 58 selections. The bad league id came back as a PricedOddsError with HTTP 400 and code unknown_league. In all, 6 requests and no 429. These are prices of one morning, shown as an example and not as current prices.

What else we checked. tsc from TypeScript 5.9.3 with --strict --erasableSyntaxOnly --verbatimModuleSyntax found 0 errors in the two files. The run above never hit the rate limit, so we tested the retry against a small local server that answers 429 with Retry-After: 1 once and then 200: the client made 2 requests, retried 1 time and waited 1 second. The API side ran for real; the 429 ran against that stand-in.

How do I add another endpoint?

Write the interface for its rows and a method of one line. For example, the price changes since a cursor from GET /v1/changes would be a #get with league and since, and its rows carry american and prev_american. Check the fields in the docs or print one real response before you write the type. To find the key of a market or prop for the markets parameter, use the market key finder. For prices as they change, the REST client is the wrong tool: the JavaScript WebSocket tutorial keeps a live price map, and its code works in a .ts file once you add types.

What are the limits of hand-written types?

They describe the responses we saw, not a contract the compiler can enforce: if a field is missing in a response, TypeScript will not notice at runtime. Keep the types to the fields you use and mark the uncertain ones optional. The client keeps no cache, so each call is one request against your rate limit. The API returns current prices and changes, not history. Nothing here is betting advice.

One use of these calls on a site is an odds table rendered on your server, which keeps the key off the page.

FAQ

Is there an official TypeScript SDK?

No. There is no SDK or npm package; the API is plain JSON over HTTPS, and this article shows a small client you own and can change.

Can I use it in the browser?

Not as it is. The client sends your key on every request, and a key in browser code is public. Call the API from your server and send your page only the data it needs.

Does it work with Bun or Deno?

We only ran it on Node 24.22.1. It uses fetch, URL and async generators, which those runtimes also have, but we did not test them.

Where do I start?

Copy the two files, set your key and run the demo on one league. The fields are in the docs, the books and leagues are on the coverage page and more runnable examples are on the developers page. Every plan starts with a 3-day free trial with a $1 card verification that is refunded immediately. The plan you pick at signup is charged from day 4 unless you cancel before the trial ends. See pricing or create an account.