<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: orbistats</title>
    <description>The latest articles on DEV Community by orbistats (@orbistats).</description>
    <link>https://dev.to/orbistats</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4128592%2F14967761-af2b-4040-8ef3-7763e7f4e21b.png</url>
      <title>DEV Community: orbistats</title>
      <link>https://dev.to/orbistats</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/orbistats"/>
    <language>en</language>
    <item>
      <title>Odds Normalization Explained: How a Sports Odds API Turns Bookmaker Chaos Into One Schema</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Thu, 19 Nov 2026 18:37:08 +0000</pubDate>
      <link>https://dev.to/orbistats/odds-normalization-explained-how-a-sports-odds-api-turns-bookmaker-chaos-into-one-schema-4f2g</link>
      <guid>https://dev.to/orbistats/odds-normalization-explained-how-a-sports-odds-api-turns-bookmaker-chaos-into-one-schema-4f2g</guid>
      <description>&lt;p&gt;Odds Normalization Explained: How a Sports Odds API Turns Bookmaker Chaos Into One Schema&lt;/p&gt;

&lt;p&gt;Pull odds from three bookmakers and you will get three different answers to a simple question: what is the price on the home team? One feed calls the market “Match Winner”, another calls it “Full Time Result”, a third calls it “1X2”. One returns decimal odds, one returns fractions, one returns American odds. Team names are spelled differently, markets get suspended without warning, and no two feeds agree on what a “live” price means.&lt;/p&gt;

&lt;p&gt;Odds normalization is the work of turning all of that into one consistent structure, so that a price from one book can be compared, averaged, stored and displayed next to a price from another. It is also the difference between a product that ships in weeks and one that spends months maintaining parsers.&lt;/p&gt;

&lt;p&gt;This guide explains what normalization actually involves, walks through the maths every odds developer needs (formats, implied probability and the bookmaker margin), and shows working code. The examples use the Orbistats Odds API, which delivers pre-match and live odds in one schema across 13 sports.&lt;/p&gt;

&lt;p&gt;Why Raw Bookmaker Odds Are Hard to Use&lt;/p&gt;

&lt;p&gt;Each bookmaker built its feed for its own platform, not for yours. If you integrate directly, you inherit every one of those decisions. In practice, the same match can differ across feeds in at least four ways:&lt;/p&gt;

&lt;p&gt;What differs    Typical raw-feed variation  What a normalized feed gives you&lt;br&gt;
Market names    “Match Winner”, “Full Time Result”, “1X2”   One market name per market type&lt;br&gt;
Outcome structure   Arrays, nested objects, home/away vs team IDs   One outcome structure (home, draw, away)&lt;br&gt;
Odds format Decimal, fractional, American   One default format, with conversions available&lt;br&gt;
Entity naming   Different spellings and abbreviations for teams Consistent team and match identifiers&lt;/p&gt;

&lt;p&gt;Normalization maps all of this into a single schema once, centrally. According to the Odds API page, Orbistats pulls odds from major sportsbooks and maps them into one set of market names, one outcome structure and one odds format, so you integrate once instead of writing a parser per book.&lt;/p&gt;

&lt;p&gt;Odds Formats You Need to Understand&lt;/p&gt;

&lt;p&gt;Even with a normalized feed, you will convert formats, because your users may expect fractions in the UK or American odds in the US. Orbistats returns decimal odds by default, with fractional and American formats available.&lt;/p&gt;

&lt;p&gt;The formulas:&lt;/p&gt;

&lt;p&gt;Decimal → implied probability: 1 / decimal&lt;br&gt;
Decimal → fractional: decimal − 1 expressed as a fraction&lt;br&gt;
Decimal → American: if decimal ≥ 2, (decimal − 1) × 100; otherwise −100 / (decimal − 1)&lt;br&gt;
Decimal Fractional  American    Implied probability&lt;br&gt;
1.50    1/2 −200  66.67%&lt;br&gt;
1.91    10/11   −110  52.36%&lt;br&gt;
2.50    3/2 +150    40.00%&lt;br&gt;
3.40    12/5    +240    29.41%&lt;br&gt;
4.20    16/5    +320    23.81%&lt;/p&gt;

&lt;p&gt;If you just need a quick conversion while testing, the Orbistats odds converters and calculators and the glossary (implied probability and other terms) cover the basics.&lt;/p&gt;

&lt;p&gt;Implied Probability and the Bookmaker Margin&lt;/p&gt;

&lt;p&gt;Decimal odds are a price, but they are also a probability estimate. A price of 2.00 implies a 50% chance, because 1 / 2.00 = 0.50.&lt;/p&gt;

&lt;p&gt;Here is the catch. Add up the implied probabilities of every outcome in a market, and you will get more than 100%. The excess is the bookmaker’s margin (also called the overround or vig). It is how the bookmaker earns a living, and it is why you cannot treat raw implied probabilities as true probabilities.&lt;/p&gt;

&lt;p&gt;Worked example. The Odds API page shows a sample response for a Manchester City vs Arsenal 1X2 market. Using those sample prices:&lt;/p&gt;

&lt;p&gt;Outcome Decimal odds    Implied probability&lt;br&gt;
Home    1.91    52.36%&lt;br&gt;
Draw    3.40    29.41%&lt;br&gt;
Away    4.20    23.81%&lt;br&gt;
Total       105.58%&lt;/p&gt;

&lt;p&gt;The market adds up to 105.58%, so the overround is 5.58%. To estimate fair probabilities, divide each implied probability by the total. This is the simplest method, called proportional (or multiplicative) margin removal:&lt;/p&gt;

&lt;p&gt;Outcome Fair probability&lt;br&gt;
Home    49.59%&lt;br&gt;
Draw    27.86%&lt;br&gt;
Away    22.55%&lt;br&gt;
Total   100.00%&lt;/p&gt;

&lt;p&gt;More sophisticated methods exist, including the power method and Shin’s method, which treat favourites and longshots differently. For a comparison, see Erik Štrumbelj’s paper On determining probability forecasts from betting odds (International Journal of Forecasting, 2014). The proportional method is a sensible default for dashboards and quick comparisons.&lt;/p&gt;

&lt;p&gt;Code: Fetch Normalized Odds and Strip the Margin&lt;/p&gt;

&lt;p&gt;Node.js: fetch the current odds for a match and compute the margin. This uses the documented endpoint GET /v1/football/odds?match_id=... with a Bearer key.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const BASE = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;/p&gt;

&lt;p&gt;async function getOdds(matchId) {&lt;br&gt;
  const res = await fetch(&lt;code&gt;${BASE}/football/odds?match_id=${encodeURIComponent(matchId)}&lt;/code&gt;, {&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_API_KEY}&lt;/code&gt; },&lt;br&gt;
    signal: AbortSignal.timeout(10_000),&lt;br&gt;
  });&lt;br&gt;
  if (!res.ok) throw new Error(&lt;code&gt;Odds request failed: HTTP ${res.status}&lt;/code&gt;);&lt;br&gt;
  const body = await res.json();&lt;br&gt;
  const payload = body.data ?? body;                       // tolerate an envelope or a flat object&lt;br&gt;
  return Array.isArray(payload) ? payload[0] : payload;    // confirm the exact shape in the sandbox&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function analyse(o) {&lt;br&gt;
  if (o.format !== "decimal") throw new Error(&lt;code&gt;Expected decimal odds, got ${o.format}&lt;/code&gt;);&lt;br&gt;
  const implied = Object.entries(o.odds).map(([outcome, d]) =&amp;gt; [outcome, 1 / d]);&lt;br&gt;
  const total = implied.reduce((sum, [, p]) =&amp;gt; sum + p, 0);&lt;br&gt;
  return {&lt;br&gt;
    market: o.market,&lt;br&gt;
    status: o.status,                                      // e.g. pre_match&lt;br&gt;
    updatedAt: o.updated_at,&lt;br&gt;
    overround: total - 1,                                  // 0.0558 means a 5.58% margin&lt;br&gt;
    fair: Object.fromEntries(implied.map(([k, p]) =&amp;gt; [k, p / total])),&lt;br&gt;
  };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;getOdds(48213).then((o) =&amp;gt; console.log(analyse(o))).catch(console.error);&lt;/p&gt;

&lt;p&gt;How it works. The function reads the odds object (home, draw, away), converts each price to an implied probability, sums them to get the overround, then divides each probability by the total to get fair probabilities. It works for two-way markets too, because it iterates over whatever outcomes are present. It refuses non-decimal data instead of silently producing wrong numbers.&lt;/p&gt;

&lt;p&gt;Security note: keep the API key on your server and never call the API directly from browser code.&lt;/p&gt;

&lt;p&gt;Python: odds format conversions and margin removal. These are pure maths helpers you can use with any odds source.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from fractions import Fraction&lt;/p&gt;

&lt;p&gt;def decimal_to_american(d: float) -&amp;gt; int:&lt;br&gt;
    return round((d - 1) * 100) if d &amp;gt;= 2 else round(-100 / (d - 1))&lt;/p&gt;

&lt;p&gt;def american_to_decimal(a: int) -&amp;gt; float:&lt;br&gt;
    return 1 + (a / 100 if a &amp;gt; 0 else 100 / abs(a))&lt;/p&gt;

&lt;p&gt;def decimal_to_fraction(d: float, max_denominator: int = 100) -&amp;gt; Fraction:&lt;br&gt;
    return Fraction(d - 1).limit_denominator(max_denominator)&lt;/p&gt;

&lt;p&gt;def remove_margin(decimals: dict[str, float]) -&amp;gt; tuple[float, dict[str, float]]:&lt;br&gt;
    implied = {k: 1 / d for k, d in decimals.items()}&lt;br&gt;
    total = sum(implied.values())&lt;br&gt;
    return total - 1, {k: p / total for k, p in implied.items()}&lt;/p&gt;

&lt;p&gt;overround, fair = remove_margin({"home": 1.91, "draw": 3.40, "away": 4.20})&lt;br&gt;
print(f"overround {overround:.2%}")                       # overround 5.58%&lt;br&gt;
print({k: f"{v:.2%}" for k, v in fair.items()})           # home 49.59%, draw 27.86%, away 22.55%&lt;br&gt;
print(decimal_to_american(1.91), decimal_to_fraction(1.91))   # -110 10/11&lt;br&gt;
Markets You Can Expect&lt;/p&gt;

&lt;p&gt;The Odds API page lists five market families. Availability varies by sport and league, with major competitions carrying the full set.&lt;/p&gt;

&lt;p&gt;Market  Also known as   Typical use&lt;br&gt;
1X2 Moneyline (two-way in sports without draws) Outright result pricing&lt;br&gt;
Spreads Handicap    Point or goal handicaps&lt;br&gt;
Totals  Over/Under  Combined score above or below a line&lt;br&gt;
Player props    Player specials Individual player performance markets&lt;br&gt;
Futures Outrights   Season or tournament winners&lt;br&gt;
Line Movement and Closing Line Value&lt;/p&gt;

&lt;p&gt;A price is not a fixed fact. It moves from the opening line through pre-match drift and live in-play changes to the closing line. Tracking that movement is useful in three ways:&lt;/p&gt;

&lt;p&gt;Pricing teams see where the market is heading and how fast.&lt;br&gt;
Analysts judge whether a model’s prices beat the closing line, a measure often called closing line value (CLV).&lt;br&gt;
Product teams show users how an odd has changed, which builds trust in an odds comparison page.&lt;/p&gt;

&lt;p&gt;The Odds API page states that opening lines, closing lines and full movement history are tracked, and that multi-season history is available through the Historical Sports Data API using the same schema. That shared schema matters: you can build a model on history and run it on live data without rewriting your parsing.&lt;/p&gt;

&lt;p&gt;How to Get Odds: REST, WebSocket and History&lt;/p&gt;

&lt;p&gt;The Odds API page describes three delivery routes for the same schema:&lt;/p&gt;

&lt;p&gt;Method  Best for    Typical latency (per the page)&lt;br&gt;
REST query  Displaying current odds, scheduled jobs Seconds&lt;br&gt;
WebSocket   Trading desks, pricing engines, live UI Under 1 second&lt;br&gt;
Historical query    Backtesting pricing models  Archival&lt;/p&gt;

&lt;p&gt;REST is the right start for most products. Add the WebSocket API when users watch prices move and seconds matter, and use webhooks when your backend should react to an odds move without polling. For help choosing, read our guide to the sports data API and the developer documentation.&lt;/p&gt;

&lt;p&gt;Who Benefits Most From Normalized Odds&lt;br&gt;
Sportsbooks and trading teams use a consensus view of the market for pricing and risk instead of depending on one book. See Sportsbooks &amp;amp; Trading and Trading Desks.&lt;br&gt;
Media and publishers can power an odds comparison board without building the plumbing. The widgets offer a drop-in odds board.&lt;br&gt;
Analytics and data science teams backtest on closing lines and movement history. See Analytics &amp;amp; Data Science.&lt;br&gt;
Fantasy and betting-tool developers convert formats, show implied probabilities and flag margins for their users.&lt;br&gt;
Building an Odds Comparison Feature: A Practical Checklist&lt;br&gt;
Pick one internal format. Store decimal odds and convert only for display.&lt;br&gt;
Store the context with every price: market, status (pre-match or live), bookmaker field and updated_at.&lt;br&gt;
Compute margin per market, not per bookmaker, and show fair probabilities alongside prices if your audience values them.&lt;br&gt;
Never mix pre-match and live lines in the same comparison.&lt;br&gt;
Show freshness. Display when a price was last updated and hide stale prices.&lt;br&gt;
Cache sensibly. Live odds need short caching; closing lines and history can be cached much longer.&lt;br&gt;
Common Pitfalls and How to Fix Them&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
Implied probabilities add up to more than 100%  Bookmaker margin (overround)    Divide each probability by the total to get fair probabilities&lt;br&gt;
Prices look wrong next to another source    Different odds formats compared directly    Convert everything to decimal first&lt;br&gt;
A market is missing for a league    Market depth varies by sport and league Handle empty markets gracefully; check coverage before promising a market&lt;br&gt;
Odds on screen look stale   Cached or paused feed   Check updated_at and status; refresh over REST or move to streaming&lt;br&gt;
Pre-match and live prices get mixed up  status ignored  Filter and label by status&lt;br&gt;
Totals drift in tests   Floating-point rounding Round only for display, never in the calculation&lt;br&gt;
Odds Across 13 Sports&lt;/p&gt;

&lt;p&gt;Orbistats covers 13 sports: Football, Basketball, American Football, Cricket, Tennis, Baseball, Esports, Combat Sports, Volleyball, Handball, Ice Hockey, Golf and Horse Racing. The schema is the same for all of them, but market depth varies by sport and league. A two-way sport such as tennis has no draw outcome, and your margin code should simply work on whatever outcomes the market contains, as the examples above do. Check the API Reference for the sport you plan to launch with.&lt;/p&gt;

&lt;p&gt;Getting Started&lt;/p&gt;

&lt;p&gt;Orbistats offers a free self-serve API key with no card required, and a sandbox where you can test requests before choosing a plan. Compare plans on the pricing page, and confirm the markets and limits your plan includes before you design around them.&lt;/p&gt;

&lt;p&gt;Key Takeaways&lt;br&gt;
Normalization replaces a parser per bookmaker with one schema for markets, outcomes and odds format.&lt;br&gt;
Store decimal odds internally and convert to fractional or American only for display.&lt;br&gt;
Raw implied probabilities total more than 100%. The excess is the bookmaker margin.&lt;br&gt;
Dividing by the total gives simple fair probabilities, and more advanced methods exist for sharper work.&lt;br&gt;
Line movement from open to close is valuable for pricing, analytics and user-facing products.&lt;br&gt;
Use REST first, add WebSocket when seconds matter and historical queries for backtesting, all in the same schema.&lt;br&gt;
Market availability varies by sport and league, so check coverage before you promise a market.&lt;br&gt;
Frequently Asked Questions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;What is odds normalization?&lt;br&gt;
It is the process of mapping odds from different bookmakers into one consistent structure, with the same market names, outcome fields and odds format, so prices can be compared and combined without custom parsing per source.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What is the difference between decimal, fractional and American odds?&lt;br&gt;
They are three ways of writing the same price. Decimal (2.50) shows total return per unit staked, fractional (3/2) shows profit relative to stake, and American (+150) shows profit on a 100 stake for positive numbers or the stake needed to win 100 for negative numbers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do I convert odds to implied probability?&lt;br&gt;
For decimal odds, divide 1 by the odds. A price of 4.00 implies a 25% probability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What is the bookmaker margin or overround?&lt;br&gt;
It is the amount by which the implied probabilities of all outcomes in a market exceed 100%. A total of 105.58% means a 5.58% margin.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do I remove the margin from odds?&lt;br&gt;
The simplest method is proportional: divide each outcome’s implied probability by the sum of all of them. Power and Shin’s methods are more advanced alternatives.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Does the Orbistats Odds API provide live and historical odds?&lt;br&gt;
Per the Odds API page, it provides pre-match and live odds, line movement, and multi-season history through the Historical Sports Data API in the same schema.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Which odds formats does the API return?&lt;br&gt;
Decimal by default, with fractional and American formats available.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How fast are live odds?&lt;br&gt;
The Odds API page lists typical latency as seconds over REST and under one second over WebSocket.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Do all sports have the same markets?&lt;br&gt;
No. The schema is consistent, but market depth varies by sport and league, and major competitions carry the full set.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;Odds look simple until you have to combine them. Different names, formats and structures turn every new bookmaker into a new parser, and raw prices hide a margin that distorts any probability you derive from them. Normalization solves the first problem, and a few lines of maths solve the second.&lt;/p&gt;

&lt;p&gt;Start with one match, convert it to decimal, remove the margin, and compare. When that works, add line movement, streaming and history.&lt;/p&gt;

&lt;p&gt;Ready to build? Start free and get an API key, try requests in the sandbox, read the Odds API documentation or compare API plans.&lt;/p&gt;

&lt;p&gt;INTERNAL LINKS USED (all from the live site)&lt;br&gt;
URL Anchor in the article&lt;br&gt;
/api/odds-api.html  Orbistats Odds API&lt;br&gt;
/api/historical-sports-data-api.html    Historical Sports Data API&lt;br&gt;
/api/websocket-api.html WebSocket API&lt;br&gt;
/api/webhooks-api.html  webhooks&lt;br&gt;
/api/sports-data-api.html   guide to the sports data API&lt;br&gt;
/developers/documentation.html  developer documentation&lt;br&gt;
/developers/api-reference.html  API Reference&lt;br&gt;
/developers/sandbox.html    sandbox&lt;br&gt;
/resources/tools.html   odds converters and calculators&lt;br&gt;
/resources/glossary.html    glossary&lt;br&gt;
/solutions/sportsbooks.html, /solutions/trading.html, /solutions/analytics.html audience sections&lt;br&gt;
/widgets.html   widgets&lt;br&gt;
/pricing.html   pricing page&lt;br&gt;
BACKLINK AND PUBLISHING OPPORTUNITIES&lt;/p&gt;

&lt;p&gt;These are opportunities only. Approval is never guaranteed, and I have not verified dofollow/nofollow for any of them.&lt;/p&gt;

&lt;h1&gt;
  
  
  Platform and URL    Approach    Anchor  Destination Type
&lt;/h1&gt;

&lt;p&gt;1   dev.to · dev.to/new    Tutorial: “Convert odds and remove the bookmaker margin in Node.js and Python”  sports odds API /api/odds-api.html  Distribution (canonical to your blog)&lt;br&gt;
2   Hashnode · hashnode.com    Architecture angle: designing an odds normalization pipeline    odds normalization  /api/odds-api.html  Distribution&lt;br&gt;
3   Medium · medium.com/new-story (orbistats account)  Business angle: why normalized odds save engineering time   Orbistats Odds API  /api/odds-api.html  Distribution&lt;br&gt;
4   GitHub · github.com/new (under github.com/orbistats)   Small repo with the conversion and margin-removal helpers, README links to the post odds API documentation  /developers/documentation.html  Resource (a repo you control)&lt;br&gt;
5   Reddit r/algobetting · reddit.com/r/algobetting    Discussion post on margin removal methods; follow the self-promotion rules  full guide  Blog URL    Community&lt;br&gt;
6   LinkedIn Article · linkedin.com    Summary for sportsbook and trading engineers    odds normalization  Blog URL    Distribution&lt;br&gt;
7   HackerNoon · app.hackernoon.com/new    Submission on “one schema instead of a parser per bookmaker”    normalized odds /api/odds-api.html  Editorial submission&lt;br&gt;
8   DZone · dzone.com (contributor guidelines) Data-integration article    odds data integration   Blog URL    Editorial guest post&lt;br&gt;
9   Towards Data Science · towardsdatascience.com (contributor guidelines) Implied probability and margin removal for data scientists  implied probability /resources/glossary.html    Editorial submission&lt;br&gt;
10  Stack Overflow · stackoverflow.com/questions   Answer genuine questions on converting odds or removing vig, linking only where it helps and disclosing affiliation odds converter  /resources/tools.html   Community Q&amp;amp;A&lt;br&gt;
11  Quora · quora.com  Answer questions such as “How do I convert decimal odds to probability?”    odds converters /resources/tools.html   Community Q&amp;amp;A&lt;br&gt;
12  Indie Hackers · indiehackers.com/post  Founder story on building a multi-sport odds feed   Orbistats   /pricing.html   Community&lt;/p&gt;

&lt;p&gt;Top 5 first: dev.to, Hashnode, Medium, the GitHub repo, r/algobetting. Publish on orbistats.com first and set the canonical URL on every cross-post.&lt;/p&gt;

&lt;p&gt;EXTERNAL REFERENCES&lt;br&gt;
Erik Štrumbelj, On determining probability forecasts from betting odds, International Journal of Forecasting (2014). Search the title to find the paper.&lt;br&gt;
Orbistats Odds API, API Reference and Pricing&lt;/p&gt;

</description>
      <category>api</category>
      <category>tutorial</category>
      <category>odds</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>REST vs WebSocket vs Webhooks for Live Sports Data: Which Should You Use?</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Wed, 18 Nov 2026 18:19:01 +0000</pubDate>
      <link>https://dev.to/orbistats/rest-vs-websocket-vs-webhooks-for-live-sports-data-which-should-you-use-j4a</link>
      <guid>https://dev.to/orbistats/rest-vs-websocket-vs-webhooks-for-live-sports-data-which-should-you-use-j4a</guid>
      <description>&lt;p&gt;Every live sports product eventually hits the same wall. The first version polls an endpoint every few seconds and works fine for one match. Then match day arrives, ten leagues kick off at once, and the app is either hammering the API, showing stale scores, or both.&lt;/p&gt;

&lt;p&gt;The cause is usually not the data provider. It is the delivery method. A live sports data API can hand you the same score three ways: you can ask for it (REST), listen for it on an open connection (WebSocket), or be told about it (webhooks). Each suits a different job, so the WebSocket vs REST API for live sports data question has no universal winner.&lt;/p&gt;

&lt;p&gt;This guide explains how each method works, what it costs in code and infrastructure, and how to combine them. The examples use the Orbistats sports data API, which offers all three methods across 13 sports. The principles apply to any provider.&lt;/p&gt;

&lt;p&gt;The Short Answer&lt;br&gt;
Use REST for schedules, standings, statistics, history and snapshots.&lt;br&gt;
Use WebSocket when a user is watching a screen that must update in seconds: scoreboards, in-play odds boards, trading dashboards.&lt;br&gt;
Use webhooks when your backend must react to an event (a goal, a final result, an odds move) without holding a connection open or running a polling loop.&lt;br&gt;
Use a hybrid for anything serious: REST as the source of truth, WebSocket for the live screen, webhooks for backend workflows.&lt;br&gt;
How Live Sports Data Moves&lt;/p&gt;

&lt;p&gt;A live match produces a stream of small changes: a goal, a card, a clock tick, a price move. Whatever the transport, your application needs three things:&lt;/p&gt;

&lt;p&gt;Identity: which match is this?&lt;br&gt;
State: what is the score, period and status right now?&lt;br&gt;
Change: what just happened?&lt;/p&gt;

&lt;p&gt;The delivery method decides who starts the transfer and how long you wait to learn about a change. REST makes you ask. WebSocket and webhooks make the provider tell you.&lt;/p&gt;

&lt;p&gt;One practical note before the code: each interface identifies matches with its own payload fields. Store a mapping between them, and check the ID formats in the sandbox before you wire the three together.&lt;/p&gt;

&lt;p&gt;Method 1: REST Polling&lt;/p&gt;

&lt;p&gt;How it works. Your client sends an HTTPS request on a timer and receives the current state. For live data the relevant endpoint is GET /v1/{sport}/matches/live. It returns every match in play with the score, clock, period and the most recent event. The API Reference suggests polling it every 5-10 seconds if you are not using a stream.&lt;/p&gt;

&lt;p&gt;Where it shines:&lt;/p&gt;

&lt;p&gt;Simplicity. Any language, any framework, no persistent connection. A cron job or serverless function is enough.&lt;br&gt;
Cacheability. Fixtures, results, standings and statistics can be cached. The live endpoint is marked as not cached.&lt;br&gt;
Completeness. REST is the only method that gives you a full snapshot on demand, which is what you need after an outage.&lt;/p&gt;

&lt;p&gt;Where it hurts:&lt;/p&gt;

&lt;p&gt;Latency equals your poll interval. With a 7-second interval, a goal can be up to 7 seconds old before you see it.&lt;br&gt;
Cost grows with matches × viewers × frequency. One endpoint polled every 5 seconds is 17,280 requests a day, before you add a second sport.&lt;br&gt;
Wasted calls. Most polls return nothing new.&lt;/p&gt;

&lt;p&gt;A safe polling loop (Node.js):&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const BASE = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;/p&gt;

&lt;p&gt;async function getLive(sport, league) {&lt;br&gt;
  const qs = league ? &lt;code&gt;?league=${encodeURIComponent(league)}&lt;/code&gt; : "";&lt;br&gt;
  const res = await fetch(&lt;code&gt;${BASE}/${sport}/matches/live${qs}&lt;/code&gt;, {&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_API_KEY}&lt;/code&gt; },&lt;br&gt;
    signal: AbortSignal.timeout(10_000),&lt;br&gt;
  });&lt;br&gt;
  const body = await res.json();&lt;br&gt;
  if (!res.ok) {&lt;br&gt;
    const e = body.errors?.[0] ?? {};&lt;br&gt;
    throw Object.assign(new Error(e.message ?? res.statusText), {&lt;br&gt;
      status: res.status, code: e.code, requestId: body.meta?.request_id,&lt;br&gt;
    });&lt;br&gt;
  }&lt;br&gt;
  return body.data; // array of live matches&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;async function poll(sport, onData, intervalMs = 7000) {&lt;br&gt;
  try {&lt;br&gt;
    onData(await getLive(sport));&lt;br&gt;
  } catch (err) {&lt;br&gt;
    if (err.status &amp;amp;&amp;amp; err.status &amp;lt; 500) throw err; // 4xx: fix the request, don't retry unchanged&lt;br&gt;
    console.error("transient error, will retry:", err.message, err.requestId);&lt;br&gt;
  }&lt;br&gt;
  setTimeout(() =&amp;gt; poll(sport, onData, intervalMs), intervalMs); // schedule after completion: no overlapping calls&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;poll("football", (matches) =&amp;gt; console.log(&lt;code&gt;${matches.length} live matches&lt;/code&gt;));&lt;/p&gt;

&lt;p&gt;How it works. Scheduling the next call with setTimeout after the previous one finishes (instead of setInterval) means a slow response never causes overlapping requests. Authentication is a Bearer key read from an environment variable. Every response uses the same envelope (data, meta, errors), and meta.request_id is what you quote to support. Retry only 500, 502, 503 and 504, and never retry a 4xx unchanged.&lt;/p&gt;

&lt;p&gt;Security note: keep the API key on your server. Browsers should call your backend, not the provider directly.&lt;/p&gt;

&lt;p&gt;Method 2: WebSocket Streaming&lt;/p&gt;

&lt;p&gt;How it works. The client opens one long-lived connection to wss://stream.orbistats.com/v1, subscribes to channels, and the server pushes messages as things change. The protocol is standardised in RFC 6455, and the browser API is documented on MDN.&lt;/p&gt;

&lt;p&gt;According to the WebSocket API page:&lt;/p&gt;

&lt;p&gt;Authentication: you pass your API key as the api_key query parameter when opening the socket. A missing or invalid key rejects the connection.&lt;br&gt;
Subscriptions: after connecting, you send { "action": "subscribe", "channel": "football.live" }. You can optionally add league or match_id, and send unsubscribe to stop a channel. One socket can carry unlimited channels.&lt;br&gt;
Messages: events arrive as JSON with a channel, an event such as match.goal, a match_id and a timestamp.&lt;br&gt;
Heartbeats: ping/pong frames keep the connection alive and make a dead one detectable.&lt;br&gt;
Close codes: 1000 normal closure, 4001 invalid or missing key, 4008 rate limit exceeded for your plan, 1006 abnormal closure (reconnect with exponential backoff).&lt;br&gt;
Connection limits: Free allows 2 concurrent connections and Starter allows 10. Growth and Enterprise limits are custom.&lt;/p&gt;

&lt;p&gt;Where it shines:&lt;/p&gt;

&lt;p&gt;Lowest delay. There is no poll interval, so changes arrive as they happen.&lt;br&gt;
Efficient at scale. One connection replaces thousands of repeated requests.&lt;br&gt;
Natural fit for live UIs. Scoreboards, odds boards and trading screens.&lt;/p&gt;

&lt;p&gt;Where it hurts:&lt;/p&gt;

&lt;p&gt;You own connection health. Connections drop silently, so you need a watchdog, reconnection and re-subscription.&lt;br&gt;
You can miss messages. Anything sent while you were offline is gone, so refresh state over REST after every reconnect.&lt;br&gt;
Stateful infrastructure. Load balancers, deploys and scaling all have to cope with long-lived connections.&lt;/p&gt;

&lt;p&gt;A reconnecting client (Node.js):&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const WebSocket = require("ws");&lt;br&gt;
const URL = &lt;code&gt;wss://stream.orbistats.com/v1?api_key=${process.env.ORBISTATS_API_KEY}&lt;/code&gt;;&lt;br&gt;
const STALE_MS = 60_000; // no message or ping for this long = treat as dead (tune to your needs)&lt;/p&gt;

&lt;p&gt;let attempt = 0, watchdog, hadConnection = false;&lt;/p&gt;

&lt;p&gt;function connect() {&lt;br&gt;
  const ws = new WebSocket(URL);&lt;br&gt;
  const arm = () =&amp;gt; {&lt;br&gt;
    clearTimeout(watchdog);&lt;br&gt;
    watchdog = setTimeout(() =&amp;gt; ws.terminate(), STALE_MS); // triggers 'close' -&amp;gt; reconnect&lt;br&gt;
  };&lt;/p&gt;

&lt;p&gt;ws.on("open", () =&amp;gt; {&lt;br&gt;
    attempt = 0;&lt;br&gt;
    ws.send(JSON.stringify({ action: "subscribe", channel: "football.live", league: "premier-league" }));&lt;br&gt;
    if (hadConnection) resyncFromRest().catch(console.error); // repair anything missed while offline&lt;br&gt;
    hadConnection = true;&lt;br&gt;
    arm();&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;ws.on("ping", arm); // the ws library answers pings automatically&lt;br&gt;
  ws.on("message", (raw) =&amp;gt; {&lt;br&gt;
    arm();&lt;br&gt;
    let msg;&lt;br&gt;
    try { msg = JSON.parse(raw); } catch { return; } // ignore malformed frames&lt;br&gt;
    switch (msg.event) {&lt;br&gt;
      case "match.goal":&lt;br&gt;
        applyGoal(msg.match_id, msg.team, msg.minute);&lt;br&gt;
        break;&lt;br&gt;
      default:&lt;br&gt;
        break; // ignore unknown events so new ones never break you&lt;br&gt;
    }&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;ws.on("error", (e) =&amp;gt; console.error("socket error:", e.message)); // 'close' always follows&lt;/p&gt;

&lt;p&gt;ws.on("close", (code) =&amp;gt; {&lt;br&gt;
    clearTimeout(watchdog);&lt;br&gt;
    if (code === 4001) return console.error("Invalid or missing API key: fix it, do not retry.");&lt;br&gt;
    const base = code === 4008 ? 15_000 : 1_000; // rate limited: back off harder&lt;br&gt;
    const delay = Math.min(60_000, base * 2 ** attempt++) + Math.random() * 1000; // backoff + jitter&lt;br&gt;
    setTimeout(connect, delay);&lt;br&gt;
  });&lt;br&gt;
}&lt;br&gt;
connect();&lt;/p&gt;

&lt;p&gt;How it works. The watchdog treats silence as a dead connection. Exponential backoff with jitter stops thousands of clients reconnecting at the same instant. A 4001 is a configuration error, so retrying in a loop only wastes time. A 4008 backs off longer. Every reconnect re-subscribes and repairs state from REST. Unknown event types are ignored on purpose, so the provider can add new ones without breaking your client.&lt;/p&gt;

&lt;p&gt;Security note: the key travels in the connection URL, so run this client on your server (or behind your own proxy) and never ship a production key in browser JavaScript.&lt;/p&gt;

&lt;p&gt;Method 3: Webhooks&lt;/p&gt;

&lt;p&gt;How it works. You register an HTTPS endpoint and the provider sends a signed POST whenever a subscribed event occurs. The Webhooks API page documents these event types: match.started, match.goal, match.finished and odds.moved.&lt;/p&gt;

&lt;p&gt;Register an endpoint:&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const res = await fetch("&lt;a href="https://api.orbistats.com/v1/webhooks" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/webhooks&lt;/a&gt;", {&lt;br&gt;
  method: "POST",&lt;br&gt;
  headers: {&lt;br&gt;
    Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_API_KEY}&lt;/code&gt;,&lt;br&gt;
    "Content-Type": "application/json",&lt;br&gt;
  },&lt;br&gt;
  body: JSON.stringify({&lt;br&gt;
    url: "&lt;a href="https://yourapp.com/webhook" rel="noopener noreferrer"&gt;https://yourapp.com/webhook&lt;/a&gt;",       // must be HTTPS&lt;br&gt;
    events: ["match.goal", "match.finished"],&lt;br&gt;
    sport: "football",                        // optional: limit to one sport&lt;br&gt;
  }),&lt;br&gt;
});&lt;br&gt;
console.log(await res.json());&lt;/p&gt;

&lt;p&gt;Where it shines:&lt;/p&gt;

&lt;p&gt;Backend automation. Settle bets, update a database, send a push notification or invalidate a cache the moment a match finishes.&lt;br&gt;
Zero idle cost. Nothing runs between events.&lt;br&gt;
Fits serverless. A function that wakes on POST is a natural receiver.&lt;/p&gt;

&lt;p&gt;Where it hurts:&lt;/p&gt;

&lt;p&gt;Public endpoint required. You must expose and secure a URL.&lt;br&gt;
At-least-once delivery. A retried delivery can arrive after the original already succeeded, so your handler must be idempotent.&lt;br&gt;
Not a UI transport. Webhooks reach servers, not browsers.&lt;/p&gt;

&lt;p&gt;What the delivery guarantees mean for your code:&lt;/p&gt;

&lt;p&gt;Respond fast. Return 200 within 5 seconds. A timeout counts as a failure and queues a retry.&lt;br&gt;
Retries. Failed deliveries retry with exponential backoff, up to 5 attempts (roughly immediate, 30 seconds, 2 minutes, 10 minutes, 1 hour).&lt;br&gt;
De-duplicate on event_id. It is stable across retries, while delivery_id changes per attempt.&lt;br&gt;
Order by sequence. It is monotonic per match_id. A retry can land after a newer event, so gate on sequence, not arrival order.&lt;br&gt;
Replay. If your endpoint was down longer than the retry window, list missed deliveries with GET /v1/webhooks/{id}/deliveries and replay them with POST /v1/webhooks/{id}/replay.&lt;/p&gt;

&lt;p&gt;A verified, idempotent receiver (Node.js + Express):&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const crypto = require("crypto");&lt;br&gt;
const express = require("express");&lt;br&gt;
const app = express();&lt;/p&gt;

&lt;p&gt;const SECRET = process.env.ORBISTATS_WEBHOOK_SECRET;&lt;br&gt;
const seenEvents = new Set();    // production: Redis or a DB unique index on event_id&lt;br&gt;
const lastSequence = new Map();  // match_id -&amp;gt; highest sequence applied&lt;/p&gt;

&lt;p&gt;function isValid(rawBody, header = "") {&lt;br&gt;
  const received = header.replace(/^sha256=/, "");&lt;br&gt;
  const expected = crypto.createHmac("sha256", SECRET).update(rawBody).digest("hex");&lt;br&gt;
  const a = Buffer.from(received, "hex");&lt;br&gt;
  const b = Buffer.from(expected, "hex");&lt;br&gt;
  return a.length &amp;gt; 0 &amp;amp;&amp;amp; a.length === b.length &amp;amp;&amp;amp; crypto.timingSafeEqual(a, b); // constant-time compare&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// The RAW body is required: re-serialised JSON will not match the signature&lt;br&gt;
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) =&amp;gt; {&lt;br&gt;
  if (!isValid(req.body, req.get("X-Orbistats-Signature"))) return res.sendStatus(401);&lt;/p&gt;

&lt;p&gt;const evt = JSON.parse(req.body.toString("utf8"));&lt;br&gt;
  res.sendStatus(200); // acknowledge within 5 seconds, process afterwards&lt;/p&gt;

&lt;p&gt;if (seenEvents.has(evt.event_id)) return;                      // duplicate delivery&lt;br&gt;
  seenEvents.add(evt.event_id);&lt;/p&gt;

&lt;p&gt;if (evt.sequence &amp;lt;= (lastSequence.get(evt.match_id) ?? -1)) return; // stale: a newer event was already applied&lt;br&gt;
  lastSequence.set(evt.match_id, evt.sequence);&lt;/p&gt;

&lt;p&gt;setImmediate(() =&amp;gt; handle(evt).catch((e) =&amp;gt; console.error("handler failed", evt.event_id, e)));&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;async function handle(evt) {&lt;br&gt;
  if (evt.event === "match.finished") {&lt;br&gt;
    console.log(&lt;code&gt;match ${evt.match_id} finished ${evt.final_score}&lt;/code&gt;);&lt;br&gt;
    // settle bets, update the DB, notify users...&lt;br&gt;
  }&lt;br&gt;
  // match.goal, match.started, odds.moved: enqueue to your job queue&lt;br&gt;
}&lt;br&gt;
app.listen(3000);&lt;/p&gt;

&lt;p&gt;How it works. The handler computes an HMAC-SHA256 of the raw body with your webhook secret and compares it with the X-Orbistats-Signature header in constant time. It acknowledges immediately, then de-duplicates on event_id and drops events whose sequence is older than what it has already applied. The signature covers the body only, so de-duplication matters even more. Stripe’s webhook guide describes the same signature-and-retry pattern.&lt;/p&gt;

&lt;p&gt;Side-by-Side Comparison&lt;br&gt;
    REST polling    WebSocket   Webhooks&lt;br&gt;
Direction   You pull    Server pushes over an open connection   Server pushes to your URL&lt;br&gt;
Delay   Up to your poll interval    Pushed as events occur  Pushed as events occur&lt;br&gt;
Best for    Fixtures, standings, stats, history, snapshots  Live scoreboards, in-play odds, trading screens Settlement, notifications, cache invalidation&lt;br&gt;
Request volume  High (scales with polling)  One connection  Only when something changes&lt;br&gt;
Missed-data risk    Low (you ask again) Medium (resync after reconnect) Medium (retries, so dedupe; replay available)&lt;br&gt;
Infrastructure  Minimal Long-lived connections  Public HTTPS endpoint&lt;br&gt;
Reaches a browser directly? Via your backend    Via your backend    No&lt;br&gt;
Complexity  Low Medium to high  Medium&lt;br&gt;
Which Method for Which Product?&lt;br&gt;
Sportsbooks and trading desks: WebSocket for odds and live prices on the pricing screen, webhooks for settlement and risk workflows, REST for market snapshots. See the Orbistats Sportsbooks and Trading Desks pages.&lt;br&gt;
Media and publishers: REST with short caching, or the drop-in widgets, is often enough. Add WebSocket only for a true live match centre.&lt;br&gt;
Fantasy platforms: webhooks for scoring updates and match completion, REST for rosters, statistics and fixtures.&lt;br&gt;
Analytics and data science: REST with cursor pagination for bulk pulls from the Historical Data API. Streaming is rarely needed.&lt;br&gt;
Mobile apps: your backend subscribes once (WebSocket or webhooks), then fans out to devices via push notifications or its own socket. One upstream connection serves all your users, which also keeps you inside the plan’s connection limit.&lt;br&gt;
The Hybrid Architecture Most Teams End Up With&lt;br&gt;
REST is the source of truth. Load fixtures, standings and the initial live snapshot at startup and after every reconnect.&lt;br&gt;
WebSocket feeds the live layer. Apply stream events to in-memory state and fan them out to connected users.&lt;br&gt;
Webhooks drive backend actions. On match.finished, write the final result and trigger settlement or notifications.&lt;br&gt;
Reconcile. Any reconnect, replay or suspicious gap triggers a REST refresh, so a dropped message never becomes a permanent error.&lt;br&gt;
Working Across 13 Sports&lt;/p&gt;

&lt;p&gt;Orbistats covers 13 sports: Football, Basketball, American Football, Cricket, Tennis, Baseball, Esports, Combat Sports, Volleyball, Handball, Ice Hockey, Golf and Horse Racing. REST URLs follow /v1/{sport}/{resource}, so adding a sport mostly means changing the path segment, and the stream and webhook pages describe one message format across sports.&lt;/p&gt;

&lt;p&gt;Sport differences still matter. Sports without a running clock return minute: null, scoring can be sets, innings or rounds (exposed in score.detail), and period values vary (2nd_half, set_2, q3). Resource availability, such as odds, lineups and historical depth, also varies by sport, so check the coverage matrix in the API Reference before designing around a resource.&lt;/p&gt;

&lt;p&gt;Common Pitfalls and How to Fix Them&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
Scoreboard freezes but the socket looks connected   Silent connection drop  Add a watchdog; terminate after a quiet period and reconnect with backoff and jitter&lt;br&gt;
Scores briefly wrong after a reconnect  Events missed while offline Re-subscribe, then refresh state from /matches/live&lt;br&gt;
Connection closes with 4001 Missing or invalid API key  Fix the key; do not retry in a loop&lt;br&gt;
Connection closes with 4008 Plan rate limit exceeded    Back off longer, reduce connections, or move to a higher plan&lt;br&gt;
Webhook signature always fails  Verifying re-serialised JSON    Verify against the raw request body&lt;br&gt;
Same event processed twice  Retry after a slow response Return 200 within 5 seconds; dedupe on event_id&lt;br&gt;
Scores jump backwards   Retried delivery arrived after a newer event    Gate on sequence per match_id, not on arrival order&lt;br&gt;
Webhooks missing after downtime Endpoint down past the retry window List and replay missed deliveries via the deliveries and replay endpoints&lt;br&gt;
Reconnect storm after a deploy  All clients retry at once   Backoff with jitter on every client&lt;br&gt;
Testing Before You Commit&lt;/p&gt;

&lt;p&gt;Orbistats publishes its pricing openly: a Free plan (€0, 1 hour of access, no card), Starter (€19, 24 hours), Growth (€79, 5 days) and Unlimited (€1,999/month, 30 days). Your access timer starts only when you open your activation link, so you choose when to begin. That makes the Free plan a good way to prototype all three delivery methods in one sitting, and the sandbox lets you try requests first. Confirm which resources and connection limits your plan includes on the pricing page and in the developer documentation.&lt;/p&gt;

&lt;p&gt;Key Takeaways&lt;br&gt;
No single method wins. REST, WebSocket and webhooks solve different problems: pull, stream and push.&lt;br&gt;
REST latency equals your poll interval, and request volume grows with matches × frequency.&lt;br&gt;
WebSocket gives the fastest screen updates, but you own reconnects, close-code handling and state repair.&lt;br&gt;
Webhooks suit backend reactions. Verify the signature on the raw body, de-duplicate on event_id and order by sequence.&lt;br&gt;
Respond to webhooks within 5 seconds and use the replay endpoints after downtime instead of building your own recovery.&lt;br&gt;
Hybrid is the production pattern: REST as truth, WebSocket for live UI, webhooks for workflows.&lt;br&gt;
Check per-sport coverage and plan limits before assuming every resource exists everywhere.&lt;br&gt;
Frequently Asked Questions&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Is WebSocket better than REST for live sports data?&lt;br&gt;
For screens that must update within seconds, yes. A WebSocket pushes changes as they happen, while REST only shows the state at your last request. REST remains better for schedules, standings, statistics, history and full snapshots.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How often should I poll a live scores API?&lt;br&gt;
The Orbistats API Reference suggests every 5-10 seconds for the live endpoint. Polling faster raises request volume without guaranteeing fresher data, so if you need faster updates, switch to WebSocket.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What is a sports data webhook?&lt;br&gt;
It is an HTTPS POST that the provider sends to your server when something changes, such as a goal or a final result. You do not poll for it. You verify the signature and process the event.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do I verify a sports API webhook signature?&lt;br&gt;
Compute an HMAC-SHA256 of the raw request body using your webhook secret and compare it to the X-Orbistats-Signature header in constant time. Never verify against re-serialised JSON.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do I handle duplicate or out-of-order webhooks?&lt;br&gt;
Delivery is at-least-once. Dedupe on event_id, which stays the same across retries, and gate on sequence, which is monotonic per match, rather than trusting arrival order.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do I handle WebSocket disconnections?&lt;br&gt;
Detect silence with a watchdog, reconnect with exponential backoff plus jitter, re-subscribe after each reconnect, and refresh state from a REST endpoint to cover missed messages. Do not retry on close code 4001, which means the key is invalid.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Can I use REST, WebSocket and webhooks together?&lt;br&gt;
Yes, and most production systems do: REST for snapshots and reference data, WebSocket for live screens, webhooks for backend workflows.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Does the same approach work for every sport?&lt;br&gt;
The delivery methods work across Orbistats’ 13 sports, but scoring structure, clocks and resource availability differ by sport, so check the coverage matrix first.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Is there a free way to test these delivery methods?&lt;br&gt;
Orbistats offers a free plan (€0, 1 hour of access, no card) and a sandbox. Check the pricing page for which resources and connection limits each plan includes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;Choosing a delivery method is really choosing who does the waiting. REST makes your app wait and ask. WebSockets keep a line open so updates arrive as they happen. Webhooks let your backend sleep until it is needed. Start with the simplest method that meets your latency requirement, add streaming where users actually watch the screen, and use webhooks for the work behind it.&lt;/p&gt;

&lt;p&gt;Ready to build it? Read the Orbistats developer documentation, try requests in the sandbox, compare API plans, or request access and start on the free plan.&lt;/p&gt;

</description>
      <category>livescores</category>
      <category>restapi</category>
      <category>webhooks</category>
      <category>websocket</category>
    </item>
    <item>
      <title>Build a Sports Data Sync Service with FastAPI &amp; SQLite</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Wed, 18 Nov 2026 13:23:29 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-sports-data-sync-service-with-fastapi-sqlite-129b</link>
      <guid>https://dev.to/orbistats/build-a-sports-data-sync-service-with-fastapi-sqlite-129b</guid>
      <description>&lt;p&gt;Calling a third-party API on every user request works in a demo. In production it causes three problems:&lt;/p&gt;

&lt;p&gt;Latency: your response time is now your provider’s response time.&lt;br&gt;
Cost and limits: traffic spikes become quota spikes (and 429 errors).&lt;br&gt;
Fragility: if the upstream hiccups, your whole product hiccups.&lt;/p&gt;

&lt;p&gt;The standard fix is a sync service: fetch data on a schedule, store it locally, and serve your users from your own database.&lt;/p&gt;

&lt;p&gt;In this tutorial we’ll build exactly that with FastAPI, httpx (async) and SQLite:&lt;/p&gt;

&lt;p&gt;An async API client with pagination, retry with exponential backoff, and Retry-After support&lt;br&gt;
Idempotent upserts so re-running a sync never duplicates data&lt;br&gt;
A background scheduler inside FastAPI’s lifespan&lt;br&gt;
Fast local query endpoints&lt;br&gt;
Docker packaging and a pytest test with a mocked API&lt;/p&gt;

&lt;p&gt;The upstream data comes from the Orbistats Sports Data API, which exposes fixtures across 13 sports with data, meta and pagination in every list response.&lt;/p&gt;

&lt;p&gt;Architecture&lt;br&gt;
            every N minutes&lt;br&gt;
 ┌────────────────────────────────┐&lt;br&gt;
 │  Background sync loop          │&lt;br&gt;
 │  for sport in SPORTS:          │&lt;br&gt;
 │    for day in next 7 days:     │&lt;br&gt;
 │      paginate → upsert         │&lt;br&gt;
 └──────────────┬─────────────────┘&lt;br&gt;
                │ httpx (Bearer auth, retries)&lt;br&gt;
                ▼&lt;br&gt;
        api.orbistats.com/v1&lt;br&gt;
                │&lt;br&gt;
                ▼&lt;br&gt;
        SQLite (fixtures.db)  ◄──── GET /fixtures  (FastAPI, instant)&lt;br&gt;
Prerequisites&lt;br&gt;
Python 3.11+&lt;br&gt;
An Orbistats API key: request access or try the sandbox&lt;br&gt;
Step 1: Project Setup&lt;br&gt;
bash&lt;br&gt;
mkdir fixtures-sync &amp;amp;&amp;amp; cd fixtures-sync&lt;br&gt;
python -m venv .venv &amp;amp;&amp;amp; source .venv/bin/activate&lt;br&gt;
pip install fastapi "uvicorn[standard]" httpx pytest pytest-asyncio&lt;br&gt;
pip freeze &amp;gt; requirements.txt&lt;br&gt;
mkdir app &amp;amp;&amp;amp; touch app/&lt;strong&gt;init&lt;/strong&gt;.py&lt;/p&gt;

&lt;p&gt;Create .env.example (and copy it to .env):&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
ORBISTATS_API_KEY=your_api_key_here&lt;br&gt;
SPORTS=football,cricket&lt;br&gt;
SYNC_DAYS=7&lt;br&gt;
SYNC_INTERVAL_SECONDS=900&lt;br&gt;
DB_PATH=fixtures.db&lt;/p&gt;

&lt;p&gt;SPORTS is configurable so you can add more later. Football and cricket are used in Orbistats’ public examples. Confirm other sport slugs in the API reference.&lt;/p&gt;

&lt;p&gt;Step 2: A Resilient Async Client&lt;/p&gt;

&lt;p&gt;Create app/client.py. This is the heart of the integration.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import asyncio&lt;br&gt;
import random&lt;br&gt;
from typing import Any, AsyncIterator&lt;/p&gt;

&lt;p&gt;import httpx&lt;/p&gt;

&lt;p&gt;BASE_URL = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;"&lt;/p&gt;

&lt;p&gt;class OrbistatsClient:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(&lt;br&gt;
        self,&lt;br&gt;
        api_key: str,&lt;br&gt;
        client: httpx.AsyncClient | None = None,&lt;br&gt;
        max_retries: int = 5,&lt;br&gt;
    ) -&amp;gt; None:&lt;br&gt;
        self._client = client or httpx.AsyncClient(&lt;br&gt;
            base_url=BASE_URL,&lt;br&gt;
            timeout=httpx.Timeout(10.0),&lt;br&gt;
            headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},&lt;br&gt;
        )&lt;br&gt;
        self._max_retries = max_retries&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@staticmethod
def _backoff(attempt: int) -&amp;gt; float:
    # 1s, 2s, 4s, 8s... capped at 30s, plus jitter to avoid thundering herds
    return min(30.0, 2.0**attempt) + random.random()

@staticmethod
def _retry_after(resp: httpx.Response) -&amp;gt; float | None:
    value = resp.headers.get("Retry-After")
    try:
        return float(value) if value is not None else None
    except ValueError:
        return None

async def get(self, path: str, **params: Any) -&amp;gt; dict:
    params = {k: v for k, v in params.items() if v is not None}

    for attempt in range(self._max_retries + 1):
        last = attempt == self._max_retries
        try:
            resp = await self._client.get(path, params=params)
        except (httpx.TimeoutException, httpx.TransportError):
            if last:
                raise
            await asyncio.sleep(self._backoff(attempt))
            continue

        if resp.status_code == 429 or resp.status_code &amp;gt;= 500:
            if last:
                resp.raise_for_status()
            delay = self._retry_after(resp) or self._backoff(attempt)
            await asyncio.sleep(delay)
            continue

        resp.raise_for_status()  # 4xx (401, 403, 404...) fail fast, no retry
        return resp.json()

    raise RuntimeError("unreachable")

async def paginate(
    self, path: str, per_page: int = 50, **params: Any
) -&amp;gt; AsyncIterator[dict]:
    """Yield every item across all pages."""
    page = 1
    while True:
        body = await self.get(path, page=page, per_page=per_page, **params)
        for item in body.get("data", []):
            yield item
        total_pages = body.get("pagination", {}).get("total_pages", page)
        if page &amp;gt;= total_pages:
            break
        page += 1

async def aclose(self) -&amp;gt; None:
    await self._client.aclose()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Three rules this code follows, worth stealing for any API integration:&lt;/p&gt;

&lt;p&gt;Retry only what is retryable. 429, 5xx and network errors are transient. 401 and 404 are not, so fail fast.&lt;br&gt;
Respect Retry-After when the server provides it, otherwise use exponential backoff with jitter.&lt;br&gt;
Hide pagination inside the client so the rest of your app just iterates.&lt;br&gt;
Step 3: The Database Layer&lt;/p&gt;

&lt;p&gt;Create app/db.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import os&lt;br&gt;
import sqlite3&lt;br&gt;
from contextlib import closing&lt;br&gt;
from datetime import datetime, timezone&lt;/p&gt;

&lt;p&gt;DB_PATH = os.getenv("DB_PATH", "fixtures.db")&lt;/p&gt;

&lt;p&gt;SCHEMA = """&lt;br&gt;
CREATE TABLE IF NOT EXISTS fixtures (&lt;br&gt;
    sport       TEXT NOT NULL,&lt;br&gt;
    fixture_id  TEXT NOT NULL,&lt;br&gt;
    home_team   TEXT,&lt;br&gt;
    away_team   TEXT,&lt;br&gt;
    kickoff     TEXT,&lt;br&gt;
    competition TEXT,&lt;br&gt;
    updated_at  TEXT NOT NULL,&lt;br&gt;
    PRIMARY KEY (sport, fixture_id)&lt;br&gt;
);&lt;br&gt;
CREATE INDEX IF NOT EXISTS idx_fixtures_sport_kickoff ON fixtures (sport, kickoff);&lt;br&gt;
"""&lt;/p&gt;

&lt;p&gt;def connect() -&amp;gt; sqlite3.Connection:&lt;br&gt;
    conn = sqlite3.connect(DB_PATH)&lt;br&gt;
    conn.row_factory = sqlite3.Row&lt;br&gt;
    return conn&lt;/p&gt;

&lt;p&gt;def init_db() -&amp;gt; None:&lt;br&gt;
    with closing(connect()) as conn:&lt;br&gt;
        conn.execute("PRAGMA journal_mode=WAL")  # readers don't block the writer&lt;br&gt;
        conn.executescript(SCHEMA)&lt;br&gt;
        conn.commit()&lt;/p&gt;

&lt;p&gt;def upsert_fixtures(sport: str, items: list[dict]) -&amp;gt; int:&lt;br&gt;
    now = datetime.now(timezone.utc).isoformat()&lt;br&gt;
    rows = [&lt;br&gt;
        (&lt;br&gt;
            sport,&lt;br&gt;
            str(i["fixture_id"]),&lt;br&gt;
            i.get("home_team"),&lt;br&gt;
            i.get("away_team"),&lt;br&gt;
            i.get("kickoff"),&lt;br&gt;
            i.get("competition"),&lt;br&gt;
            now,&lt;br&gt;
        )&lt;br&gt;
        for i in items&lt;br&gt;
        if i.get("fixture_id") is not None&lt;br&gt;
    ]&lt;br&gt;
    with closing(connect()) as conn:&lt;br&gt;
        conn.executemany(&lt;br&gt;
            """&lt;br&gt;
            INSERT INTO fixtures&lt;br&gt;
                (sport, fixture_id, home_team, away_team, kickoff, competition, updated_at)&lt;br&gt;
            VALUES (?, ?, ?, ?, ?, ?, ?)&lt;br&gt;
            ON CONFLICT(sport, fixture_id) DO UPDATE SET&lt;br&gt;
                home_team   = excluded.home_team,&lt;br&gt;
                away_team   = excluded.away_team,&lt;br&gt;
                kickoff     = excluded.kickoff,&lt;br&gt;
                competition = excluded.competition,&lt;br&gt;
                updated_at  = excluded.updated_at&lt;br&gt;
            """,&lt;br&gt;
            rows,&lt;br&gt;
        )&lt;br&gt;
        conn.commit()&lt;br&gt;
    return len(rows)&lt;/p&gt;

&lt;p&gt;def query_fixtures(&lt;br&gt;
    sport: str, date: str | None, competition: str | None, limit: int, offset: int&lt;br&gt;
) -&amp;gt; list[dict]:&lt;br&gt;
    sql = "SELECT * FROM fixtures WHERE sport = ?"&lt;br&gt;
    args: list = [sport]&lt;br&gt;
    if date:&lt;br&gt;
        sql += " AND substr(kickoff, 1, 10) = ?"&lt;br&gt;
        args.append(date)&lt;br&gt;
    if competition:&lt;br&gt;
        sql += " AND competition = ?"&lt;br&gt;
        args.append(competition)&lt;br&gt;
    sql += " ORDER BY kickoff LIMIT ? OFFSET ?"&lt;br&gt;
    args += [limit, offset]&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with closing(connect()) as conn:
    return [dict(r) for r in conn.execute(sql, args).fetchall()]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The ON CONFLICT ... DO UPDATE clause makes every sync idempotent. Run it ten times and you still have exactly one row per fixture, with the latest data. That’s what lets you retry failed syncs without fear.&lt;/p&gt;

&lt;p&gt;Step 4: The Sync Logic&lt;/p&gt;

&lt;p&gt;Create app/sync.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import asyncio&lt;br&gt;
import logging&lt;br&gt;
from datetime import date, timedelta&lt;/p&gt;

&lt;p&gt;from .client import OrbistatsClient&lt;br&gt;
from .db import upsert_fixtures&lt;/p&gt;

&lt;p&gt;log = logging.getLogger("sync")&lt;/p&gt;

&lt;p&gt;async def sync_sport_day(client: OrbistatsClient, sport: str, day: date) -&amp;gt; int:&lt;br&gt;
    items = [f async for f in client.paginate(f"/{sport}/fixtures", date=day.isoformat())]&lt;br&gt;
    # sqlite3 is blocking, so keep it off the event loop&lt;br&gt;
    return await asyncio.to_thread(upsert_fixtures, sport, items)&lt;/p&gt;

&lt;p&gt;async def sync_all(client: OrbistatsClient, sports: list[str], days: int) -&amp;gt; None:&lt;br&gt;
    sem = asyncio.Semaphore(3)  # be polite: at most 3 concurrent upstream jobs&lt;br&gt;
    today = date.today()&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async def job(sport: str, offset: int) -&amp;gt; None:
    day = today + timedelta(days=offset)
    async with sem:
        try:
            count = await sync_sport_day(client, sport, day)
            log.info("synced %s %s: %d fixtures", sport, day, count)
        except Exception:
            # one failed sport/day must not abort the rest
            log.exception("sync failed for %s %s", sport, day)

await asyncio.gather(*(job(s, d) for s in sports for d in range(days)))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;async def sync_loop(&lt;br&gt;
    client: OrbistatsClient, sports: list[str], days: int, interval: int&lt;br&gt;
) -&amp;gt; None:&lt;br&gt;
    while True:&lt;br&gt;
        await sync_all(client, sports, days)&lt;br&gt;
        await asyncio.sleep(interval)&lt;/p&gt;

&lt;p&gt;Notes:&lt;/p&gt;

&lt;p&gt;asyncio.Semaphore(3) caps concurrency so a 13-sport × 7-day sync doesn’t fire 91 requests at once and trigger rate limits.&lt;br&gt;
Failures are isolated per job with logging. One bad day doesn’t poison the whole run.&lt;br&gt;
asyncio.to_thread keeps blocking SQLite calls from freezing the event loop.&lt;br&gt;
Step 5: The FastAPI App&lt;/p&gt;

&lt;p&gt;Create app/main.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import asyncio&lt;br&gt;
import logging&lt;br&gt;
import os&lt;br&gt;
from contextlib import asynccontextmanager&lt;/p&gt;

&lt;p&gt;from fastapi import FastAPI, HTTPException, Query&lt;/p&gt;

&lt;p&gt;from .client import OrbistatsClient&lt;br&gt;
from .db import init_db, query_fixtures&lt;br&gt;
from .sync import sync_loop&lt;/p&gt;

&lt;p&gt;logging.basicConfig(level=logging.INFO)&lt;/p&gt;

&lt;p&gt;SPORTS = [s.strip() for s in os.getenv("SPORTS", "football,cricket").split(",") if s.strip()]&lt;br&gt;
SYNC_DAYS = int(os.getenv("SYNC_DAYS", "7"))&lt;br&gt;
SYNC_INTERVAL = int(os.getenv("SYNC_INTERVAL_SECONDS", "900"))&lt;/p&gt;

&lt;p&gt;@asynccontextmanager&lt;br&gt;
async def lifespan(app: FastAPI):&lt;br&gt;
    api_key = os.environ["ORBISTATS_API_KEY"]&lt;br&gt;
    init_db()&lt;br&gt;
    client = OrbistatsClient(api_key)&lt;br&gt;
    task = asyncio.create_task(sync_loop(client, SPORTS, SYNC_DAYS, SYNC_INTERVAL))&lt;br&gt;
    try:&lt;br&gt;
        yield&lt;br&gt;
    finally:&lt;br&gt;
        task.cancel()&lt;br&gt;
        await client.aclose()&lt;/p&gt;

&lt;p&gt;app = FastAPI(title="Fixtures Sync Service", lifespan=lifespan)&lt;/p&gt;

&lt;p&gt;@app.get("/health")&lt;br&gt;
def health():&lt;br&gt;
    return {"status": "ok", "sports": SPORTS}&lt;/p&gt;

&lt;p&gt;@app.get("/sports")&lt;br&gt;
def sports():&lt;br&gt;
    return {"sports": SPORTS}&lt;/p&gt;

&lt;p&gt;@app.get("/fixtures")&lt;br&gt;
def fixtures(&lt;br&gt;
    sport: str,&lt;br&gt;
    date: str | None = Query(None, pattern=r"^\d{4}-\d{2}-\d{2}$"),&lt;br&gt;
    competition: str | None = None,&lt;br&gt;
    limit: int = Query(50, ge=1, le=200),&lt;br&gt;
    offset: int = Query(0, ge=0),&lt;br&gt;
):&lt;br&gt;
    if sport not in SPORTS:&lt;br&gt;
        raise HTTPException(status_code=404, detail=f"Sport '{sport}' is not synced")&lt;br&gt;
    return {&lt;br&gt;
        "sport": sport,&lt;br&gt;
        "count": len(rows := query_fixtures(sport, date, competition, limit, offset)),&lt;br&gt;
        "data": rows,&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;Run it:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
export $(grep -v '^#' .env | xargs)&lt;br&gt;
uvicorn app.main:app --reload&lt;/p&gt;

&lt;p&gt;Then query your own API:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
curl "&lt;a href="http://localhost:8000/fixtures?sport=football&amp;amp;date=2026-11-21" rel="noopener noreferrer"&gt;http://localhost:8000/fixtures?sport=football&amp;amp;date=2026-11-21&lt;/a&gt;"&lt;/p&gt;

&lt;p&gt;Open &lt;a href="http://localhost:8000/docs" rel="noopener noreferrer"&gt;http://localhost:8000/docs&lt;/a&gt; for FastAPI’s automatic interactive documentation. Responses now come from local disk in milliseconds, whatever the upstream is doing.&lt;/p&gt;

&lt;p&gt;Step 6: Test It Without Calling the Real API&lt;/p&gt;

&lt;p&gt;httpx.MockTransport lets us simulate paginated responses and a 429. Create tests/test_client.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import httpx&lt;br&gt;
import pytest&lt;/p&gt;

&lt;p&gt;from app.client import OrbistatsClient&lt;/p&gt;

&lt;p&gt;pytestmark = pytest.mark.asyncio&lt;/p&gt;

&lt;p&gt;async def test_paginates_and_retries_on_429(monkeypatch):&lt;br&gt;
    async def no_sleep(_):  # keep the test fast&lt;br&gt;
        return None&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;monkeypatch.setattr("app.client.asyncio.sleep", no_sleep)
calls = {"n": 0}

def handler(request: httpx.Request) -&amp;gt; httpx.Response:
    calls["n"] += 1
    page = int(request.url.params["page"])
    if calls["n"] == 1:
        return httpx.Response(429, headers={"Retry-After": "0"})
    return httpx.Response(
        200,
        json={
            "data": [{"fixture_id": f"p{page}"}],
            "pagination": {"page": page, "total_pages": 2},
        },
    )

mock = httpx.AsyncClient(
    base_url="https://api.orbistats.com/v1",
    transport=httpx.MockTransport(handler),
)
client = OrbistatsClient("test-key", client=mock)

ids = [i["fixture_id"] async for i in client.paginate("/football/fixtures")]

assert ids == ["p1", "p2"]
assert calls["n"] == 3  # 429 + page 1 + page 2
await client.aclose()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Add a pytest.ini:&lt;/p&gt;

&lt;p&gt;ini&lt;br&gt;
[pytest]&lt;br&gt;
asyncio_mode = auto&lt;/p&gt;

&lt;p&gt;Run:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
pytest -q&lt;br&gt;
Step 7: Dockerize It&lt;br&gt;
dockerfile&lt;br&gt;
FROM python:3.12-slim&lt;br&gt;
WORKDIR /app&lt;br&gt;
COPY requirements.txt .&lt;br&gt;
RUN pip install --no-cache-dir -r requirements.txt&lt;br&gt;
COPY app ./app&lt;br&gt;
ENV DB_PATH=/data/fixtures.db&lt;br&gt;
VOLUME ["/data"]&lt;br&gt;
EXPOSE 8000&lt;br&gt;
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]&lt;br&gt;
bash&lt;br&gt;
docker build -t fixtures-sync .&lt;br&gt;
docker run -p 8000:8000 -v fixtures-data:/data \&lt;br&gt;
  -e ORBISTATS_API_KEY=your_key -e SPORTS=football,cricket fixtures-sync&lt;/p&gt;

&lt;p&gt;Mount a volume for /data so your database survives container restarts.&lt;/p&gt;

&lt;p&gt;Where to Take This Next&lt;br&gt;
More sports. Add the other slugs to SPORTS. Orbistats covers 13 sports with one schema, so the sync code doesn’t change.&lt;br&gt;
Statistics and standings. Add tables for team and player data from the Sports Statistics API.&lt;br&gt;
Historical backfill. Loop sync_sport_day over past dates, or use the Historical Sports Data API for analytics and model training.&lt;br&gt;
Postgres. Swap SQLite for Postgres when you need multiple writers. The ON CONFLICT syntax is nearly identical.&lt;br&gt;
Push, not poll. For near-real-time fields, add webhooks or the WebSocket API on top of the scheduled sync.&lt;br&gt;
Monitoring. Check the provider’s status page and changelog when debugging sync anomalies.&lt;br&gt;
Who Needs This Pattern?&lt;br&gt;
Fantasy platforms scoring thousands of users from one dataset (Fantasy &amp;amp; Analytics solutions)&lt;br&gt;
Data science teams that need clean, queryable history (Analytics &amp;amp; Data Science)&lt;br&gt;
Media sites that want instant page loads without hammering an upstream API&lt;/p&gt;

&lt;p&gt;Working on odds-related features? The Python Odds Converter tutorial pairs nicely with this service.&lt;/p&gt;

&lt;p&gt;Production Checklist&lt;br&gt;
[ ] API key from environment variables or a secrets manager&lt;br&gt;
[ ] Retries limited to 429, 5xx and network errors (done)&lt;br&gt;
[ ] Concurrency cap on upstream calls (done)&lt;br&gt;
[ ] Idempotent upserts (done)&lt;br&gt;
[ ] Persistent volume for the database&lt;br&gt;
[ ] A health check and alert if updated_at goes stale&lt;br&gt;
[ ] Review the data licensing terms before storing or redistributing data&lt;br&gt;
[ ] Pick an access plan on the pricing page that fits your sync window&lt;br&gt;
Recap&lt;/p&gt;

&lt;p&gt;You built a service that:&lt;/p&gt;

&lt;p&gt;Syncs fixtures on a schedule with pagination, retries and backoff&lt;br&gt;
Stores them with idempotent upserts&lt;br&gt;
Serves users from a fast local database&lt;br&gt;
Is tested without hitting the real API&lt;br&gt;
Ships as a Docker container&lt;/p&gt;

&lt;p&gt;Get started with the Orbistats documentation, explore the Glossary for sports-data terms, or request API access.&lt;/p&gt;

&lt;p&gt;Would you like a follow-up that adds Postgres and a live odds-movement table? Let me know in the comments. 💬&lt;/p&gt;

</description>
      <category>python</category>
      <category>fastapi</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build a Discord Sports Bot with discord.js &amp; an API</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Wed, 18 Nov 2026 13:20:40 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-discord-sports-bot-with-discordjs-an-api-3mgj</link>
      <guid>https://dev.to/orbistats/build-a-discord-sports-bot-with-discordjs-an-api-3mgj</guid>
      <description>&lt;p&gt;Every sports Discord server eventually asks the same question: “What matches are on today?”&lt;/p&gt;

&lt;p&gt;In this tutorial we’ll build a Discord bot with a single, polished slash command:&lt;/p&gt;

&lt;p&gt;/fixtures sport:cricket date:2026-11-21&lt;/p&gt;

&lt;p&gt;It returns a clean embed of matches grouped by competition. We’ll cover:&lt;/p&gt;

&lt;p&gt;Registering slash commands with dropdown choices for 13 sports&lt;br&gt;
Calling a sports API safely from Node.js&lt;br&gt;
A small TTL cache so busy servers don’t burn your quota&lt;br&gt;
Rate-limit and error handling with friendly messages&lt;br&gt;
Ideas for adding goal alerts with webhooks&lt;/p&gt;

&lt;p&gt;The data comes from the Orbistats API, which covers 13 sports under one schema, so one command handles every sport.&lt;/p&gt;

&lt;p&gt;Prerequisites&lt;br&gt;
Node.js 20+ (built-in fetch)&lt;br&gt;
A Discord account and a server where you can add bots&lt;br&gt;
An Orbistats API key via Request Access. You can also test requests in the sandbox.&lt;br&gt;
Step 1: Create the Discord Application&lt;br&gt;
Open the Discord Developer Portal and click New Application.&lt;br&gt;
Under Bot, click Reset Token and copy it.&lt;br&gt;
Copy the Application ID from the General Information page.&lt;br&gt;
Under OAuth2 → URL Generator, tick bot and applications.commands, then open the generated URL to invite the bot to your test server.&lt;br&gt;
Copy your server’s ID (enable Developer Mode, then right-click the server).&lt;br&gt;
Step 2: Project Setup&lt;br&gt;
bash&lt;br&gt;
mkdir sports-discord-bot &amp;amp;&amp;amp; cd sports-discord-bot&lt;br&gt;
npm init -y&lt;br&gt;
npm install discord.js dotenv&lt;/p&gt;

&lt;p&gt;In package.json add "type": "module". Create .env:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
DISCORD_TOKEN=your_bot_token&lt;br&gt;
DISCORD_CLIENT_ID=your_application_id&lt;br&gt;
DISCORD_GUILD_ID=your_test_server_id&lt;br&gt;
ORBISTATS_API_KEY=your_orbistats_key&lt;/p&gt;

&lt;p&gt;Add .env to .gitignore immediately.&lt;/p&gt;

&lt;p&gt;Step 3: Define the Sports List Once&lt;/p&gt;

&lt;p&gt;Create sports.js. The value is the sport segment of the API path. Football and cricket are used in Orbistats’ public examples. Confirm the others in the API reference.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
export const SPORTS = [&lt;br&gt;
  { name: "⚽ Football", value: "football" },&lt;br&gt;
  { name: "🏀 Basketball", value: "basketball" },&lt;br&gt;
  { name: "🏈 American Football", value: "american-football" },&lt;br&gt;
  { name: "🏏 Cricket", value: "cricket" },&lt;br&gt;
  { name: "🎾 Tennis", value: "tennis" },&lt;br&gt;
  { name: "⚾ Baseball", value: "baseball" },&lt;br&gt;
  { name: "🎮 Esports", value: "esports" },&lt;br&gt;
  { name: "🥊 Combat Sports", value: "combat-sports" },&lt;br&gt;
  { name: "🏐 Volleyball", value: "volleyball" },&lt;br&gt;
  { name: "🤾 Handball", value: "handball" },&lt;br&gt;
  { name: "🏒 Ice Hockey", value: "ice-hockey" },&lt;br&gt;
  { name: "⛳ Golf", value: "golf" },&lt;br&gt;
  { name: "🏇 Horse Racing", value: "horse-racing" },&lt;br&gt;
];&lt;/p&gt;

&lt;p&gt;Discord allows up to 25 choices per option, so 13 sports fit comfortably.&lt;/p&gt;

&lt;p&gt;Step 4: The API Client with a TTL Cache&lt;/p&gt;

&lt;p&gt;Create orbistats.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
const BASE_URL = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;br&gt;
const TTL_MS = 60_000;&lt;br&gt;
const cache = new Map();&lt;/p&gt;

&lt;p&gt;export class RateLimitedError extends Error {}&lt;/p&gt;

&lt;p&gt;export async function getFixtures({ sport, date, perPage = 50 }) {&lt;br&gt;
  const cacheKey = &lt;code&gt;${sport}:${date}:${perPage}&lt;/code&gt;;&lt;br&gt;
  const hit = cache.get(cacheKey);&lt;br&gt;
  if (hit &amp;amp;&amp;amp; hit.expires &amp;gt; Date.now()) return hit.value;&lt;/p&gt;

&lt;p&gt;const url = new URL(&lt;code&gt;${BASE_URL}/${sport}/fixtures&lt;/code&gt;);&lt;br&gt;
  url.searchParams.set("date", date);&lt;br&gt;
  url.searchParams.set("per_page", String(perPage));&lt;/p&gt;

&lt;p&gt;const res = await fetch(url, {&lt;br&gt;
    headers: {&lt;br&gt;
      Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_API_KEY}&lt;/code&gt;,&lt;br&gt;
      Accept: "application/json",&lt;br&gt;
    },&lt;br&gt;
    signal: AbortSignal.timeout(8000),&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;if (res.status === 429) throw new RateLimitedError("rate limited");&lt;br&gt;
  if (!res.ok) throw new Error(&lt;code&gt;Upstream HTTP ${res.status}&lt;/code&gt;);&lt;/p&gt;

&lt;p&gt;const json = await res.json(); // { data, meta, pagination }&lt;br&gt;
  cache.set(cacheKey, { value: json, expires: Date.now() + TTL_MS });&lt;br&gt;
  return json;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Why cache? In a popular server, twenty people may run /fixtures sport:football within a minute. With a 60-second cache that’s one upstream request instead of twenty.&lt;/p&gt;

&lt;p&gt;Step 5: Register the Slash Command&lt;/p&gt;

&lt;p&gt;Create deploy-commands.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import "dotenv/config";&lt;br&gt;
import { REST, Routes, SlashCommandBuilder } from "discord.js";&lt;br&gt;
import { SPORTS } from "./sports.js";&lt;/p&gt;

&lt;p&gt;const command = new SlashCommandBuilder()&lt;br&gt;
  .setName("fixtures")&lt;br&gt;
  .setDescription("Show fixtures for a sport and date")&lt;br&gt;
  .addStringOption((o) =&amp;gt;&lt;br&gt;
    o.setName("sport").setDescription("Which sport?").setRequired(true).addChoices(...SPORTS)&lt;br&gt;
  )&lt;br&gt;
  .addStringOption((o) =&amp;gt;&lt;br&gt;
    o.setName("date").setDescription("YYYY-MM-DD (defaults to today, UTC)")&lt;br&gt;
  );&lt;/p&gt;

&lt;p&gt;const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN);&lt;/p&gt;

&lt;p&gt;await rest.put(&lt;br&gt;
  Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.DISCORD_GUILD_ID),&lt;br&gt;
  { body: [command.toJSON()] }&lt;br&gt;
);&lt;/p&gt;

&lt;p&gt;console.log("✅ Slash command registered");&lt;/p&gt;

&lt;p&gt;Run it once:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
node deploy-commands.js&lt;/p&gt;

&lt;p&gt;Guild commands update instantly, which is ideal while developing. Switch to Routes.applicationCommands(clientId) for global deployment later (propagation can take a while).&lt;/p&gt;

&lt;p&gt;Step 6: The Bot Itself&lt;/p&gt;

&lt;p&gt;Create index.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import "dotenv/config";&lt;br&gt;
import { Client, EmbedBuilder, Events, GatewayIntentBits } from "discord.js";&lt;br&gt;
import { getFixtures, RateLimitedError } from "./orbistats.js";&lt;br&gt;
import { SPORTS } from "./sports.js";&lt;/p&gt;

&lt;p&gt;const client = new Client({ intents: [GatewayIntentBits.Guilds] });&lt;br&gt;
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;&lt;/p&gt;

&lt;p&gt;function sportLabel(value) {&lt;br&gt;
  return SPORTS.find((s) =&amp;gt; s.value === value)?.name ?? value;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function formatKickoff(iso) {&lt;br&gt;
  const ms = Date.parse(iso);&lt;br&gt;
  if (Number.isNaN(ms)) return iso ?? "TBA";&lt;br&gt;
  return &lt;code&gt;&amp;lt;t:${Math.floor(ms / 1000)}:t&amp;gt;&lt;/code&gt;; // Discord renders in each user's timezone&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function buildEmbed({ sport, date, json }) {&lt;br&gt;
  const fixtures = json.data ?? [];&lt;br&gt;
  const embed = new EmbedBuilder()&lt;br&gt;
    .setTitle(&lt;code&gt;${sportLabel(sport)} fixtures · ${date}&lt;/code&gt;)&lt;br&gt;
    .setColor(0x1db954)&lt;br&gt;
    .setFooter({ text: "Data: Orbistats" })&lt;br&gt;
    .setTimestamp();&lt;/p&gt;

&lt;p&gt;if (fixtures.length === 0) {&lt;br&gt;
    return embed.setDescription("No fixtures found for this date.");&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;const byCompetition = {};&lt;br&gt;
  for (const f of fixtures) (byCompetition[f.competition ?? "Other"] ||= []).push(f);&lt;/p&gt;

&lt;p&gt;let description = "";&lt;br&gt;
  for (const [competition, items] of Object.entries(byCompetition)) {&lt;br&gt;
    const block =&lt;br&gt;
      &lt;code&gt;**${competition}**\n&lt;/code&gt; +&lt;br&gt;
      items.map((f) =&amp;gt; &lt;code&gt;${formatKickoff(f.kickoff)} — ${f.home_team} vs ${f.away_team}&lt;/code&gt;).join("\n") +&lt;br&gt;
      "\n\n";&lt;br&gt;
    if (description.length + block.length &amp;gt; 3800) {&lt;br&gt;
      description += "…and more. Narrow by date to see the rest.";&lt;br&gt;
      break;&lt;br&gt;
    }&lt;br&gt;
    description += block;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;return embed.setDescription(description.trim());&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;client.once(Events.ClientReady, (c) =&amp;gt; console.log(&lt;code&gt;Logged in as ${c.user.tag}&lt;/code&gt;));&lt;/p&gt;

&lt;p&gt;client.on(Events.InteractionCreate, async (interaction) =&amp;gt; {&lt;br&gt;
  if (!interaction.isChatInputCommand() || interaction.commandName !== "fixtures") return;&lt;/p&gt;

&lt;p&gt;const sport = interaction.options.getString("sport", true);&lt;br&gt;
  const date = interaction.options.getString("date") ?? new Date().toISOString().slice(0, 10);&lt;/p&gt;

&lt;p&gt;if (!DATE_RE.test(date)) {&lt;br&gt;
    return interaction.reply({ content: "Please use the format YYYY-MM-DD.", ephemeral: true });&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;await interaction.deferReply(); // we have 15 minutes instead of 3 seconds&lt;/p&gt;

&lt;p&gt;try {&lt;br&gt;
    const json = await getFixtures({ sport, date });&lt;br&gt;
    await interaction.editReply({ embeds: [buildEmbed({ sport, date, json })] });&lt;br&gt;
  } catch (err) {&lt;br&gt;
    console.error(err.message); // never log the API key&lt;br&gt;
    const message =&lt;br&gt;
      err instanceof RateLimitedError&lt;br&gt;
        ? "⏳ The data provider is busy. Try again in a minute."&lt;br&gt;
        : "⚠️ Couldn't load fixtures right now. Please try again later.";&lt;br&gt;
    await interaction.editReply({ content: message });&lt;br&gt;
  }&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;client.login(process.env.DISCORD_TOKEN);&lt;/p&gt;

&lt;p&gt;Run it:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
node index.js&lt;/p&gt;

&lt;p&gt;In Discord type /fixtures, choose a sport and watch the embed appear.&lt;/p&gt;

&lt;p&gt;Why These Design Choices Matter&lt;/p&gt;

&lt;p&gt;deferReply() Discord requires a response within 3 seconds. API calls can be slower, so defer first, then edit the reply.&lt;/p&gt;

&lt;p&gt;Discord timestamps () Every user sees kickoff in their own timezone. No timezone maths and no confused fans.&lt;/p&gt;

&lt;p&gt;Embed size limits Embed descriptions max out at 4096 characters. We stop at roughly 3800 and add a “…and more” line instead of crashing.&lt;/p&gt;

&lt;p&gt;Friendly errors Users don’t need to see HTTP 429. They need to know when to retry.&lt;/p&gt;

&lt;p&gt;Step 7: Keep the Bot Running&lt;/p&gt;

&lt;p&gt;For quick hosting use any Node-friendly platform. A minimal Dockerfile:&lt;/p&gt;

&lt;p&gt;dockerfile&lt;br&gt;
FROM node:20-alpine&lt;br&gt;
WORKDIR /app&lt;br&gt;
COPY package*.json ./&lt;br&gt;
RUN npm ci --omit=dev&lt;br&gt;
COPY . .&lt;br&gt;
CMD ["node", "index.js"]&lt;/p&gt;

&lt;p&gt;Pass secrets as environment variables on the host, never inside the image.&lt;/p&gt;

&lt;p&gt;Level-Up Ideas&lt;br&gt;
Goal and result alerts. Instead of polling, receive pushed events through webhooks and post to a channel via a Discord webhook. See also the Live Scores API.&lt;br&gt;
Per-server favourite sport. Store a default sport per guild so /fixtures needs no arguments.&lt;br&gt;
Autocomplete for competitions. Use competition_id filters and Discord’s autocomplete interactions.&lt;br&gt;
Live command. Add /live that reads the live endpoint and refreshes one message every 30 seconds.&lt;br&gt;
Odds helper. Combine fixtures with an odds-conversion command, using ideas from Python Odds Converter: Decimal, American &amp;amp; Fractional Odds.&lt;br&gt;
Multi-Sport for Free&lt;/p&gt;

&lt;p&gt;Because Orbistats exposes cricket, tennis, basketball, football and nine more sports through a consistent schema, the same buildEmbed function renders all of them. That’s the payoff of a unified API: one command, thirteen sports, zero per-sport code.&lt;/p&gt;

&lt;p&gt;If you’d like a deeper Node.js walkthrough for a single sport, read Build a Cricket Fixtures Finder + Live Scoreboard in Node.js.&lt;/p&gt;

&lt;p&gt;Production Checklist&lt;br&gt;
[ ] Secrets in environment variables&lt;br&gt;
[ ] 60-second cache (done) and a per-user cooldown if your server is large&lt;br&gt;
[ ] Friendly handling of 401, 429 and 5xx (done)&lt;br&gt;
[ ] Timeouts on every upstream call (done)&lt;br&gt;
[ ] Review the data licensing terms before running a public bot&lt;br&gt;
[ ] Compare plans on the pricing page so your access window matches your traffic&lt;br&gt;
Resources&lt;br&gt;
Orbistats API reference&lt;br&gt;
Documentation&lt;br&gt;
Orbistats Discord community&lt;br&gt;
Get API access&lt;/p&gt;

&lt;p&gt;Which sport should get its own custom embed next? Tell me below. 🏏🎾🏀&lt;/p&gt;

</description>
      <category>discord</category>
      <category>node</category>
      <category>javascript</category>
      <category>api</category>
    </item>
    <item>
      <title>Build a Live Football Dashboard with Next.js and an API</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Wed, 18 Nov 2026 13:18:37 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-live-football-dashboard-with-nextjs-and-an-api-31ef</link>
      <guid>https://dev.to/orbistats/build-a-live-football-dashboard-with-nextjs-and-an-api-31ef</guid>
      <description>&lt;p&gt;Most “build a live score app” tutorials make the same mistake in the first five minutes: they call the sports API straight from the browser, which means your API key ships to every visitor.&lt;/p&gt;

&lt;p&gt;In this tutorial we’ll build a football dashboard in Next.js (App Router + TypeScript) the right way:&lt;/p&gt;

&lt;p&gt;A server-side proxy so the API key never reaches the browser&lt;br&gt;
Fixtures by date, grouped by competition, with search and pagination&lt;br&gt;
A live ticker that refreshes automatically&lt;br&gt;
Caching and error handling so your dashboard survives rate limits&lt;/p&gt;

&lt;p&gt;We’ll use the Orbistats Sports Data API, but the architecture works with any REST sports provider.&lt;/p&gt;

&lt;p&gt;What We’re Building&lt;br&gt;
Browser (React UI)&lt;br&gt;
     │   GET /api/fixtures?date=2026-11-21&lt;br&gt;
     ▼&lt;br&gt;
Next.js Route Handler  ──(adds Bearer key, caches 60s)──►  api.orbistats.com/v1&lt;br&gt;
     ▲&lt;br&gt;
     └── JSON back to the UI&lt;/p&gt;

&lt;p&gt;The browser only ever talks to your /api/* routes. Your key lives in a server environment variable.&lt;/p&gt;

&lt;p&gt;Prerequisites&lt;br&gt;
Node.js 20+&lt;br&gt;
Basic React and TypeScript&lt;br&gt;
An Orbistats API key: request access (the Free plan gives a 1-hour window, plenty to follow along), or try the sandbox first&lt;br&gt;
Step 1: Create the Project&lt;br&gt;
bash&lt;br&gt;
npx create-next-app@latest football-dashboard --typescript --app --eslint&lt;br&gt;
cd football-dashboard&lt;/p&gt;

&lt;p&gt;Add your key to .env.local (this file is git-ignored by default):&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
ORBISTATS_API_KEY=your_api_key_here&lt;/p&gt;

&lt;p&gt;Never prefix it with NEXT_PUBLIC_. That prefix exposes a variable to the browser.&lt;/p&gt;

&lt;p&gt;Step 2: Types&lt;/p&gt;

&lt;p&gt;The fixtures endpoint returns data, meta and pagination. Create lib/types.ts:&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
export interface Fixture {&lt;br&gt;
  fixture_id: string;&lt;br&gt;
  home_team: string;&lt;br&gt;
  away_team: string;&lt;br&gt;
  kickoff: string;&lt;br&gt;
  competition: string;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export interface FixturesResponse {&lt;br&gt;
  data: Fixture[];&lt;br&gt;
  meta: { sport: string; count: number };&lt;br&gt;
  pagination: {&lt;br&gt;
    page: number;&lt;br&gt;
    per_page: number;&lt;br&gt;
    total_pages: number;&lt;br&gt;
    total_results: number;&lt;br&gt;
  };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export interface LiveMatch {&lt;br&gt;
  match_id: string;&lt;br&gt;
  status: string;&lt;br&gt;
  minute?: number;&lt;br&gt;
  home: { name: string; score: number };&lt;br&gt;
  away: { name: string; score: number };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;You don’t need to model every field. Add more as your UI needs them. Check the API reference for the full response fields.&lt;/p&gt;

&lt;p&gt;Step 3: A Tiny, Reusable API Client&lt;/p&gt;

&lt;p&gt;Create lib/orbistats.ts. This is the only file that knows about authentication.&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
const BASE_URL = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;/p&gt;

&lt;p&gt;export class OrbistatsError extends Error {&lt;br&gt;
  constructor(public status: number, message: string) {&lt;br&gt;
    super(message);&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;type Params = Record;&lt;/p&gt;

&lt;p&gt;export async function orbistats(&lt;br&gt;
  path: string,&lt;br&gt;
  params: Params = {},&lt;br&gt;
  revalidateSeconds = 30&lt;br&gt;
): Promise {&lt;br&gt;
  const key = process.env.ORBISTATS_API_KEY;&lt;br&gt;
  if (!key) throw new OrbistatsError(500, "ORBISTATS_API_KEY is not set");&lt;/p&gt;

&lt;p&gt;const url = new URL(&lt;code&gt;${BASE_URL}${path}&lt;/code&gt;);&lt;br&gt;
  for (const [k, v] of Object.entries(params)) {&lt;br&gt;
    if (v !== undefined &amp;amp;&amp;amp; v !== "") url.searchParams.set(k, String(v));&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;const res = await fetch(url, {&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Bearer ${key}&lt;/code&gt;, Accept: "application/json" },&lt;br&gt;
    next: { revalidate: revalidateSeconds }, // server-side cache&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;if (!res.ok) throw new OrbistatsError(res.status, await res.text());&lt;br&gt;
  return res.json() as Promise;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;next: { revalidate } tells Next.js to cache the upstream response. If 500 visitors load the same date within a minute, you make one upstream request instead of 500. That one line protects both your bill and your rate limit.&lt;/p&gt;

&lt;p&gt;Step 4: The Fixtures Route Handler&lt;/p&gt;

&lt;p&gt;Create app/api/fixtures/route.ts:&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
import { NextRequest, NextResponse } from "next/server";&lt;br&gt;
import { orbistats, OrbistatsError } from "@/lib/orbistats";&lt;br&gt;
import type { FixturesResponse } from "@/lib/types";&lt;/p&gt;

&lt;p&gt;const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;&lt;/p&gt;

&lt;p&gt;export async function GET(req: NextRequest) {&lt;br&gt;
  const sp = req.nextUrl.searchParams;&lt;br&gt;
  const date = sp.get("date") ?? new Date().toISOString().slice(0, 10);&lt;br&gt;
  const page = Math.max(1, Number(sp.get("page") ?? 1));&lt;/p&gt;

&lt;p&gt;if (!DATE_RE.test(date)) {&lt;br&gt;
    return NextResponse.json({ error: "date must be YYYY-MM-DD" }, { status: 400 });&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;try {&lt;br&gt;
    const data = await orbistats(&lt;br&gt;
      "/football/fixtures",&lt;br&gt;
      { date, page, per_page: 50 },&lt;br&gt;
      60&lt;br&gt;
    );&lt;br&gt;
    return NextResponse.json(data);&lt;br&gt;
  } catch (e) {&lt;br&gt;
    if (e instanceof OrbistatsError) {&lt;br&gt;
      if (e.status === 429) {&lt;br&gt;
        return NextResponse.json({ error: "Busy right now, retry shortly." }, { status: 429 });&lt;br&gt;
      }&lt;br&gt;
      console.error("Orbistats error", e.status); // never log the key&lt;br&gt;
      return NextResponse.json({ error: "Upstream error" }, { status: 502 });&lt;br&gt;
    }&lt;br&gt;
    return NextResponse.json({ error: "Unexpected error" }, { status: 500 });&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Two details worth copying into every integration:&lt;/p&gt;

&lt;p&gt;Validate input before forwarding it upstream.&lt;br&gt;
Translate errors into safe messages. Never return the raw upstream body to the browser.&lt;br&gt;
Step 5: The Live Route&lt;/p&gt;

&lt;p&gt;Live scores change every few seconds, so cache briefly. Create app/api/live/route.ts:&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
import { NextResponse } from "next/server";&lt;br&gt;
import { orbistats, OrbistatsError } from "@/lib/orbistats";&lt;br&gt;
import type { LiveMatch } from "@/lib/types";&lt;/p&gt;

&lt;p&gt;export async function GET() {&lt;br&gt;
  try {&lt;br&gt;
    const json = await orbistats(&lt;br&gt;
      "/football/matches/live",&lt;br&gt;
      {},&lt;br&gt;
      10 // 10-second cache is plenty for a ticker&lt;br&gt;
    );&lt;br&gt;
    const matches = Array.isArray(json) ? json : json.data ?? [];&lt;br&gt;
    return NextResponse.json({ matches });&lt;br&gt;
  } catch (e) {&lt;br&gt;
    const status = e instanceof OrbistatsError &amp;amp;&amp;amp; e.status === 429 ? 429 : 502;&lt;br&gt;
    return NextResponse.json({ matches: [], error: "Live data unavailable" }, { status });&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;The normalisation line (Array.isArray(json) ? json : json.data) makes the handler tolerant of either response shape. Confirm the final live schema in the documentation.&lt;/p&gt;

&lt;p&gt;Step 6: The Live Ticker Component&lt;/p&gt;

&lt;p&gt;Create components/LiveTicker.tsx:&lt;/p&gt;

&lt;p&gt;tsx&lt;br&gt;
"use client";&lt;br&gt;
import { useEffect, useState } from "react";&lt;br&gt;
import type { LiveMatch } from "@/lib/types";&lt;/p&gt;

&lt;p&gt;export default function LiveTicker() {&lt;br&gt;
  const [matches, setMatches] = useState([]);&lt;br&gt;
  const [error, setError] = useState(false);&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    let alive = true;&lt;br&gt;
    const controller = new AbortController();&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function load() {
  try {
    const res = await fetch("/api/live", { signal: controller.signal });
    const json = await res.json();
    if (alive) { setMatches(json.matches ?? []); setError(!res.ok); }
  } catch {
    if (alive) setError(true);
  }
}

load();
const id = setInterval(load, 15_000);
return () =&amp;gt; { alive = false; controller.abort(); clearInterval(id); };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}, []);&lt;/p&gt;

&lt;p&gt;if (error &amp;amp;&amp;amp; matches.length === 0) return &lt;/p&gt;
&lt;p&gt;Live scores temporarily unavailable.&lt;/p&gt;;&lt;br&gt;
  if (matches.length === 0) return &lt;p&gt;No live matches right now.&lt;/p&gt;;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;ul&gt;

      {matches.map((m) =&amp;gt; (
        &lt;li&gt;

          &lt;strong&gt;{m.home.name}&lt;/strong&gt; {m.home.score} – {m.away.score}{" "}
          &lt;strong&gt;{m.away.name}&lt;/strong&gt;
          {m.minute !== undefined &amp;amp;&amp;amp; &lt;em&gt; · {m.minute}'&lt;/em&gt;}
        &lt;/li&gt;

      ))}
    &lt;/ul&gt;
&lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;Polling every 15 seconds through your cached route is a sensible starting point. When you need true real-time, move to the WebSocket API or webhooks (more on that at the end).&lt;/p&gt;

&lt;p&gt;Step 7: The Fixtures Browser&lt;/p&gt;

&lt;p&gt;Create components/Fixtures.tsx with a date picker, search box, grouping and pagination:&lt;/p&gt;

&lt;p&gt;tsx&lt;br&gt;
"use client";&lt;br&gt;
import { useEffect, useMemo, useState } from "react";&lt;br&gt;
import type { Fixture, FixturesResponse } from "@/lib/types";&lt;/p&gt;

&lt;p&gt;const today = () =&amp;gt; new Date().toISOString().slice(0, 10);&lt;/p&gt;

&lt;p&gt;export default function Fixtures() {&lt;br&gt;
  const [date, setDate] = useState(today());&lt;br&gt;
  const [page, setPage] = useState(1);&lt;br&gt;
  const [query, setQuery] = useState("");&lt;br&gt;
  const [state, setState] = useState&amp;lt;{ loading: boolean; error?: string; res?: FixturesResponse }&amp;gt;({ loading: true });&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    const controller = new AbortController();&lt;br&gt;
    setState((s) =&amp;gt; ({ ...s, loading: true, error: undefined }));&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch(`/api/fixtures?date=${date}&amp;amp;page=${page}`, { signal: controller.signal })
  .then(async (r) =&amp;gt; {
    const json = await r.json();
    if (!r.ok) throw new Error(json.error ?? "Request failed");
    setState({ loading: false, res: json });
  })
  .catch((e) =&amp;gt; {
    if (e.name !== "AbortError") setState({ loading: false, error: e.message });
  });

return () =&amp;gt; controller.abort();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}, [date, page]);&lt;/p&gt;

&lt;p&gt;const grouped = useMemo(() =&amp;gt; {&lt;br&gt;
    const q = query.trim().toLowerCase();&lt;br&gt;
    const items = (state.res?.data ?? []).filter(&lt;br&gt;
      (f) =&amp;gt; !q || &lt;code&gt;${f.home_team} ${f.away_team} ${f.competition}&lt;/code&gt;.toLowerCase().includes(q)&lt;br&gt;
    );&lt;br&gt;
    return items.reduce&amp;gt;((acc, f) =&amp;gt; {&lt;br&gt;
      (acc[f.competition] ||= []).push(f);&lt;br&gt;
      return acc;&lt;br&gt;
    }, {});&lt;br&gt;
  }, [state.res, query]);&lt;/p&gt;

&lt;p&gt;const totalPages = state.res?.pagination.total_pages ?? 1;&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;br&gt;
         { setDate(e.target.value); setPage(1); }} /&amp;gt;&lt;br&gt;
         setQuery(e.target.value)} /&amp;gt;&lt;br&gt;
      

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  {state.loading &amp;amp;&amp;amp; &amp;lt;p&amp;gt;Loading fixtures…&amp;lt;/p&amp;gt;}
  {state.error &amp;amp;&amp;amp; &amp;lt;p role="alert"&amp;gt;⚠️ {state.error}&amp;lt;/p&amp;gt;}

  {Object.entries(grouped).map(([competition, fixtures]) =&amp;gt; (
    &amp;lt;div key={competition} style={{ marginBottom: 20 }}&amp;gt;
      &amp;lt;h3&amp;gt;{competition}&amp;lt;/h3&amp;gt;
      &amp;lt;ul&amp;gt;
        {fixtures.map((f) =&amp;gt; (
          &amp;lt;li key={f.fixture_id}&amp;gt;
            {new Date(f.kickoff).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}{" "}
            — {f.home_team} vs {f.away_team}
          &amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  ))}

  &amp;lt;div style={{ display: "flex", gap: 8, alignItems: "center" }}&amp;gt;
    &amp;lt;button disabled={page &amp;lt;= 1} onClick={() =&amp;gt; setPage((p) =&amp;gt; p - 1)}&amp;gt;← Prev&amp;lt;/button&amp;gt;
    &amp;lt;span&amp;gt;Page {page} / {totalPages}&amp;lt;/span&amp;gt;
    &amp;lt;button disabled={page &amp;gt;= totalPages} onClick={() =&amp;gt; setPage((p) =&amp;gt; p + 1)}&amp;gt;Next →&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/section&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Notes:&lt;/p&gt;

&lt;p&gt;AbortController cancels in-flight requests when the user changes date quickly, which prevents out-of-order updates (old response overwriting new one).&lt;br&gt;
toLocaleTimeString renders kickoff in the viewer’s timezone. Store and transmit UTC, display locally.&lt;br&gt;
Step 8: Put It Together&lt;/p&gt;

&lt;p&gt;Replace app/page.tsx:&lt;/p&gt;

&lt;p&gt;tsx&lt;br&gt;
import Fixtures from "@/components/Fixtures";&lt;br&gt;
import LiveTicker from "@/components/LiveTicker";&lt;/p&gt;

&lt;p&gt;export default function Home() {&lt;br&gt;
  return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;h1&gt;⚽ Football Dashboard&lt;/h1&gt;
&lt;br&gt;
      &lt;h2&gt;Live now&lt;/h2&gt;
&lt;br&gt;
      &lt;br&gt;
      &lt;h2&gt;Fixtures&lt;/h2&gt;
&lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;Run it:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
npm run dev&lt;/p&gt;

&lt;p&gt;Open &lt;a href="http://localhost:3000" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt;, pick a date and you should see fixtures grouped by competition.&lt;/p&gt;

&lt;p&gt;Step 9: Make It Production-Ready&lt;br&gt;
Rate limits: the server-side cache above is your first defence. Add per-IP rate limiting to /api/* (for example with Upstash Ratelimit) so your own users can’t burn your quota.&lt;br&gt;
Timeouts: add signal: AbortSignal.timeout(8000) to the upstream fetch.&lt;br&gt;
Secrets: set ORBISTATS_API_KEY in your hosting dashboard (Vercel, Netlify, etc.), never in the repo.&lt;br&gt;
Observability: log status codes and latency, never headers.&lt;br&gt;
Licensing: read the data licensing terms before displaying data publicly.&lt;br&gt;
Going Real-Time and Multi-Sport&lt;/p&gt;

&lt;p&gt;Polling is a fine start, but it has limits. For instant updates, subscribe your server to the WebSocket stream and relay to browsers via Server-Sent Events. The Live Scores API is designed for that pattern.&lt;/p&gt;

&lt;p&gt;Because the API is multi-sport, turning this into a cricket, tennis or basketball dashboard is mostly a path change. Orbistats covers football, basketball, cricket, tennis and nine more sports, so make sport a route parameter (/api/[sport]/fixtures) and you have a multi-sport app.&lt;/p&gt;

&lt;p&gt;Don’t want to build UI at all? Drop-in widgets give you live scores with a snippet.&lt;/p&gt;

&lt;p&gt;Related Tutorials&lt;br&gt;
Consuming a Sports Data API in Go with net/http&lt;br&gt;
Build a Cricket Fixtures Finder + Live Scoreboard in Node.js&lt;br&gt;
Recap&lt;/p&gt;

&lt;p&gt;You built a football dashboard that:&lt;/p&gt;

&lt;p&gt;Keeps the API key server-side&lt;br&gt;
Caches upstream calls to protect quota&lt;br&gt;
Handles errors and cancellation properly&lt;br&gt;
Shows fixtures, grouping, search and pagination&lt;br&gt;
Includes a live ticker you can upgrade to WebSockets&lt;/p&gt;

&lt;p&gt;Grab a key via Request Access, follow the quickstart, compare plans on the pricing page, or explore the SDKs.&lt;/p&gt;

&lt;p&gt;What sport should I build next? Tell me in the comments. 👇&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>react</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build a Cricket Fixtures Finder + Live Scoreboard in Node.js (IPL, Ashes &amp; WTC Final Ready)</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Wed, 18 Nov 2026 12:35:15 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-cricket-fixtures-finder-live-scoreboard-in-nodejs-ipl-ashes-wtc-final-ready-4fa</link>
      <guid>https://dev.to/orbistats/build-a-cricket-fixtures-finder-live-scoreboard-in-nodejs-ipl-ashes-wtc-final-ready-4fa</guid>
      <description>&lt;p&gt;Cricket’s next eight months are packed: the IPL 2027 auction, the Border-Gavaskar Trophy, the WTC Final at The Oval, then the Ashes. In this tutorial you will build a small Node.js tool that finds fixtures for any window, shows a live scoreboard, and receives full-time results by webhook, using the Orbistats cricket API. The full calendar is in the cricket data API guide.&lt;/p&gt;

&lt;p&gt;What you will build&lt;/p&gt;

&lt;p&gt;A resilient API helper with retries&lt;br&gt;
A fixtures finder for any date window&lt;br&gt;
A live scoreboard (polling first, then WebSocket)&lt;br&gt;
An odds call and a signed webhook receiver&lt;/p&gt;

&lt;p&gt;Prerequisites: Node 18+ (for built-in fetch) and a free API key from signup. Test in the sandbox first, since the same endpoints return sample data.&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
mkdir cricket-live &amp;amp;&amp;amp; cd cricket-live&lt;br&gt;
npm init -y &amp;amp;&amp;amp; npm i ws express&lt;br&gt;
export ORBISTATS_API_KEY="your_key_here"&lt;/p&gt;

&lt;p&gt;Set "type": "module" in package.json so you can use import.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A resilient API helper&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Every response uses one envelope: data, meta and errors. The helper below retries only the safe errors (500, 502, 503, 504) with exponential backoff and jitter, and never retries a 4xx. See the API reference for the full error list.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// orbistats.js&lt;br&gt;
const BASE = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;br&gt;
const RETRYABLE = new Set([500, 502, 503, 504]);&lt;/p&gt;

&lt;p&gt;export async function api(path, params = {}, { retries = 3 } = {}) {&lt;br&gt;
  const url = new URL(BASE + path);&lt;br&gt;
  for (const [k, v] of Object.entries(params)) {&lt;br&gt;
    if (v != null) url.searchParams.set(k, v);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;for (let attempt = 0; ; attempt++) {&lt;br&gt;
    try {&lt;br&gt;
      const res = await fetch(url, {&lt;br&gt;
        headers: { Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_API_KEY}&lt;/code&gt; },&lt;br&gt;
        signal: AbortSignal.timeout(10_000),&lt;br&gt;
      });&lt;br&gt;
      const body = await res.json();&lt;br&gt;
      if (res.ok) return body;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const err = body.errors?.[0] ?? {};
  if (!RETRYABLE.has(res.status) || attempt &amp;gt;= retries) {
    throw Object.assign(new Error(err.message ?? res.statusText), {
      status: res.status,
      code: err.code,
      requestId: body.meta?.request_id,
    });
  }
} catch (e) {
  if (e.status || attempt &amp;gt;= retries) throw e; // API error, or out of retries
}
const delay = Math.min(8000, 500 * 2 ** attempt) + Math.random() * 250;
await new Promise((r) =&amp;gt; setTimeout(r, delay));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
}&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the competition slugs&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Never guess a league slug. Slugs are case-sensitive and sport-scoped, so list them from /competitions.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// slugs.js&lt;br&gt;
import { api } from "./orbistats.js";&lt;/p&gt;

&lt;p&gt;const { data } = await api("/cricket/competitions", { per_page: 100 });&lt;br&gt;
const wanted = /ipl|ashes|border|test championship|bbl|sa20|ilt20/i;&lt;/p&gt;

&lt;p&gt;for (const c of data.filter((c) =&amp;gt; wanted.test(c.name))) {&lt;br&gt;
  console.log(c.slug.padEnd(28), "→", c.name);&lt;br&gt;
}&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pull fixtures for any window&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Fixtures default to the next 14 days, so pass date_from and date_to for anything further out. This loops through every page.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// fixtures.js&lt;br&gt;
import { api } from "./orbistats.js";&lt;/p&gt;

&lt;p&gt;export async function fixtures(league, dateFrom, dateTo) {&lt;br&gt;
  const out = [];&lt;br&gt;
  for (let page = 1, pages = 1; page &amp;lt;= pages; page++) {&lt;br&gt;
    const { data, meta } = await api("/cricket/fixtures", {&lt;br&gt;
      league, date_from: dateFrom, date_to: dateTo, page, per_page: 100,&lt;br&gt;
    });&lt;br&gt;
    out.push(...data);&lt;br&gt;
    pages = meta.pagination.total_pages;&lt;br&gt;
  }&lt;br&gt;
  return out;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// Example: Border-Gavaskar window, Jan 21 – Mar 3, 2027&lt;br&gt;
const list = await fixtures("YOUR_SLUG", "2027-01-21", "2027-03-03");&lt;br&gt;
for (const f of list) {&lt;br&gt;
  console.log(f.kickoff, "|", f.home_team, "v", f.away_team, "|", f.venue ?? "TBC");&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Keep fixture_id (the fx_… value). It is the key for odds, events, webhooks and WebSocket filters.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A live scoreboard by polling&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Start simple: poll every 5–10 seconds. The Live Scores API returns every match in play with the score, period and latest event. Cricket innings detail appears in score.detail when relevant.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// poll.js&lt;br&gt;
import { api } from "./orbistats.js";&lt;/p&gt;

&lt;p&gt;async function tick() {&lt;br&gt;
  const { data } = await api("/cricket/matches/live");&lt;br&gt;
  console.clear();&lt;br&gt;
  for (const m of data) {&lt;br&gt;
    console.log(&lt;br&gt;
      &lt;code&gt;${m.home_team} v ${m.away_team} | ${JSON.stringify(m.score)} | last: ${m.last_event?.type ?? "-"}&lt;/code&gt;&lt;br&gt;
    );&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
setInterval(() =&amp;gt; tick().catch(console.error), 8000);&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Upgrade to WebSocket&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Polling wastes requests and adds delay. The WebSocket API pushes updates over one connection. Four rules make it production-safe: re-subscribe after every reconnect, treat silence as a dead connection, resync over REST when seq jumps, and back off with jitter.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// stream.js&lt;br&gt;
import WebSocket from "ws";&lt;br&gt;
import { api } from "./orbistats.js";&lt;/p&gt;

&lt;p&gt;const URL = &lt;code&gt;wss://stream.orbistats.com/v1?token=${process.env.ORBISTATS_API_KEY}&lt;/code&gt;;&lt;br&gt;
const board = new Map(); // fixture_id → latest snapshot&lt;br&gt;
let attempt = 0, lastSeq = null, first = true;&lt;/p&gt;

&lt;p&gt;async function resync() {&lt;br&gt;
  const { data } = await api("/cricket/matches/live"); // REST is the source of truth&lt;br&gt;
  board.clear();&lt;br&gt;
  data.forEach((m) =&amp;gt; board.set(m.fixture_id, m));&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function connect() {&lt;br&gt;
  const ws = new WebSocket(URL);&lt;br&gt;
  let watchdog;&lt;br&gt;
  const arm = () =&amp;gt; {&lt;br&gt;
    clearTimeout(watchdog);&lt;br&gt;
    watchdog = setTimeout(() =&amp;gt; ws.terminate(), 45_000); // silent = dead&lt;br&gt;
  };&lt;/p&gt;

&lt;p&gt;ws.on("open", async () =&amp;gt; {&lt;br&gt;
    attempt = 0; lastSeq = null; arm();&lt;br&gt;
    ws.send(JSON.stringify({ subscribe: "cricket.live" })); // always re-subscribe&lt;br&gt;
    if (!first) await resync();                             // fill the gap&lt;br&gt;
    first = false;&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;ws.on("message", async (raw) =&amp;gt; {&lt;br&gt;
    arm();&lt;br&gt;
    let msg;&lt;br&gt;
    try { msg = JSON.parse(raw); } catch { return; }&lt;br&gt;
    if (msg.type === "score_update" || msg.type === "match_event") {&lt;br&gt;
      if (lastSeq !== null &amp;amp;&amp;amp; msg.seq &amp;gt; lastSeq + 1) await resync(); // missed messages&lt;br&gt;
      lastSeq = msg.seq;&lt;br&gt;
      const prev = board.get(msg.data.fixture_id) ?? {};&lt;br&gt;
      board.set(msg.data.fixture_id, { ...prev, ...msg.data });&lt;br&gt;
    }&lt;br&gt;
  });&lt;/p&gt;

&lt;p&gt;ws.on("error", (e) =&amp;gt; console.error("ws error:", e.message));&lt;br&gt;
  ws.on("close", () =&amp;gt; {&lt;br&gt;
    clearTimeout(watchdog);&lt;br&gt;
    const delay = Math.min(30_000, 1000 * 2 ** attempt++) + Math.random() * 1000;&lt;br&gt;
    setTimeout(connect, delay);&lt;br&gt;
  });&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;await resync();&lt;br&gt;
connect();&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add odds&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Odds use the same fixture ID. Pass it as match_id. The endpoint is plan-dependent, so a 403 plan_restricted means your plan does not include it. See the Odds API page and the pricing page.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
const { data: odds } = await api("/cricket/odds", { match_id: "fx_123456" });&lt;br&gt;
for (const q of odds.markets?.["1X2"] ?? []) console.log(q.bookmaker, q);&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Receive full-time results by webhook&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Webhooks remove polling for results. Webhooks are signed with HMAC-SHA256 over {timestamp}.{raw_body}. Verify against the raw body, reject old timestamps, and de-duplicate on the event id.&lt;/p&gt;

&lt;p&gt;javascript&lt;br&gt;
// webhook.js&lt;br&gt;
import express from "express";&lt;br&gt;
import crypto from "node:crypto";&lt;/p&gt;

&lt;p&gt;const app = express();&lt;br&gt;
const SECRET = process.env.ORBISTATS_WEBHOOK_SECRET;&lt;br&gt;
const seen = new Set(); // use Redis or a DB with a TTL in production&lt;/p&gt;

&lt;p&gt;function verify(raw, h) {&lt;br&gt;
  const ts = h["x-orbistats-timestamp"];&lt;br&gt;
  const sig = (h["x-orbistats-signature"] ?? "").replace(/^sha256=/, "");&lt;br&gt;
  if (!ts || !sig || Math.abs(Date.now() / 1000 - Number(ts)) &amp;gt; 300) return false;&lt;br&gt;
  const expected = crypto.createHmac("sha256", SECRET).update(&lt;code&gt;${ts}.${raw}&lt;/code&gt;).digest("hex");&lt;br&gt;
  const a = Buffer.from(sig, "hex"), b = Buffer.from(expected, "hex");&lt;br&gt;
  return a.length === b.length &amp;amp;&amp;amp; crypto.timingSafeEqual(a, b);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;app.post("/webhooks/orbistats", express.raw({ type: "application/json" }), (req, res) =&amp;gt; {&lt;br&gt;
  const raw = req.body.toString("utf8");&lt;br&gt;
  if (!verify(raw, req.headers)) return res.sendStatus(401);&lt;br&gt;
  res.sendStatus(200); // acknowledge fast&lt;/p&gt;

&lt;p&gt;const evt = JSON.parse(raw);&lt;br&gt;
  if (seen.has(evt.id)) return; // retries can repeat events&lt;br&gt;
  seen.add(evt.id);&lt;br&gt;
  if (evt.event === "fixture.finished") {&lt;br&gt;
    console.log("finished:", evt.data.fixture_id, evt.data.final_score);&lt;br&gt;
  }&lt;br&gt;
});&lt;br&gt;
app.listen(3000);&lt;br&gt;
Troubleshooting&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
401 invalid_api_key Header missing the word Bearer  Authorization: Bearer YOUR_API_KEY, no extra quotes&lt;br&gt;
Fixtures come back empty    Default window is 14 days, or off-season    Pass date_from and date_to&lt;br&gt;
404 not_found   Wrong league slug or ID from another sport  Take slugs from /competitions and IDs from fixtures&lt;br&gt;
403 plan_restricted Endpoint not in your plan   Check pricing or drop the call&lt;br&gt;
Webhook returns 401 Parsed JSON before verifying, or wrong secret   Verify against the raw body&lt;br&gt;
Scoreboard freezes  Silent socket drop  Keep the watchdog and resync on reconnect&lt;br&gt;
Which plan for which event?&lt;br&gt;
A single T20I or ODI day: Starter (24 hours).&lt;br&gt;
A five-day Test, such as the WTC Final or an Ashes Test: Growth (5 days).&lt;br&gt;
A month-long league window: Unlimited (30 days).&lt;/p&gt;

&lt;p&gt;Your access timer starts when you open the activation link, so you choose when to go live. Compare plans on the pricing page.&lt;/p&gt;

&lt;p&gt;Where to go next&lt;/p&gt;

&lt;p&gt;You now have fixtures, a live board, odds and settlement. Next, explore the SDKs, read the documentation, watch the status page, and see history for backtesting. Start free at orbistats.com.&lt;/p&gt;

&lt;p&gt;Not betting advice. Dates in the calendar are announced or reported and may change.&lt;/p&gt;

</description>
      <category>api</category>
      <category>cricket</category>
    </item>
    <item>
      <title>Python Odds Converter: Decimal, American &amp; Fractional Odds</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:45:25 +0000</pubDate>
      <link>https://dev.to/orbistats/python-odds-converter-decimal-american-fractional-odds-51h6</link>
      <guid>https://dev.to/orbistats/python-odds-converter-decimal-american-fractional-odds-51h6</guid>
      <description>&lt;p&gt;Build a tested Python odds converter: decimal, American, fractional, implied probability and margin removal, plus live odds from an API. Full code included.&lt;/p&gt;

&lt;p&gt;Odds Converter in Python: Decimal, American, Fractional and Implied Probability&lt;/p&gt;

&lt;p&gt;If you have ever touched betting data, you have hit this wall. One bookmaker shows -110. Another shows 1.91. A third shows 10/11. They are all (almost) the same price written three different ways, and your code has to understand all of them.&lt;/p&gt;

&lt;p&gt;In this guide we will build a small, dependency-free odds converter in Python from scratch. It is the kind of utility you end up needing in every sports-data project, whether you are building a fantasy app, a trading dashboard, a model backtest or just a personal betting tracker.&lt;/p&gt;

&lt;p&gt;By the end you will have:&lt;/p&gt;

&lt;p&gt;Converters between decimal, American and fractional odds&lt;br&gt;
A parser that auto-detects the format from a string&lt;br&gt;
Implied probability calculation&lt;br&gt;
Margin (overround) removal with two methods, proportional and power&lt;br&gt;
A basic expected value helper and a best-price finder&lt;br&gt;
A working example that feeds live odds from an API into the converter&lt;br&gt;
A small pytest suite and a CLI&lt;/p&gt;

&lt;p&gt;Everything uses only the Python standard library, except requests and pytest in the later sections.&lt;/p&gt;

&lt;p&gt;Table of contents&lt;br&gt;
The three odds formats&lt;br&gt;
Implied probability&lt;br&gt;
Conversion functions&lt;br&gt;
Auto-detecting the format&lt;br&gt;
A clean Odds class&lt;br&gt;
The bookmaker margin (overround)&lt;br&gt;
Two ways to remove the margin&lt;br&gt;
Expected value and best price&lt;br&gt;
Getting real odds from an API&lt;br&gt;
Tests&lt;br&gt;
A tiny CLI&lt;br&gt;
Common mistakes&lt;br&gt;
FAQ&lt;br&gt;
Where to go next&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The three odds formats
Format  Example Where you see it
Decimal 2.50    Europe, Australia, Canada, most APIs
American (moneyline)    +150 / -110 United States
Fractional  3/2 UK and Ireland, horse racing&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;All three describe the same idea: how much you get back relative to what you stake.&lt;/p&gt;

&lt;p&gt;Decimal 2.50: a 1 unit stake returns 2.50 in total (1.50 profit plus your 1 stake).&lt;br&gt;
American +150: a 100 stake wins 150 in profit. American -110: you need to stake 110 to win 100.&lt;br&gt;
Fractional 3/2: 3 units of profit for every 2 staked.&lt;/p&gt;

&lt;p&gt;Decimal is the easiest format to calculate with, so we will treat it as the canonical format. Convert everything to decimal first, then convert out to whatever you need.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Implied probability&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Implied probability is the chance that a price suggests:&lt;/p&gt;

&lt;p&gt;implied_probability = 1 / decimal_odds&lt;/p&gt;

&lt;p&gt;So 2.50 implies 1 / 2.50 = 40%. A -110 line (decimal 1.909) implies about 52.4%.&lt;/p&gt;

&lt;p&gt;If you want a plain-English refresher on this and related terms, the Orbistats glossary explains odds, xG and implied probability without jargon.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Conversion functions
python
from &lt;strong&gt;future&lt;/strong&gt; import annotations&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;from fractions import Fraction&lt;/p&gt;

&lt;p&gt;def american_to_decimal(american: int) -&amp;gt; float:&lt;br&gt;
    if -100 &amp;lt; american &amp;lt; 100:&lt;br&gt;
        raise ValueError("American odds must be &amp;lt;= -100 or &amp;gt;= +100")&lt;br&gt;
    if american &amp;gt; 0:&lt;br&gt;
        return 1 + american / 100&lt;br&gt;
    return 1 + 100 / abs(american)&lt;/p&gt;

&lt;p&gt;def decimal_to_american(decimal: float) -&amp;gt; int:&lt;br&gt;
    if decimal &amp;lt;= 1:&lt;br&gt;
        raise ValueError("Decimal odds must be greater than 1.0")&lt;br&gt;
    if decimal &amp;gt;= 2:&lt;br&gt;
        return round((decimal - 1) * 100)&lt;br&gt;
    return round(-100 / (decimal - 1))&lt;/p&gt;

&lt;p&gt;def fractional_to_decimal(fractional: str) -&amp;gt; float:&lt;br&gt;
    text = fractional.strip().lower()&lt;br&gt;
    if text in {"evens", "evs"}:&lt;br&gt;
        return 2.0&lt;br&gt;
    num, den = text.split("/")&lt;br&gt;
    if int(den) == 0:&lt;br&gt;
        raise ValueError("Denominator cannot be zero")&lt;br&gt;
    return 1 + int(num) / int(den)&lt;/p&gt;

&lt;p&gt;def decimal_to_fractional(decimal: float, max_denominator: int = 100) -&amp;gt; str:&lt;br&gt;
    if decimal &amp;lt;= 1:&lt;br&gt;
        raise ValueError("Decimal odds must be greater than 1.0")&lt;br&gt;
    # Going through str() avoids float noise like 1.5000000000000002&lt;br&gt;
    profit = Fraction(str(round(decimal, 4))) - 1&lt;br&gt;
    profit = profit.limit_denominator(max_denominator)&lt;br&gt;
    return f"{profit.numerator}/{profit.denominator}"&lt;/p&gt;

&lt;p&gt;def implied_probability(decimal: float) -&amp;gt; float:&lt;br&gt;
    if decimal &amp;lt;= 1:&lt;br&gt;
        raise ValueError("Decimal odds must be greater than 1.0")&lt;br&gt;
    return 1 / decimal&lt;/p&gt;

&lt;p&gt;A few design notes worth knowing:&lt;/p&gt;

&lt;p&gt;American odds have a built-in gap. Anything strictly between -100 and +100 is not a valid price, so the function rejects it.&lt;br&gt;
The decimal &amp;gt;= 2 branch is where American odds flip sign. Underdogs (decimal 2.00 or higher) are positive, favourites are negative.&lt;br&gt;
Fractions are messy. limit_denominator turns ugly values into bookmaker-style fractions. For example 3.50 becomes 5/2, not 2.5/1.&lt;br&gt;
Everything validates input. Silent bad data is the worst bug in odds code, so we fail loudly.&lt;/p&gt;

&lt;p&gt;Try it in a REPL:&lt;/p&gt;

&lt;p&gt;python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;american_to_decimal(150)&lt;br&gt;
2.5&lt;br&gt;
decimal_to_american(3.40)&lt;br&gt;
240&lt;br&gt;
fractional_to_decimal("5/2")&lt;br&gt;
3.5&lt;br&gt;
decimal_to_fractional(3.5)&lt;br&gt;
'5/2'&lt;br&gt;
round(implied_probability(2.5), 4)&lt;br&gt;
0.4&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Auto-detecting the format&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;Real data rarely tells you which format it is in. This parser guesses from the shape of the string:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def parse_odds(text: str) -&amp;gt; float:&lt;br&gt;
    """Return decimal odds from '+150', '-110', '5/2', 'evens' or '1.91'."""&lt;br&gt;
    t = text.strip().lower()&lt;br&gt;
    if t in {"evens", "evs"} or "/" in t:&lt;br&gt;
        return fractional_to_decimal(t)&lt;br&gt;
    if t.startswith(("+", "-")):&lt;br&gt;
        return american_to_decimal(int(t))&lt;br&gt;
    value = float(t)&lt;br&gt;
    if value &amp;lt;= 1:&lt;br&gt;
        raise ValueError("Decimal odds must be greater than 1.0")&lt;br&gt;
    return value&lt;/p&gt;

&lt;p&gt;The rules are simple. A slash means fractional, a leading + or - means American, and anything else is decimal. One honest limitation: an American price without a sign (for example 150) is ambiguous, so we treat it as decimal and reject it. Always keep the sign on American odds.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A clean Odds class&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Calling five functions gets old quickly. A small frozen dataclass makes the code read naturally:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from dataclasses import dataclass&lt;/p&gt;

&lt;p&gt;@dataclass(frozen=True)&lt;br&gt;
class Odds:&lt;br&gt;
    decimal: float&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __post_init__(self):
    if self.decimal &amp;lt;= 1:
        raise ValueError("Decimal odds must be greater than 1.0")

@classmethod
def parse(cls, text: str) -&amp;gt; "Odds":
    return cls(parse_odds(text))

@classmethod
def from_american(cls, value: int) -&amp;gt; "Odds":
    return cls(american_to_decimal(value))

@classmethod
def from_fractional(cls, value: str) -&amp;gt; "Odds":
    return cls(fractional_to_decimal(value))

@classmethod
def from_probability(cls, p: float) -&amp;gt; "Odds":
    if not 0 &amp;lt; p &amp;lt; 1:
        raise ValueError("Probability must be between 0 and 1 (exclusive)")
    return cls(1 / p)

@property
def american(self) -&amp;gt; int:
    return decimal_to_american(self.decimal)

@property
def fractional(self) -&amp;gt; str:
    return decimal_to_fractional(self.decimal)

@property
def probability(self) -&amp;gt; float:
    return implied_probability(self.decimal)

def __str__(self) -&amp;gt; str:
    sign = "+" if self.american &amp;gt; 0 else ""
    return (
        f"{self.decimal:.2f} | {sign}{self.american} | "
        f"{self.fractional} | {self.probability:.1%}"
    )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now conversions are one-liners:&lt;/p&gt;

&lt;p&gt;python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;print(Odds.parse("+150"))&lt;br&gt;
2.50 | +150 | 3/2 | 40.0%&lt;br&gt;
print(Odds.parse("-110"))&lt;br&gt;
1.91 | -110 | 10/11 | 52.4%&lt;br&gt;
print(Odds.parse("5/2"))&lt;br&gt;
3.50 | +250 | 5/2 | 28.6%&lt;br&gt;
print(Odds.from_probability(0.25))&lt;br&gt;
4.00 | +300 | 3/1 | 25.0%&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice that Odds.parse("1.91") gives 91/100 as the fraction, while Odds.parse("-110") gives 10/11. Both are correct for their input. Bookmaker prices are rounded, so a decimal price and its “equivalent” fraction rarely match exactly.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The bookmaker margin (overround)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here is the part most converters skip. If you add up the implied probabilities of every outcome in a market, you should get 100%. You never do.&lt;/p&gt;

&lt;p&gt;Take a football 1X2 market with these sample prices:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
odds = {"home": 1.91, "draw": 3.40, "away": 4.20}&lt;/p&gt;

&lt;p&gt;The implied probabilities are 52.36%, 29.41% and 23.81%. They add up to 105.58%. That extra 5.58% is the bookmaker’s margin, also called the overround or vig.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def market_overround(decimal_odds: dict[str, float]) -&amp;gt; float:&lt;br&gt;
    """Total implied probability minus 1. 0.0558 means a 5.58% margin."""&lt;br&gt;
    return sum(1 / o for o in decimal_odds.values()) - 1&lt;br&gt;
python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;f"{market_overround(odds):.2%}"&lt;br&gt;
'5.58%'&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;This number is useful by itself. A lower margin means a sharper (better value) price. Comparing overround across bookmakers is one of the quickest ways to see who is pricing most efficiently.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Two ways to remove the margin&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To estimate what the market really thinks, you strip the margin out and get fair probabilities that sum to exactly 100%.&lt;/p&gt;

&lt;p&gt;Method 1: Proportional (the simple default)&lt;/p&gt;

&lt;p&gt;Divide each implied probability by the total:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def fair_probabilities(decimal_odds: dict[str, float]) -&amp;gt; dict[str, float]:&lt;br&gt;
    implied = {k: 1 / o for k, o in decimal_odds.items()}&lt;br&gt;
    total = sum(implied.values())&lt;br&gt;
    return {k: p / total for k, p in implied.items()}&lt;br&gt;
python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;{k: f"{v:.2%}" for k, v in fair_probabilities(odds).items()}&lt;br&gt;
{'home': '49.59%', 'draw': '27.86%', 'away': '22.55%'}&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is easy to explain and good enough for most uses. Its weakness is that it assumes the margin is spread evenly across all outcomes.&lt;/p&gt;

&lt;p&gt;Method 2: Power method (handles longshot bias)&lt;/p&gt;

&lt;p&gt;In practice, bookmakers often load more margin onto longshots. The power method finds an exponent k such that the implied probabilities raised to k sum to 1:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def fair_probabilities_power(decimal_odds: dict[str, float]) -&amp;gt; dict[str, float]:&lt;br&gt;
    implied = {k: 1 / o for k, o in decimal_odds.items()}&lt;br&gt;
    lo, hi = 1.0, 2.0&lt;br&gt;
    while sum(p ** hi for p in implied.values()) &amp;gt; 1:&lt;br&gt;
        hi &lt;em&gt;= 2&lt;br&gt;
    for _ in range(100):&lt;br&gt;
        mid = (lo + hi) / 2&lt;br&gt;
        if sum(p *&lt;/em&gt; mid for p in implied.values()) &amp;gt; 1:&lt;br&gt;
            lo = mid&lt;br&gt;
        else:&lt;br&gt;
            hi = mid&lt;br&gt;
    k = (lo + hi) / 2&lt;br&gt;
    return {name: p ** k for name, p in implied.items()}&lt;br&gt;
python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;{k: f"{v:.2%}" for k, v in fair_probabilities_power(odds).items()}&lt;br&gt;
{'home': '50.52%', 'draw': '27.49%', 'away': '21.99%'}&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;Compare the two. The power method gives the favourite a slightly higher fair probability (50.52% vs 49.59%) and the longshot a lower one (21.99% vs 22.55%). That is the favourite-longshot bias showing up in the numbers. Neither method is “the truth”, but knowing both makes your models more honest.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Expected value and best price&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once you have a fair probability, you can ask whether a price is worth taking. Expected value (EV) per unit staked is:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def expected_value(decimal: float, true_probability: float, stake: float = 1.0) -&amp;gt; float:&lt;br&gt;
    return stake * (true_probability * decimal - 1)&lt;br&gt;
python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;expected_value(2.10, 0.50)        # 1 unit stake&lt;br&gt;
0.05000000000000004&lt;br&gt;
expected_value(2.10, 0.50, 50)    # 50 unit stake&lt;br&gt;
2.500000000000002&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you believe an outcome is 50% likely and a bookmaker offers 2.10, you expect to make 0.05 per unit staked over the long run. The hard part is the “if you believe”, which is where fair probabilities and good historical data come in.&lt;/p&gt;

&lt;p&gt;When you have the same market from several bookmakers, picking the best price is one line:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def best_price(quotes: dict[str, float]) -&amp;gt; tuple[str, float]:&lt;br&gt;
    book = max(quotes, key=quotes.get)&lt;br&gt;
    return book, quotes[book]&lt;br&gt;
python&lt;/p&gt;

&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;best_price({"BookA": 1.95, "BookB": 2.02, "BookC": 1.98})&lt;br&gt;
('BookB', 2.02)&lt;/p&gt;
&lt;/blockquote&gt;


&lt;/blockquote&gt;
&lt;br&gt;
&lt;/blockquote&gt;

&lt;p&gt;Line shopping like this is one of the most reliable edges in betting maths, and it only works if every price is in the same format. That is exactly why a normalised feed matters.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Getting real odds from an API&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Typing prices by hand is fine for learning. Real projects pull odds from a data provider, and then every one of the problems above shows up at scale: different formats, different markets, different margins.&lt;/p&gt;

&lt;p&gt;This is where a normalised sports odds API earns its keep. The Orbistats Odds API delivers pre-match and live odds normalised across bookmakers, so you do not maintain one parser per source. If you want the deeper background, the sports odds API guide covers live, historical and normalised odds in detail.&lt;/p&gt;

&lt;p&gt;Getting started follows four steps: request access, open the activation link, grab your API key and make your first request. The quickstart walks through it, the documentation explains authentication and the base URL, and the API reference lists endpoints, parameters and response fields. You can also try requests in the sandbox before writing any code.&lt;/p&gt;

&lt;p&gt;Authentication is a bearer token. Here is the pattern. The endpoint path and parameters below are placeholders, so copy the real ones from the API reference:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import requests&lt;/p&gt;

&lt;p&gt;API_KEY = "YOUR_API_KEY"&lt;br&gt;
BASE_URL = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;"&lt;br&gt;
headers = {"Authorization": f"Bearer {API_KEY}"}&lt;/p&gt;

&lt;h1&gt;
  
  
  Replace with the real odds endpoint and parameters from the API reference
&lt;/h1&gt;

&lt;p&gt;resp = requests.get(f"{BASE_URL}/odds", headers=headers, params={}, timeout=10)&lt;br&gt;
resp.raise_for_status()&lt;br&gt;
payload = resp.json()&lt;/p&gt;

&lt;p&gt;Because payload shapes can differ, wrap the extraction in a small function so the rest of your code never depends on the raw structure. This version assumes a 1X2 market shaped like the sample below, so adjust it to the real response:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
def extract_1x2(market: dict) -&amp;gt; dict[str, float]:&lt;br&gt;
    """Expecting: {"market": "1X2", "odds": {"home": 1.91, "draw": 3.40, "away": 4.20}}"""&lt;br&gt;
    prices = market["odds"]&lt;br&gt;
    return {side: float(prices[side]) for side in ("home", "draw", "away")}&lt;/p&gt;

&lt;p&gt;market = {"market": "1X2", "odds": {"home": 1.91, "draw": 3.40, "away": 4.20}}&lt;br&gt;
prices = extract_1x2(market)&lt;/p&gt;

&lt;p&gt;for side, price in prices.items():&lt;br&gt;
    print(f"{side:&amp;gt;5}: {Odds(price)}")&lt;/p&gt;

&lt;p&gt;print(f"Margin: {market_overround(prices):.2%}")&lt;br&gt;
print("Fair (proportional):", {k: round(v, 4) for k, v in fair_probabilities(prices).items()})&lt;/p&gt;

&lt;p&gt;The numbers in these examples are sample prices for illustration, not live odds.&lt;/p&gt;

&lt;p&gt;It is not just football&lt;/p&gt;

&lt;p&gt;Odds maths is identical across sports, only the markets change. Orbistats covers 13 sports behind one API, so the same converter works everywhere:&lt;/p&gt;

&lt;p&gt;Football for 1X2, handicaps and totals&lt;br&gt;
Cricket for match winner and innings markets&lt;br&gt;
Tennis for two-way moneyline-style prices&lt;/p&gt;

&lt;p&gt;Two-way markets like tennis are the simplest case for margin removal. With two outcomes at 1.91 each, the overround is about 4.71% and both fair probabilities come out at exactly 50%.&lt;/p&gt;

&lt;p&gt;Backtesting your converter on history&lt;/p&gt;

&lt;p&gt;A converter is only as good as the data you test it on. If you want to check how fair probabilities compare with real results over many seasons, you need historical odds, ideally including closing prices. The Historical Sports Data API is built for that kind of backtesting, and this step-by-step article on how to backtest a sports betting model with historical odds data shows the full workflow. Removing the margin from closing odds is a classic way to build a strong baseline probability model.&lt;/p&gt;

&lt;p&gt;Pricing note&lt;/p&gt;

&lt;p&gt;Access is based on time windows rather than monthly seats. As listed on the pricing page, there is a Free plan (1 hour, no card), Starter at €19 for 24 hours, Growth at €79 for 5 days and an Unlimited monthly plan. Every plan includes all sports and endpoints. Check the page for current details, since plans can change.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Tests&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Odds maths is exactly the kind of code that breaks silently, so write tests. Save the code above as odds.py and create test_odds.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import pytest&lt;br&gt;
from odds import (&lt;br&gt;
    Odds,&lt;br&gt;
    american_to_decimal,&lt;br&gt;
    decimal_to_american,&lt;br&gt;
    decimal_to_fractional,&lt;br&gt;
    fair_probabilities,&lt;br&gt;
    fair_probabilities_power,&lt;br&gt;
    fractional_to_decimal,&lt;br&gt;
    parse_odds,&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;def test_american_round_trip():&lt;br&gt;
    for value in (-300, -110, 100, 150, 500):&lt;br&gt;
        assert decimal_to_american(american_to_decimal(value)) == value&lt;/p&gt;

&lt;p&gt;def test_fractional_round_trip():&lt;br&gt;
    for value in ("1/2", "5/2", "10/11", "11/4"):&lt;br&gt;
        assert decimal_to_fractional(fractional_to_decimal(value)) == value&lt;/p&gt;

&lt;p&gt;def test_evens():&lt;br&gt;
    assert fractional_to_decimal("evens") == 2.0&lt;br&gt;
    assert decimal_to_american(2.0) == 100&lt;/p&gt;

&lt;p&gt;def test_parse_detects_formats():&lt;br&gt;
    assert parse_odds("+150") == pytest.approx(2.5)&lt;br&gt;
    assert parse_odds("5/2") == pytest.approx(3.5)&lt;br&gt;
    assert parse_odds("1.91") == pytest.approx(1.91)&lt;/p&gt;

&lt;p&gt;def test_probability_round_trip():&lt;br&gt;
    assert Odds.from_probability(0.4).decimal == pytest.approx(2.5)&lt;/p&gt;

&lt;p&gt;@pytest.mark.parametrize("method", [fair_probabilities, fair_probabilities_power])&lt;br&gt;
def test_fair_probabilities_sum_to_one(method):&lt;br&gt;
    fair = method({"home": 1.91, "draw": 3.40, "away": 4.20})&lt;br&gt;
    assert sum(fair.values()) == pytest.approx(1.0)&lt;/p&gt;

&lt;p&gt;@pytest.mark.parametrize("bad", [0, 50, -50])&lt;br&gt;
def test_invalid_american(bad):&lt;br&gt;
    with pytest.raises(ValueError):&lt;br&gt;
        american_to_decimal(bad)&lt;/p&gt;

&lt;p&gt;def test_invalid_decimal():&lt;br&gt;
    with pytest.raises(ValueError):&lt;br&gt;
        Odds(1.0)&lt;/p&gt;

&lt;p&gt;Run it with:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
pip install pytest&lt;br&gt;
pytest -q&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A tiny CLI&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Add this to the bottom of odds.py to convert from the terminal:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    import sys&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for arg in sys.argv[1:]:
    print(f"{arg:&amp;gt;8}  -&amp;gt;  {Odds.parse(arg)}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;bash&lt;br&gt;
$ python odds.py +150 -110 5/2 1.91 evens&lt;br&gt;
    +150  -&amp;gt;  2.50 | +150 | 3/2 | 40.0%&lt;br&gt;
    -110  -&amp;gt;  1.91 | -110 | 10/11 | 52.4%&lt;br&gt;
     5/2  -&amp;gt;  3.50 | +250 | 5/2 | 28.6%&lt;br&gt;
    1.91  -&amp;gt;  1.91 | -110 | 91/100 | 52.4%&lt;br&gt;
   evens  -&amp;gt;  2.00 | +100 | 1/1 | 50.0%&lt;/p&gt;

&lt;p&gt;If you prefer a no-code option for quick checks, Orbistats also publishes odds converters and quick calculators you can use in the browser.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Common mistakes
Treating implied probability as true probability. It includes the bookmaker’s margin. Use fair probabilities when you want the market’s real view.
Expecting perfect round trips. Rounding to whole American numbers or simple fractions loses a little precision. Treat conversions as approximate and keep decimal as your source of truth.
Mixing up favourites and underdogs in American odds. Negative means favourite and positive means underdog, and the flip happens at decimal 2.00.
Floating point surprises. Comparing floats with == will bite you. Use pytest.approx in tests and math.isclose in code.
Ignoring sign on American odds. 150 and +150 are not the same thing to a parser. Keep the sign.
Removing margin from the wrong market. Only normalise a complete market where outcomes are mutually exclusive and cover every possibility, like 1X2 or a two-way moneyline.&lt;/li&gt;
&lt;li&gt;FAQ&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;How do you convert American odds to decimal?&lt;br&gt;
For positive odds, divide by 100 and add 1. For negative odds, divide 100 by the absolute value and add 1. So +150 is 2.50 and -110 is about 1.91.&lt;/p&gt;

&lt;p&gt;How do you calculate implied probability from odds?&lt;br&gt;
Divide 1 by the decimal odds. 2.50 gives 0.40, or 40%.&lt;/p&gt;

&lt;p&gt;What is the overround?&lt;br&gt;
It is how much the implied probabilities of all outcomes exceed 100%. It is the bookmaker’s built-in margin.&lt;/p&gt;

&lt;p&gt;Which margin removal method should I use?&lt;br&gt;
Start with proportional because it is simple and transparent. Move to the power method (or Shin’s method) if you care about longshot bias.&lt;/p&gt;

&lt;p&gt;Can I use this with live odds?&lt;br&gt;
Yes. The maths is the same. Live prices just change faster, so pair the converter with a streaming source. Orbistats supports WebSocket delivery for live feeds so you avoid constant polling.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Where to go next&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You now have a solid, tested foundation. Natural next steps:&lt;/p&gt;

&lt;p&gt;Wrap the converter in a Streamlit or FastAPI app&lt;br&gt;
Compare margins across bookmakers and rank them&lt;br&gt;
Build an expected value finder that flags prices above your fair probability&lt;br&gt;
Add historical backtests to see whether your fair probabilities actually beat closing lines&lt;br&gt;
Start with the developer hub to explore everything the API offers&lt;/p&gt;

&lt;p&gt;If you are comparing providers before you build, the Orbistats blog also has a buyer’s guide on how to choose a sports data API.&lt;/p&gt;

&lt;p&gt;If this was useful, leave a comment with the odds format you run into most, and I will add more conversions and examples. Happy coding.&lt;/p&gt;

&lt;p&gt;Disclosure: I am affiliated with Orbistats. All odds shown in code examples are sample prices for illustration.&lt;/p&gt;

</description>
      <category>python</category>
      <category>tutorial</category>
      <category>api</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Build an Odds Comparison Dashboard with Python and Streamlit</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:37:31 +0000</pubDate>
      <link>https://dev.to/orbistats/build-an-odds-comparison-dashboard-with-python-and-streamlit-1kaj</link>
      <guid>https://dev.to/orbistats/build-an-odds-comparison-dashboard-with-python-and-streamlit-1kaj</guid>
      <description>&lt;p&gt;An odds comparison page answers one question: where is the best price right now? Building one is mostly plumbing: fetch odds, reshape them into a table, highlight the winners, and keep it fresh without hammering the API.&lt;/p&gt;

&lt;p&gt;In this tutorial we build a Streamlit dashboard that compares bookmaker odds for a match, highlights the best price per outcome, shows each bookmaker’s margin and the market’s fair probabilities, and charts line movement over time. Because Streamlit runs your Python on the server, your API key never reaches the browser, and you can build the whole thing in mock mode with no API key.&lt;/p&gt;

&lt;p&gt;Disclosure: I work on Orbistats, the data source used here. The structure works with any odds API once you adapt one function.&lt;/p&gt;

&lt;p&gt;What we are building&lt;br&gt;
A comparison table: bookmakers as rows, outcomes as columns, best price highlighted.&lt;br&gt;
Metric cards: best price per outcome and which bookmaker offers it.&lt;br&gt;
Margin and fair probability: each bookmaker’s built-in margin, plus de-vigged probabilities.&lt;br&gt;
A line-movement chart of the best price over time.&lt;br&gt;
Auto-refresh and caching, so ten viewers cost one upstream call.&lt;br&gt;
Mock mode, so the UI works before you have a key.&lt;br&gt;
Prerequisites&lt;br&gt;
Python 3.10+ and a terminal.&lt;br&gt;
Basic pandas. We use pivot_table and a little styling.&lt;br&gt;
An Orbistats key is optional until the last step. You can look at real JSON in the sandbox first. Odds terms are explained in the glossary.&lt;br&gt;
Step 1: Project setup&lt;br&gt;
bash&lt;br&gt;
mkdir odds-dashboard &amp;amp;&amp;amp; cd odds-dashboard&lt;br&gt;
python -m venv .venv &amp;amp;&amp;amp; source .venv/bin/activate   # Windows: .venv\Scripts\activate&lt;/p&gt;

&lt;p&gt;requirements.txt:&lt;/p&gt;

&lt;p&gt;text&lt;br&gt;
streamlit&amp;gt;=1.37&lt;br&gt;
pandas&lt;br&gt;
requests&lt;br&gt;
python-dotenv&lt;br&gt;
pytest&lt;br&gt;
bash&lt;br&gt;
pip install -r requirements.txt&lt;/p&gt;

&lt;p&gt;.env (add it to .gitignore):&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
USE_MOCK=1&lt;br&gt;
ORBISTATS_API_KEY=your_key_here&lt;br&gt;
ORBISTATS_BASE=&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;streamlit&amp;gt;=1.37 matters because we use st.fragment with auto-refresh, which arrived in that version.&lt;/p&gt;

&lt;p&gt;Step 2: The odds math (small, pure, testable)&lt;/p&gt;

&lt;p&gt;Keep the maths separate from the UI so you can test it without opening a browser. Create odds_math.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
OUTCOME_ORDER = ["home", "draw", "away"]&lt;/p&gt;

&lt;p&gt;def margin(odds: list[float]) -&amp;gt; float:&lt;br&gt;
    """Bookmaker margin (overround): sum of implied probabilities minus 1."""&lt;br&gt;
    return sum(1 / o for o in odds) - 1&lt;/p&gt;

&lt;p&gt;def devig(odds: dict[str, float]) -&amp;gt; dict[str, float]:&lt;br&gt;
    """Remove the margin proportionally to get 'fair' probabilities."""&lt;br&gt;
    total = sum(1 / o for o in odds.values())&lt;br&gt;
    return {k: (1 / o) / total for k, o in odds.items()}&lt;/p&gt;

&lt;p&gt;Quick sanity check with the example odds from the Orbistats docs, home 1.91, draw 3.40, away 4.20:&lt;/p&gt;

&lt;p&gt;Implied probabilities: 52.4%, 29.4%, 23.8%&lt;br&gt;
They sum to about 105.6%, so the margin is about 5.6%.&lt;/p&gt;

&lt;p&gt;Add test_odds_math.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from odds_math import devig, margin&lt;/p&gt;

&lt;p&gt;def test_margin():&lt;br&gt;
    assert round(margin([1.91, 3.40, 4.20]), 4) == 0.0558&lt;/p&gt;

&lt;p&gt;def test_devig_sums_to_one():&lt;br&gt;
    fair = devig({"home": 1.91, "draw": 3.40, "away": 4.20})&lt;br&gt;
    assert abs(sum(fair.values()) - 1) &amp;lt; 1e-9&lt;br&gt;
bash&lt;br&gt;
pytest -q&lt;br&gt;
Step 3: The data layer (real API and mock in one place)&lt;/p&gt;

&lt;p&gt;Only this file knows what the API looks like. The endpoint pattern follows the odds reference (GET /v1/{sport}/odds?match_id=...&amp;amp;market=1x2) and the fixtures pattern (/v1/{sport}/fixtures?date=today). The response shapes inside normalize_* are assumptions: adjust them to the real payload in the API reference.&lt;/p&gt;

&lt;p&gt;Create source.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import os&lt;br&gt;
import random&lt;/p&gt;

&lt;p&gt;import requests&lt;br&gt;
import streamlit as st&lt;br&gt;
from dotenv import load_dotenv&lt;/p&gt;

&lt;p&gt;load_dotenv()&lt;/p&gt;

&lt;p&gt;BASE = os.getenv("ORBISTATS_BASE", "&lt;a href="https://api.orbistats.com/v1%22" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1"&lt;/a&gt;)&lt;br&gt;
KEY = os.getenv("ORBISTATS_API_KEY")&lt;br&gt;
USE_MOCK = os.getenv("USE_MOCK") == "1" or not KEY&lt;/p&gt;

&lt;p&gt;SPORTS = ["football", "basketball", "american-football", "cricket", "tennis",&lt;br&gt;
          "baseball", "esports", "combat-sports", "volleyball", "handball",&lt;br&gt;
          "ice-hockey", "golf", "horse-racing"]&lt;/p&gt;

&lt;h1&gt;
  
  
  ---------- real API (cached so many viewers share one upstream call) ----------
&lt;/h1&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/st"&gt;@st&lt;/a&gt;.cache_data(ttl=15, show_spinner=False)&lt;br&gt;
def _get(path: str, params: tuple = ()):&lt;br&gt;
    r = requests.get(&lt;br&gt;
        f"{BASE}{path}",&lt;br&gt;
        headers={"Authorization": f"Bearer {KEY}"},&lt;br&gt;
        params=dict(params),&lt;br&gt;
        timeout=10,&lt;br&gt;
    )&lt;br&gt;
    r.raise_for_status()&lt;br&gt;
    return r.json()&lt;/p&gt;

&lt;p&gt;def normalize_fixtures(raw) -&amp;gt; list[dict]:&lt;br&gt;
    items = raw if isinstance(raw, list) else raw.get("data", [])&lt;br&gt;
    out = []&lt;br&gt;
    for m in items:&lt;br&gt;
        match_id = m.get("match_id") or m.get("id")&lt;br&gt;
        home, away = m.get("home") or {}, m.get("away") or {}&lt;br&gt;
        label = (f"{home.get('name')} vs {away.get('name')}"&lt;br&gt;
                 if home and away else m.get("name", str(match_id)))&lt;br&gt;
        if match_id:&lt;br&gt;
            out.append({"match_id": str(match_id), "label": label})&lt;br&gt;
    return out&lt;/p&gt;

&lt;p&gt;def normalize_odds(raw) -&amp;gt; list[dict]:&lt;br&gt;
    """Return rows of {bookmaker, outcome, odds}.&lt;br&gt;
    ASSUMPTION: a list of {bookmaker, odds: {home, draw, away}}; adjust to the docs."""&lt;br&gt;
    items = raw if isinstance(raw, list) else raw.get("data", [raw])&lt;br&gt;
    rows = []&lt;br&gt;
    for it in items:&lt;br&gt;
        book = it.get("bookmaker") or it.get("book") or "feed"&lt;br&gt;
        if isinstance(book, dict):&lt;br&gt;
            book = book.get("name", "feed")&lt;br&gt;
        for outcome, price in (it.get("odds") or {}).items():&lt;br&gt;
            try:&lt;br&gt;
                price = float(price)&lt;br&gt;
            except (TypeError, ValueError):&lt;br&gt;
                continue&lt;br&gt;
            if price &amp;gt; 1.0:&lt;br&gt;
                rows.append({"bookmaker": str(book), "outcome": str(outcome).lower(), "odds": price})&lt;br&gt;
    return rows&lt;/p&gt;

&lt;h1&gt;
  
  
  ---------- mock data (a random walk, so the charts move) ----------
&lt;/h1&gt;

&lt;p&gt;_BOOKS = ["Book A", "Book B", "Book C", "Book D", "Book E"]&lt;br&gt;
_BASE = {"home": 1.91, "draw": 3.40, "away": 4.20}&lt;br&gt;
_state: dict = {}&lt;/p&gt;

&lt;p&gt;_MOCK_FIXTURES = [&lt;br&gt;
    {"match_id": "mock_1", "label": "Blue Rovers vs Red City"},&lt;br&gt;
    {"match_id": "mock_2", "label": "Northside FC vs Harbor United"},&lt;br&gt;
]&lt;/p&gt;

&lt;p&gt;def _mock_odds(match_id: str) -&amp;gt; list[dict]:&lt;br&gt;
    rows = []&lt;br&gt;
    for book in _BOOKS:&lt;br&gt;
        cur = _state.setdefault(&lt;br&gt;
            (match_id, book),&lt;br&gt;
            {k: v * random.uniform(0.97, 1.03) for k, v in _BASE.items()},&lt;br&gt;
        )&lt;br&gt;
        for outcome in cur:&lt;br&gt;
            cur[outcome] = max(1.05, round(cur[outcome] * random.uniform(0.99, 1.01), 2))&lt;br&gt;
            rows.append({"bookmaker": book, "outcome": outcome, "odds": cur[outcome]})&lt;br&gt;
    return rows&lt;/p&gt;

&lt;h1&gt;
  
  
  ---------- public functions the app uses ----------
&lt;/h1&gt;

&lt;p&gt;def get_fixtures(sport: str) -&amp;gt; list[dict]:&lt;br&gt;
    if USE_MOCK:&lt;br&gt;
        return _MOCK_FIXTURES&lt;br&gt;
    return normalize_fixtures(_get(f"/{sport}/fixtures", (("date", "today"),)))&lt;/p&gt;

&lt;p&gt;def get_odds(sport: str, match_id: str, market: str) -&amp;gt; list[dict]:&lt;br&gt;
    if USE_MOCK:&lt;br&gt;
        return _mock_odds(match_id)&lt;br&gt;
    raw = _get(f"/{sport}/odds", (("match_id", match_id), ("market", market)))&lt;br&gt;
    return normalize_odds(raw)&lt;/p&gt;

&lt;p&gt;Three things worth noticing:&lt;/p&gt;

&lt;p&gt;st.cache_data(ttl=15) is your quota shield. However many people open the dashboard, the same match and market cost at most one upstream call every 15 seconds, which is about 4 a minute.&lt;br&gt;
Params are passed as a tuple so Streamlit can hash them for the cache key.&lt;br&gt;
Mock bookmakers are generic names (“Book A”), so the demo never implies real prices from real companies.&lt;br&gt;
Step 4: The dashboard&lt;/p&gt;

&lt;p&gt;Create app.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import pandas as pd&lt;br&gt;
import requests&lt;br&gt;
import streamlit as st&lt;/p&gt;

&lt;p&gt;from odds_math import OUTCOME_ORDER, devig, margin&lt;br&gt;
from source import SPORTS, USE_MOCK, get_fixtures, get_odds&lt;/p&gt;

&lt;p&gt;st.set_page_config(page_title="Odds Comparison", page_icon="📊", layout="wide")&lt;br&gt;
st.title("📊 Odds Comparison Dashboard")&lt;/p&gt;

&lt;p&gt;if USE_MOCK:&lt;br&gt;
    st.info("Mock mode: simulated odds. Set ORBISTATS_API_KEY in .env (and USE_MOCK=0) for real data.")&lt;/p&gt;

&lt;p&gt;def highlight_best(col: pd.Series):&lt;br&gt;
    best = col.max()&lt;br&gt;
    return ["background-color: rgba(34,197,94,.35); font-weight: 700" if v == best else ""&lt;br&gt;
            for v in col]&lt;/p&gt;

&lt;p&gt;def board(sport: str, match_id: str, market: str):&lt;br&gt;
    try:&lt;br&gt;
        rows = get_odds(sport, match_id, market)&lt;br&gt;
    except requests.RequestException as e:&lt;br&gt;
        st.error(f"API error: {e}")&lt;br&gt;
        return&lt;br&gt;
    if not rows:&lt;br&gt;
        st.warning("No odds returned for this match and market yet.")&lt;br&gt;
        return&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 1) bookmakers x outcomes table&lt;br&gt;
df = pd.DataFrame(rows)&lt;br&gt;
table = df.pivot_table(index="bookmaker", columns="outcome", values="odds", aggfunc="max")&lt;br&gt;
ordered = [c for c in OUTCOME_ORDER if c in table.columns]&lt;br&gt;
odds_cols = ordered + [c for c in table.columns if c not in ordered]&lt;br&gt;
table = table[odds_cols]
&lt;h1&gt;
  
  
  2) margin per bookmaker (only where every outcome is present)
&lt;/h1&gt;

&lt;p&gt;complete = table.dropna()&lt;br&gt;
table["margin %"] = (complete.apply(lambda r: margin(r.tolist()), axis=1) * 100)&lt;/p&gt;
&lt;h1&gt;
  
  
  3) best price per outcome
&lt;/h1&gt;

&lt;p&gt;best = table[odds_cols].max()&lt;br&gt;
best_book = table[odds_cols].idxmax()&lt;/p&gt;

&lt;p&gt;cols = st.columns(len(odds_cols) + 1)&lt;br&gt;
for c, name in zip(cols, odds_cols):&lt;br&gt;
    c.metric(f"Best {name}", f"{best[name]:.2f}")&lt;br&gt;
    c.caption(f"at {best_book[name]}")&lt;br&gt;
cols[-1].metric(&lt;br&gt;
    "Best-price margin", f"{margin(best.tolist()) * 100:.2f}%",&lt;br&gt;
    help="Below 0% usually means stale or mismatched prices, not free money.",&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;st.dataframe(&lt;br&gt;
    table.style.apply(highlight_best, subset=odds_cols)&lt;br&gt;
    .format("{:.2f}", subset=odds_cols, na_rep="–")&lt;br&gt;
    .format("{:.2f}%", subset=["margin %"], na_rep="–")&lt;br&gt;
)&lt;/p&gt;
&lt;h1&gt;
  
  
  4) fair probabilities (margin removed), averaged across bookmakers
&lt;/h1&gt;

&lt;p&gt;if len(complete):&lt;br&gt;
    fair = pd.DataFrame([devig(r.to_dict()) for _, r in complete.iterrows()],&lt;br&gt;
                        index=complete.index)&lt;br&gt;
    st.subheader("Fair probability (margin removed)")&lt;br&gt;
    st.bar_chart((fair.mean() * 100).round(1))&lt;/p&gt;
&lt;h1&gt;
  
  
  5) line movement of the best price
&lt;/h1&gt;

&lt;p&gt;key = (sport, match_id, market)&lt;br&gt;
history = st.session_state.setdefault("history", [])&lt;br&gt;
history.append({"key": key, "ts": pd.Timestamp.now(), **{o: float(best[o]) for o in odds_cols}})&lt;br&gt;
del history[:-300]  # keep memory bounded&lt;br&gt;
mine = [h for h in history if h["key"] == key]&lt;br&gt;
if len(mine) &amp;gt; 1:&lt;br&gt;
    st.subheader("Best price over time")&lt;br&gt;
    st.line_chart(pd.DataFrame(mine).set_index("ts")[odds_cols])&lt;/p&gt;

&lt;p&gt;st.caption(f"Updated {pd.Timestamp.now():%H:%M:%S}")&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h1&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  ---------- sidebar controls ----------&lt;br&gt;
&lt;/h1&gt;

&lt;p&gt;with st.sidebar:&lt;br&gt;
    sport = st.selectbox("Sport", SPORTS, format_func=lambda s: s.replace("-", " ").title())&lt;br&gt;
    market = st.text_input("Market", value="1x2",&lt;br&gt;
                           help="Check the supported markets in the Odds API docs.")&lt;br&gt;
    refresh = st.select_slider("Auto-refresh (seconds)", options=[10, 20, 30, 60], value=30)&lt;/p&gt;

&lt;p&gt;try:&lt;br&gt;
    fixtures = get_fixtures(sport)&lt;br&gt;
except requests.RequestException as e:&lt;br&gt;
    st.error(f"Could not load fixtures: {e}")&lt;br&gt;
    st.stop()&lt;/p&gt;

&lt;p&gt;if not fixtures:&lt;br&gt;
    st.warning("No fixtures found for today.")&lt;br&gt;
    st.stop()&lt;/p&gt;

&lt;p&gt;options = {f["label"]: f["match_id"] for f in fixtures}&lt;br&gt;
label = st.sidebar.selectbox("Match", list(options))&lt;br&gt;
match_id = options[label]&lt;/p&gt;

&lt;p&gt;st.subheader(label)&lt;br&gt;
st.fragment(run_every=refresh)(board)(sport, match_id, market)&lt;/p&gt;

&lt;p&gt;Run it:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
streamlit run app.py&lt;/p&gt;

&lt;p&gt;You should see a table of five mock bookmakers, a green highlight on the best price in each column, margin values around 3 to 8 percent, a fair-probability bar chart, and a line chart that starts moving after the second refresh.&lt;/p&gt;

&lt;p&gt;How it works (the parts worth understanding)&lt;/p&gt;

&lt;p&gt;st.fragment(run_every=...) refreshes only the odds board. Your sidebar selections stay put, and the rest of the page does not rerun every 30 seconds.&lt;/p&gt;

&lt;p&gt;pivot_table(..., aggfunc="max") guards against a bookmaker listing the same outcome twice by keeping the higher price.&lt;/p&gt;

&lt;p&gt;The best-price margin is a data-quality signal, not a strategy. If the best prices across bookmakers sum to less than 100%, the dashboard shows a negative margin. In practice that nearly always means stale odds, different lines or mismatched markets. Real prices at that level disappear fast and often cannot be taken at the shown stake.&lt;/p&gt;

&lt;p&gt;Fair probability is an estimate. Proportional de-vigging is the simplest method. It is fine for a dashboard, but it is not a prediction and not betting advice.&lt;/p&gt;

&lt;p&gt;Step 5: Switch to real data&lt;br&gt;
Get access. Request access. Your plan’s access time starts when you open the activation link, so do this only when the UI is ready.&lt;br&gt;
Confirm the endpoints and payload in the API reference and the Odds API page. Adjust normalize_fixtures and normalize_odds if the field names differ.&lt;br&gt;
Edit .env: set USE_MOCK=0 and paste your key.&lt;br&gt;
Run streamlit run app.py again.&lt;/p&gt;

&lt;p&gt;The Odds API covers pre-match and live odds normalized across bookmakers, so you do not write a parser per bookmaker. Fixtures come from the Sports Data API. Check supported markets for your sport in the documentation before changing the Market box.&lt;/p&gt;

&lt;p&gt;Common problems&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
“No odds returned”  Wrong market value, or match_id from a different sport  Take the market name from the docs and pick the match from the same sport’s fixtures&lt;br&gt;
Only one row called “feed”  The payload has no per-bookmaker list in the shape you assumed  Print the raw JSON and adjust normalize_odds&lt;br&gt;
Empty or odd columns    Outcome names differ (for example 1, x, 2)  Map them to home, draw, away inside normalize_odds&lt;br&gt;
401 error   Key missing, or .env not loaded Check ORBISTATS_API_KEY, and that load_dotenv() runs in source.py&lt;br&gt;
429 error   Too many refreshes or many sessions Increase the refresh interval or the cache ttl&lt;br&gt;
Best-price margin is negative   Stale, mismatched or different-line odds    Treat it as a data-quality flag, and compare timestamps if the API provides them&lt;br&gt;
Line chart restarts when you change match   History is keyed by sport, match and market That is intended, so each selection keeps its own series&lt;br&gt;
App feels slow  Network calls made outside the cache    Keep every API call inside _get, which is cached&lt;br&gt;
Nothing is highlighted  Only one bookmaker, or all values tied  Add more sources, since ties highlight every tied cell by design&lt;br&gt;
Deploying it&lt;br&gt;
Streamlit Community Cloud is the quickest option. Push the repo to GitHub, add your key under the app’s secrets, and confirm that ORBISTATS_API_KEY is visible to the app as an environment variable.&lt;br&gt;
Any small server or container also works: streamlit run app.py --server.port 8501.&lt;br&gt;
Protect your quota. A public Streamlit app lets anyone use your API key indirectly. The cache helps, but also consider a login or a password gate, and keep refresh intervals generous.&lt;br&gt;
Read the licence before displaying odds publicly or commercially: data licensing. Odds data is for comparison and analysis, and betting rules differ by country.&lt;br&gt;
Where to go next&lt;br&gt;
Convert formats: add decimal, American and fractional views with the helpers from Odds Converter in JS &amp;amp; Python, and use the odds tools page to sanity-check your results.&lt;br&gt;
Go further with maths: see Build a +EV Bet Finder in Python for edge and stake sizing.&lt;br&gt;
Stream instead of poll: the WebSocket API suits live odds, and Building a Sports Betting Dashboard with Next.js shows a relay pattern.&lt;br&gt;
Keep history: save snapshots to SQLite and backfill with the Historical Sports Data API for real line-movement charts.&lt;br&gt;
Add markets: one tab each for totals and handicaps, once you have confirmed them in the docs.&lt;br&gt;
Check the basics: pricing is on the pricing page.&lt;br&gt;
Wrap-up&lt;/p&gt;

&lt;p&gt;You built a dashboard that normalizes bookmaker odds into one table, highlights the best price, exposes each bookmaker’s margin, estimates fair probabilities and tracks movement, with a cache that protects your quota and a mock mode that lets you build before you pay for anything.&lt;/p&gt;

&lt;p&gt;If you want to see it on real odds, request the free hour and run Step 5. Which tab should come next: totals and handicaps, or a saved line-movement history? Tell me in the comments.&lt;/p&gt;

</description>
      <category>python</category>
      <category>kafka</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build a Telegram/Discord Live Score Alert Bot in Python (Webhooks, No Polling)</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:32:49 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-telegramdiscord-live-score-alert-bot-in-python-webhooks-no-polling-112l</link>
      <guid>https://dev.to/orbistats/build-a-telegramdiscord-live-score-alert-bot-in-python-webhooks-no-polling-112l</guid>
      <description>&lt;p&gt;The cheapest way to get a goal alert is to stop asking. A polling bot calls an API every few seconds, 24 hours a day, to learn that nothing changed. A webhook bot sits quietly until the data provider calls you.&lt;/p&gt;

&lt;p&gt;In this tutorial we build a FastAPI service that receives sports webhooks and fans them out to Telegram and Discord. It handles the things that break real alert bots: duplicate deliveries, slow handlers, failed sends, rate limits and fake requests. You can test the entire thing without an API key, using a small script that fires sample events at your own server.&lt;/p&gt;

&lt;p&gt;Disclosure: I work on Orbistats, the data source in this series. The pattern works with any provider that supports webhooks.&lt;/p&gt;

&lt;p&gt;What we are building&lt;br&gt;
text&lt;br&gt;
Orbistats ──POST──▶  FastAPI receiver  ──▶  dedupe (SQLite)  ──▶  ┌─▶ Telegram&lt;br&gt;
 (webhook)           /webhooks/orbistats     ack in &amp;lt;1s          └─▶ Discord&lt;br&gt;
                     verify signature        send in background&lt;br&gt;
A receiver endpoint that verifies, filters and acknowledges instantly.&lt;br&gt;
Idempotent delivery: the same event never alerts twice.&lt;br&gt;
Two notifiers (Telegram and Discord) that fail independently.&lt;br&gt;
A test sender so you can develop with zero external dependencies.&lt;/p&gt;

&lt;p&gt;Polling math, for perspective. Polling every 10 seconds across 6 live hours is 2,160 requests a day to deliver maybe a few dozen events. A webhook bot makes zero requests to learn about those events.&lt;/p&gt;

&lt;p&gt;Prerequisites&lt;br&gt;
Python 3.10+ and a terminal.&lt;br&gt;
A Telegram account and/or a Discord server where you can add a webhook.&lt;br&gt;
An Orbistats account is optional until the last step. If you want to see real payloads first, use the sandbox. For how webhooks are registered and what events exist, read the Webhooks API docs.&lt;br&gt;
Step 1: Project setup&lt;br&gt;
bash&lt;br&gt;
mkdir score-alerts &amp;amp;&amp;amp; cd score-alerts&lt;br&gt;
python -m venv .venv &amp;amp;&amp;amp; source .venv/bin/activate   # Windows: .venv\Scripts\activate&lt;/p&gt;

&lt;p&gt;requirements.txt:&lt;/p&gt;

&lt;p&gt;text&lt;br&gt;
fastapi&lt;br&gt;
uvicorn[standard]&lt;br&gt;
httpx&lt;br&gt;
python-dotenv&lt;br&gt;
bash&lt;br&gt;
pip install -r requirements.txt&lt;br&gt;
Step 2: Get your Telegram and Discord credentials&lt;/p&gt;

&lt;p&gt;Telegram (2 minutes):&lt;/p&gt;

&lt;p&gt;Open &lt;a class="mentioned-user" href="https://dev.to/botfather"&gt;@botfather&lt;/a&gt;, send /newbot, and copy the bot token.&lt;br&gt;
Add the bot to your group, or make it an admin of your channel.&lt;br&gt;
Send any message in that chat, then open &lt;a href="https://api.telegram.org/bot" rel="noopener noreferrer"&gt;https://api.telegram.org/bot&lt;/a&gt;/getUpdates and copy the chat.id value. Group and channel ids are usually negative numbers.&lt;/p&gt;

&lt;p&gt;Discord (1 minute):&lt;/p&gt;

&lt;p&gt;In your server: Server Settings → Integrations → Webhooks → New Webhook.&lt;br&gt;
Pick a channel and click Copy Webhook URL.&lt;/p&gt;

&lt;p&gt;Create .env and add it to .gitignore:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
TELEGRAM_BOT_TOKEN=123456:ABC...&lt;br&gt;
TELEGRAM_CHAT_ID=-1001234567890&lt;br&gt;
DISCORD_WEBHOOK_URL=&lt;a href="https://discord.com/api/webhooks/" rel="noopener noreferrer"&gt;https://discord.com/api/webhooks/&lt;/a&gt;...&lt;br&gt;
WEBHOOK_SECRET=change-me-long-random-string&lt;br&gt;
WEBHOOK_SIGNATURE_HEADER=X-Signature&lt;br&gt;
ALERT_TYPES=goal,red_card,full_time&lt;br&gt;
SEEN_DB=seen.db&lt;/p&gt;

&lt;p&gt;Treat the Discord webhook URL like a password. Anyone who has it can post to your channel.&lt;/p&gt;

&lt;p&gt;Step 3: The event model (the only place we assume a payload shape)&lt;/p&gt;

&lt;p&gt;Every provider names events differently, so we isolate that in one function. The rest of the app only ever sees our own Event. The match fields below follow the live-match example in the Orbistats docs (match_id, minute, home.name, home.score). The event envelope (type, id, data) is an assumption: match it to the Webhooks docs.&lt;/p&gt;

&lt;p&gt;Create events.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import hashlib&lt;br&gt;
import html&lt;br&gt;
from dataclasses import dataclass&lt;/p&gt;

&lt;p&gt;@dataclass(frozen=True)&lt;br&gt;
class Event:&lt;br&gt;
    id: str | None&lt;br&gt;
    type: str&lt;br&gt;
    match_id: str&lt;br&gt;
    minute: int | None&lt;br&gt;
    home: str&lt;br&gt;
    away: str&lt;br&gt;
    home_score: int&lt;br&gt;
    away_score: int&lt;br&gt;
    player: str | None = None&lt;/p&gt;

&lt;p&gt;def normalize_event(p: dict) -&amp;gt; Event | None:&lt;br&gt;
    """Map the provider's webhook payload into our own Event.&lt;br&gt;
    ASSUMPTION: adjust field names to the real payload in the Webhooks docs."""&lt;br&gt;
    data = p.get("data", p)&lt;br&gt;
    match = data.get("match", data)&lt;br&gt;
    home = match.get("home") or {}&lt;br&gt;
    away = match.get("away") or {}&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;etype = str(p.get("type") or data.get("type") or "").lower().replace(" ", "_")
match_id = match.get("match_id") or data.get("match_id")
if not etype or not match_id:
    return None  # not an event we understand

minute = match.get("minute")
if minute is None:
    minute = data.get("minute")

player = data.get("player")
if isinstance(player, dict):
    player = player.get("name")

return Event(
    id=p.get("id"),
    type=etype,
    match_id=str(match_id),
    minute=int(minute) if minute is not None else None,
    home=home.get("name", "Home"),
    away=away.get("name", "Away"),
    home_score=int(home.get("score") or 0),
    away_score=int(away.get("score") or 0),
    player=player,
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def dedupe_key(e: Event) -&amp;gt; str:&lt;br&gt;
    """Prefer the provider's event id; otherwise derive a stable key."""&lt;br&gt;
    if e.id:&lt;br&gt;
        return f"id:{e.id}"&lt;br&gt;
    raw = f"{e.match_id}|{e.type}|{e.minute}|{e.home_score}-{e.away_score}|{e.player}"&lt;br&gt;
    return "h:" + hashlib.sha256(raw.encode()).hexdigest()[:24]&lt;/p&gt;

&lt;p&gt;EMOJI = {"goal": "⚽", "red_card": "🟥", "yellow_card": "🟨",&lt;br&gt;
         "half_time": "⏸️", "full_time": "🏁"}&lt;/p&gt;

&lt;p&gt;def headline(e: Event) -&amp;gt; str:&lt;br&gt;
    icon = EMOJI.get(e.type, "📣")&lt;br&gt;
    minute = f" {e.minute}'" if e.minute is not None else ""&lt;br&gt;
    return f"{icon} {e.type.replace('_', ' ').upper()}{minute}"&lt;/p&gt;

&lt;p&gt;def body(e: Event) -&amp;gt; str:&lt;br&gt;
    line = f"{e.home} {e.home_score} – {e.away_score} {e.away}"&lt;br&gt;
    return f"{line}\n{e.player}" if e.player else line&lt;/p&gt;

&lt;p&gt;def to_discord_text(e: Event) -&amp;gt; str:&lt;br&gt;
    return f"&lt;strong&gt;{headline(e)}&lt;/strong&gt;\n{body(e)}"&lt;/p&gt;

&lt;p&gt;def to_telegram_html(e: Event) -&amp;gt; str:&lt;br&gt;
    # Telegram HTML mode breaks on raw &amp;lt; &amp;gt; &amp;amp;, so always escape API data&lt;br&gt;
    return f"&lt;b&gt;{html.escape(headline(e))}&lt;/b&gt;\n{html.escape(body(e))}"&lt;/p&gt;

&lt;p&gt;Why a derived dedupe key? If a provider does not send a unique event id, hashing the match, event type, minute and score still gives you a stable key, so retries do not become double alerts.&lt;/p&gt;

&lt;p&gt;Step 4: Remember what we have already sent (SQLite)&lt;/p&gt;

&lt;p&gt;Create store.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import os&lt;br&gt;
import sqlite3&lt;br&gt;
import time&lt;/p&gt;

&lt;p&gt;_db = sqlite3.connect(os.getenv("SEEN_DB", "seen.db"), check_same_thread=False)&lt;br&gt;
_db.execute("CREATE TABLE IF NOT EXISTS seen (key TEXT PRIMARY KEY, at INTEGER NOT NULL)")&lt;br&gt;
_db.commit()&lt;/p&gt;

&lt;p&gt;def first_time(key: str) -&amp;gt; bool:&lt;br&gt;
    """True only the first time a key is seen (atomic claim)."""&lt;br&gt;
    cur = _db.execute("INSERT OR IGNORE INTO seen (key, at) VALUES (?, ?)",&lt;br&gt;
                      (key, int(time.time())))&lt;br&gt;
    _db.commit()&lt;br&gt;
    return cur.rowcount == 1&lt;/p&gt;

&lt;p&gt;def forget(key: str) -&amp;gt; None:&lt;br&gt;
    """Release a key so a retry can alert again (used when every send failed)."""&lt;br&gt;
    _db.execute("DELETE FROM seen WHERE key = ?", (key,))&lt;br&gt;
    _db.commit()&lt;/p&gt;

&lt;p&gt;INSERT OR IGNORE makes the check-and-claim a single atomic statement, so two simultaneous deliveries cannot both win. For a long-running service, delete rows older than a week now and then.&lt;/p&gt;

&lt;p&gt;Step 5: The notifiers (Telegram and Discord)&lt;/p&gt;

&lt;p&gt;Create notify.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import asyncio&lt;br&gt;
import os&lt;/p&gt;

&lt;p&gt;import httpx&lt;/p&gt;

&lt;p&gt;TG_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")&lt;br&gt;
TG_CHAT = os.getenv("TELEGRAM_CHAT_ID")&lt;br&gt;
DISCORD_URL = os.getenv("DISCORD_WEBHOOK_URL")&lt;/p&gt;

&lt;p&gt;async def _post_json(client: httpx.AsyncClient, url: str, payload: dict, retries: int = 2):&lt;br&gt;
    """POST with a polite retry when the service says 429 (rate limited)."""&lt;br&gt;
    for attempt in range(retries + 1):&lt;br&gt;
        r = await client.post(url, json=payload, timeout=10)&lt;br&gt;
        if r.status_code != 429:&lt;br&gt;
            r.raise_for_status()&lt;br&gt;
            return&lt;br&gt;
        wait = r.headers.get("Retry-After")&lt;br&gt;
        await asyncio.sleep(min(float(wait), 10) if wait else 2 ** attempt)&lt;br&gt;
    raise RuntimeError("rate limited after retries")&lt;/p&gt;

&lt;p&gt;async def send_telegram(client: httpx.AsyncClient, html_text: str):&lt;br&gt;
    if not (TG_TOKEN and TG_CHAT):&lt;br&gt;
        return  # channel not configured&lt;br&gt;
    await _post_json(&lt;br&gt;
        client,&lt;br&gt;
        f"&lt;a href="https://api.telegram.org/bot%7BTG_TOKEN%7D/sendMessage" rel="noopener noreferrer"&gt;https://api.telegram.org/bot{TG_TOKEN}/sendMessage&lt;/a&gt;",&lt;br&gt;
        {"chat_id": TG_CHAT, "text": html_text,&lt;br&gt;
         "parse_mode": "HTML", "disable_web_page_preview": True},&lt;br&gt;
    )&lt;/p&gt;

&lt;p&gt;async def send_discord(client: httpx.AsyncClient, text: str):&lt;br&gt;
    if not DISCORD_URL:&lt;br&gt;
        return&lt;br&gt;
    await _post_json(&lt;br&gt;
        client,&lt;br&gt;
        DISCORD_URL,&lt;br&gt;
        # allowed_mentions: [] stops a malicious payload from pinging &lt;a class="mentioned-user" href="https://dev.to/everyone"&gt;@everyone&lt;/a&gt;&lt;br&gt;
        {"content": text, "allowed_mentions": {"parse": []}},&lt;br&gt;
    )&lt;/p&gt;

&lt;p&gt;Two details are worth copying. allowed_mentions means even if a team name or player field contained &lt;a class="mentioned-user" href="https://dev.to/everyone"&gt;@everyone&lt;/a&gt;, Discord would not ping anyone. And each notifier returns quietly when it is not configured, so you can run with only one channel.&lt;/p&gt;

&lt;p&gt;Step 6: The receiver&lt;/p&gt;

&lt;p&gt;This is the heart of the bot. It follows one rule: verify, filter, dedupe, acknowledge, and only then do the slow work.&lt;/p&gt;

&lt;p&gt;Create app.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import asyncio&lt;br&gt;
import hashlib&lt;br&gt;
import hmac&lt;br&gt;
import json&lt;br&gt;
import logging&lt;br&gt;
import os&lt;/p&gt;

&lt;p&gt;import httpx&lt;br&gt;
from dotenv import load_dotenv&lt;br&gt;
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request&lt;/p&gt;

&lt;p&gt;load_dotenv()&lt;/p&gt;

&lt;p&gt;from events import dedupe_key, normalize_event, to_discord_text, to_telegram_html  # noqa: E402&lt;br&gt;
from notify import send_discord, send_telegram  # noqa: E402&lt;br&gt;
from store import first_time, forget  # noqa: E402&lt;/p&gt;

&lt;p&gt;logging.basicConfig(level=logging.INFO)&lt;br&gt;
log = logging.getLogger("score-alerts")&lt;/p&gt;

&lt;p&gt;SECRET = os.getenv("WEBHOOK_SECRET", "")&lt;br&gt;
SIG_HEADER = os.getenv("WEBHOOK_SIGNATURE_HEADER", "X-Signature")&lt;br&gt;
ALERT_TYPES = set(os.getenv("ALERT_TYPES", "goal,red_card,full_time").split(","))&lt;/p&gt;

&lt;p&gt;app = FastAPI()&lt;/p&gt;

&lt;p&gt;def verify(raw: bytes, header_value: str | None) -&amp;gt; bool:&lt;br&gt;
    """Generic HMAC-SHA256 check. ASSUMPTION: match header name and scheme&lt;br&gt;
    to the signature method documented in the Webhooks API docs."""&lt;br&gt;
    if not SECRET:&lt;br&gt;
        return True  # signature check disabled: development only!&lt;br&gt;
    if not header_value:&lt;br&gt;
        return False&lt;br&gt;
    expected = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()&lt;br&gt;
    received = header_value.removeprefix("sha256=")&lt;br&gt;
    return hmac.compare_digest(expected, received)  # constant-time compare&lt;/p&gt;

&lt;p&gt;async def fan_out(event, key: str):&lt;br&gt;
    async with httpx.AsyncClient() as client:&lt;br&gt;
        results = await asyncio.gather(&lt;br&gt;
            send_telegram(client, to_telegram_html(event)),&lt;br&gt;
            send_discord(client, to_discord_text(event)),&lt;br&gt;
            return_exceptions=True,  # one failing channel must not block the other&lt;br&gt;
        )&lt;br&gt;
    failures = [r for r in results if isinstance(r, Exception)]&lt;br&gt;
    for f in failures:&lt;br&gt;
        log.error("notify failed: %s", f)&lt;br&gt;
    if len(failures) == len(results):&lt;br&gt;
        forget(key)  # nothing was delivered, so allow a provider retry to alert&lt;/p&gt;

&lt;p&gt;@app.post("/webhooks/orbistats")&lt;br&gt;
async def receive(request: Request, background: BackgroundTasks):&lt;br&gt;
    raw = await request.body()  # signature is computed on the RAW bytes&lt;br&gt;
    if not verify(raw, request.headers.get(SIG_HEADER)):&lt;br&gt;
        raise HTTPException(status_code=401, detail="bad signature")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    payload = json.loads(raw)
except ValueError:
    raise HTTPException(status_code=400, detail="invalid json")

event = normalize_event(payload)
if event is None or event.type not in ALERT_TYPES:
    return {"ok": True, "ignored": True}

key = dedupe_key(event)
if not first_time(key):
    return {"ok": True, "duplicate": True}

background.add_task(fan_out, event, key)  # send AFTER we respond
return {"ok": True}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;@app.get("/health")&lt;br&gt;
def health():&lt;br&gt;
    return {"ok": True}&lt;/p&gt;

&lt;p&gt;Why each line matters:&lt;/p&gt;

&lt;p&gt;Raw body first. HMAC signatures are computed over the exact bytes sent. Parse JSON before verifying and you may re-serialize differently, and valid requests will fail.&lt;br&gt;
compare_digest. A normal == can leak timing information.&lt;br&gt;
200 immediately. Providers usually retry slow or failed deliveries. Doing the Telegram and Discord calls in a background task keeps your response time tiny, so retries are rare.&lt;br&gt;
Dedupe still exists because retries and network hiccups can deliver the same event twice anyway.&lt;br&gt;
forget() on total failure. If both channels failed, releasing the key means a later retry can still alert, instead of the event being silently lost.&lt;/p&gt;

&lt;p&gt;For production volume, replace BackgroundTasks with a real queue (Redis with RQ, Celery, or a cloud queue) so alerts survive a process restart.&lt;/p&gt;

&lt;p&gt;Step 7: Test it with no API key&lt;/p&gt;

&lt;p&gt;Build against a fake sender first. Create send_test_event.py:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import hashlib&lt;br&gt;
import hmac&lt;br&gt;
import json&lt;br&gt;
import os&lt;/p&gt;

&lt;p&gt;import httpx&lt;br&gt;
from dotenv import load_dotenv&lt;/p&gt;

&lt;p&gt;load_dotenv()&lt;/p&gt;

&lt;p&gt;URL = os.getenv("TARGET", "&lt;a href="http://localhost:8000/webhooks/orbistats%22" rel="noopener noreferrer"&gt;http://localhost:8000/webhooks/orbistats"&lt;/a&gt;)&lt;br&gt;
SECRET = os.getenv("WEBHOOK_SECRET", "")&lt;br&gt;
HEADER = os.getenv("WEBHOOK_SIGNATURE_HEADER", "X-Signature")&lt;/p&gt;

&lt;p&gt;def send(payload: dict):&lt;br&gt;
    raw = json.dumps(payload).encode()&lt;br&gt;
    headers = {"Content-Type": "application/json"}&lt;br&gt;
    if SECRET:&lt;br&gt;
        headers[HEADER] = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest()&lt;br&gt;
    r = httpx.post(URL, content=raw, headers=headers, timeout=10)&lt;br&gt;
    print(r.status_code, r.json())&lt;/p&gt;

&lt;p&gt;goal = {&lt;br&gt;
    "id": "evt_1001",&lt;br&gt;
    "type": "goal",&lt;br&gt;
    "data": {&lt;br&gt;
        "match_id": "match_50231",&lt;br&gt;
        "minute": 73,&lt;br&gt;
        "home": {"name": "Manchester City", "score": 3},&lt;br&gt;
        "away": {"name": "Arsenal", "score": 1},&lt;br&gt;
        "player": "J. Doe",&lt;br&gt;
    },&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;send(goal)   # should alert once&lt;br&gt;
send(goal)   # same id again: should be reported as a duplicate&lt;/p&gt;

&lt;p&gt;send({"id": "evt_1002", "type": "substitution",&lt;br&gt;
      "data": {"match_id": "match_50231", "minute": 75,&lt;br&gt;
               "home": {"name": "Manchester City", "score": 3},&lt;br&gt;
               "away": {"name": "Arsenal", "score": 1}}})   # not in ALERT_TYPES: ignored&lt;/p&gt;

&lt;p&gt;Run the server in one terminal:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
uvicorn app:app --port 8000 --env-file .env&lt;/p&gt;

&lt;p&gt;Run the sender in another:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
python send_test_event.py&lt;/p&gt;

&lt;p&gt;You should see three results: {"ok": true} (and a message in Telegram and Discord), then {"ok": true, "duplicate": true}, then {"ok": true, "ignored": true}. Try removing the signature header or changing the secret and confirm you get a 401.&lt;/p&gt;

&lt;p&gt;Step 8: Go live with real webhooks&lt;br&gt;
Expose your server over HTTPS. For local testing use a tunnel, such as ngrok http 8000 or a Cloudflare Tunnel, and copy the public URL. For real use, deploy to a small always-on host (a VPS, Fly.io or Railway).&lt;br&gt;
Get your access. Request access. Your plan’s access time starts when you open the activation link, so do this only when your receiver is ready and your tunnel is up.&lt;br&gt;
Register your URL at &lt;a href="https://YOUR-PUBLIC-URL/webhooks/orbistats" rel="noopener noreferrer"&gt;https://YOUR-PUBLIC-URL/webhooks/orbistats&lt;/a&gt; the way the Webhooks API docs describe, and confirm the event names and payload shape against normalize_event().&lt;br&gt;
Match the signature scheme. Update WEBHOOK_SIGNATURE_HEADER and verify() to the documented method, and set WEBHOOK_SECRET to the secret you were given.&lt;br&gt;
Watch the first live event arrive. Check the API reference and the Live Scores API page for field names.&lt;/p&gt;

&lt;p&gt;A minimal Dockerfile for deployment:&lt;/p&gt;

&lt;p&gt;dockerfile&lt;br&gt;
FROM python:3.12-slim&lt;br&gt;
WORKDIR /app&lt;br&gt;
COPY requirements.txt .&lt;br&gt;
RUN pip install --no-cache-dir -r requirements.txt&lt;br&gt;
COPY *.py .&lt;br&gt;
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]&lt;br&gt;
bash&lt;br&gt;
docker build -t score-alerts .&lt;br&gt;
docker run -d --restart unless-stopped --env-file .env -p 8000:8000 \&lt;br&gt;
  -v $(pwd)/data:/app/data -e SEEN_DB=/app/data/seen.db score-alerts&lt;br&gt;
Which channel should you use?&lt;br&gt;
    Telegram    Discord&lt;br&gt;
Setup   Bot token + chat id One webhook URL&lt;br&gt;
Best for    Personal alerts, small groups, channels Communities and servers&lt;br&gt;
Rich formatting HTML or MarkdownV2  Markdown and embeds&lt;br&gt;
Watch out for   Chat ids differ for users, groups and channels  Webhook URL is a secret&lt;br&gt;
Common problems&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
Duplicate alerts    Provider retried because the first response was slow, or no event id    Respond instantly, keep the dedupe table, use the derived key&lt;br&gt;
Telegram error can't parse entities Unescaped &amp;lt;, &amp;gt; or &amp;amp; in team or player names Always pass API text through html.escape&lt;br&gt;
Telegram chat not found or 403  Bot not in the chat, or wrong id    Add the bot (admin for channels), re-check getUpdates, remember group ids are negative&lt;br&gt;
Discord 404 or 401  Webhook deleted or URL copied wrongly   Recreate the webhook and update .env&lt;br&gt;
Your endpoint returns 401 for real events   Signature computed on re-serialized JSON, wrong secret, or wrong header name    Verify on the raw body, and copy the header and scheme from the docs&lt;br&gt;
Nothing arrives at all  Public URL not reachable or not HTTPS   Test /health from outside, check the tunnel, check the provider’s delivery logs&lt;br&gt;
Alerts arrive late  Slow handler or a sleeping free-tier host   Acknowledge first, queue the sends, keep an instance warm&lt;br&gt;
Surprise &lt;a class="mentioned-user" href="https://dev.to/everyone"&gt;@everyone&lt;/a&gt; pings    Raw API text posted as Discord content  Keep allowed_mentions set to an empty parse list&lt;br&gt;
Alert lost after a Telegram outage  Event marked as seen before delivery failed Use forget() when every channel fails, or move to a queue with retries&lt;br&gt;
Security checklist&lt;br&gt;
Never commit .env, the Telegram token or the Discord webhook URL, and rotate them if they leak.&lt;br&gt;
Always verify signatures in production. An unverified endpoint lets anyone spam your channels.&lt;br&gt;
Escape everything from the payload before it goes into HTML or chat markdown.&lt;br&gt;
Respond with 2xx only after the event is safely handled or queued, and never leak internal errors in the response body.&lt;br&gt;
Where to go next&lt;br&gt;
Prefer a persistent connection? Compare this with the push approach in I Built a Discord Bot That Alerts Live Score Updates Using WebSockets.&lt;br&gt;
Want the live screen too? Pair these alerts with the scoreboard from Build a Live Football Scoreboard in 20 Minutes.&lt;br&gt;
New to the API? Start with Sports APIs Explained, and see how alerts fit into a bigger app in Build a Multi-Sport Dashboard.&lt;br&gt;
Add features: per-team subscriptions (/follow Arsenal), a quiet-hours setting, odds-movement alerts, or a daily summary from the Sports Data API.&lt;br&gt;
Monitor it: check provider health on the status page, and review pricing before you plan longer-running production use.&lt;br&gt;
Wrap-up&lt;/p&gt;

&lt;p&gt;You built an alert bot that never polls, never double-alerts, replies fast, survives one channel failing, and rejects forged requests. Just as important, every assumption about the provider’s payload lives in two small functions, so adapting to the real docs is a ten-minute job.&lt;/p&gt;

&lt;p&gt;If you want to try it on real events, request the free hour and run Step 8. Should the next post add per-user /follow subscriptions, or odds-movement alerts? Let me know in the comments.&lt;/p&gt;

</description>
      <category>python</category>
      <category>webhooks</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build a Live Football Scoreboard in 20 Minutes with JavaScript and a Sports API</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:19:06 +0000</pubDate>
      <link>https://dev.to/orbistats/build-a-live-football-scoreboard-in-20-minutes-with-javascript-and-a-sports-api-4fa7</link>
      <guid>https://dev.to/orbistats/build-a-live-football-scoreboard-in-20-minutes-with-javascript-and-a-sports-api-4fa7</guid>
      <description>&lt;p&gt;A live scoreboard looks simple until you ship it. The demo works, then real life shows up: your API key leaks into the browser, ten open tabs burn your quota, a background tab keeps polling for no reason, and the score changes so quietly that users never notice the goal.&lt;/p&gt;

&lt;p&gt;In this tutorial we build a React scoreboard that avoids all four problems, using a tiny Node proxy and the Orbistats Live Scores API. You will have a working app in about 20 minutes, and you can build the whole UI without an API key, using a built-in mock feed.&lt;/p&gt;

&lt;p&gt;Disclosure: I work on Orbistats, the data source used here. The pattern works with any sports API that returns live match JSON.&lt;/p&gt;

&lt;p&gt;What we are building&lt;br&gt;
A React + Vite scoreboard that shows live and finished matches.&lt;br&gt;
A tiny Express proxy that keeps your API key on the server and caches responses so ten tabs cost one upstream call.&lt;br&gt;
A useLiveScores hook with adaptive polling: faster when matches are live, slower when idle, paused when the tab is hidden.&lt;br&gt;
A goal flash so users actually see a score change.&lt;br&gt;
Mock mode, so you can finish the UI before you touch a key.&lt;br&gt;
Step    What you do Time&lt;br&gt;
1   Create the project  2 min&lt;br&gt;
2   Write the proxy with mock mode  4 min&lt;br&gt;
3   Write the hook  5 min&lt;br&gt;
4   Build the UI and styles 6 min&lt;br&gt;
5   Switch to real data 3 min&lt;br&gt;
Prerequisites&lt;br&gt;
Node.js 20.6 or newer (we use the built-in --env-file flag and fetch).&lt;br&gt;
Basic React. You only need components and hooks.&lt;br&gt;
An Orbistats API key is optional until Step 5. If you want to look at real payloads first, the sandbox lets you try requests, and the quickstart covers authentication.&lt;br&gt;
Step 1: Create the project (2 min)&lt;br&gt;
bash&lt;br&gt;
npm create vite@latest live-scoreboard -- --template react&lt;br&gt;
cd live-scoreboard&lt;br&gt;
npm install&lt;br&gt;
npm install express&lt;/p&gt;

&lt;p&gt;Create a .env file in the project root. These variables are read by the server only, so they never reach the browser:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
USE_MOCK=1&lt;br&gt;
ORBISTATS_API_KEY=your_key_here&lt;br&gt;
ORBISTATS_BASE=&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;&lt;br&gt;
ORBISTATS_LIVE_PATH=/football/matches/live&lt;/p&gt;

&lt;p&gt;Add .env to .gitignore, then add a script to package.json:&lt;/p&gt;

&lt;p&gt;json&lt;br&gt;
"scripts": {&lt;br&gt;
  "dev": "vite",&lt;br&gt;
  "server": "node --env-file=.env server.js"&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Finally, tell Vite to forward /api calls to our proxy. Replace vite.config.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import { defineConfig } from "vite";&lt;br&gt;
import react from "@vitejs/plugin-react";&lt;/p&gt;

&lt;p&gt;export default defineConfig({&lt;br&gt;
  plugins: [react()],&lt;br&gt;
  server: { proxy: { "/api": "&lt;a href="http://localhost:4000" rel="noopener noreferrer"&gt;http://localhost:4000&lt;/a&gt;" } },&lt;br&gt;
});&lt;br&gt;
Step 2: The proxy, with a mock feed (4 min)&lt;/p&gt;

&lt;p&gt;Why a proxy? If you call the API straight from the browser, your key is visible to anyone who opens DevTools. A proxy also gives you one place to cache.&lt;/p&gt;

&lt;p&gt;Create server.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import express from "express";&lt;/p&gt;

&lt;p&gt;const app = express();&lt;br&gt;
const KEY = process.env.ORBISTATS_API_KEY;&lt;br&gt;
const BASE = process.env.ORBISTATS_BASE ?? "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;";&lt;br&gt;
const LIVE_PATH = process.env.ORBISTATS_LIVE_PATH ?? "/football/matches/live";&lt;br&gt;
const USE_MOCK = process.env.USE_MOCK === "1" || !KEY;&lt;br&gt;
const TTL_MS = 5000; // one upstream call per 5 seconds, however many tabs&lt;/p&gt;

&lt;p&gt;// Mock data uses the same shape as the live-match example in the docs&lt;br&gt;
const mock = [&lt;br&gt;
  { match_id: "m1", status: "live", minute: 61,&lt;br&gt;
    home: { name: "Manchester City", score: 2 }, away: { name: "Arsenal", score: 1 } },&lt;br&gt;
  { match_id: "m2", status: "live", minute: 34,&lt;br&gt;
    home: { name: "Real Madrid", score: 0 }, away: { name: "Barcelona", score: 0 } },&lt;br&gt;
  { match_id: "m3", status: "finished", minute: 90,&lt;br&gt;
    home: { name: "Inter", score: 1 }, away: { name: "Milan", score: 1 } },&lt;br&gt;
];&lt;/p&gt;

&lt;p&gt;// Advance the fake matches so you can watch scores change&lt;br&gt;
setInterval(() =&amp;gt; {&lt;br&gt;
  for (const m of mock) {&lt;br&gt;
    if (m.status !== "live") continue;&lt;br&gt;
    m.minute = Math.min(90, m.minute + 1);&lt;br&gt;
    if (Math.random() &amp;lt; 0.1) (Math.random() &amp;lt; 0.5 ? m.home : m.away).score += 1;&lt;br&gt;
    if (m.minute === 90) m.status = "finished";&lt;br&gt;
  }&lt;br&gt;
}, 3000);&lt;/p&gt;

&lt;p&gt;let cache = { at: 0, body: null };&lt;/p&gt;

&lt;p&gt;app.get("/api/live", async (_req, res) =&amp;gt; {&lt;br&gt;
  if (USE_MOCK) return res.json(mock);&lt;/p&gt;

&lt;p&gt;const now = Date.now();&lt;br&gt;
  if (cache.body &amp;amp;&amp;amp; now - cache.at &amp;lt; TTL_MS) return res.json(cache.body);&lt;/p&gt;

&lt;p&gt;try {&lt;br&gt;
    const r = await fetch(&lt;code&gt;${BASE}${LIVE_PATH}&lt;/code&gt;, {&lt;br&gt;
      headers: { Authorization: &lt;code&gt;Bearer ${KEY}&lt;/code&gt; },&lt;br&gt;
    });&lt;br&gt;
    if (!r.ok) return res.status(r.status).json({ error: &lt;code&gt;Upstream ${r.status}&lt;/code&gt; });&lt;br&gt;
    const body = await r.json();&lt;br&gt;
    cache = { at: now, body };&lt;br&gt;
    res.json(body);&lt;br&gt;
  } catch {&lt;br&gt;
    res.status(502).json({ error: "Upstream unreachable" });&lt;br&gt;
  }&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;app.listen(4000, () =&amp;gt; {&lt;br&gt;
  console.log(&lt;code&gt;API proxy on http://localhost:4000 (${USE_MOCK ? "mock" : "live"} mode)&lt;/code&gt;);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Start it with npm run server, then open &lt;a href="http://localhost:4000/api/live" rel="noopener noreferrer"&gt;http://localhost:4000/api/live&lt;/a&gt;. You should see the mock matches as JSON.&lt;/p&gt;

&lt;p&gt;Step 3: The useLiveScores hook (5 min)&lt;/p&gt;

&lt;p&gt;All the data-fetching logic lives in one hook, so the UI stays dumb and you can swap polling for a push connection later without touching components.&lt;/p&gt;

&lt;p&gt;First, a small normalizer so the UI never depends on the raw API shape. Create src/normalize.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// Maps the API's live-match shape into the shape our UI uses.&lt;br&gt;
// Check the API reference for the exact response envelope.&lt;br&gt;
export function normalize(raw) {&lt;br&gt;
  const list = Array.isArray(raw) ? raw : raw?.data ?? raw?.matches ?? [raw];&lt;br&gt;
  return list.filter(Boolean).map((m) =&amp;gt; ({&lt;br&gt;
    id: m.match_id,&lt;br&gt;
    status: m.status,&lt;br&gt;
    minute: m.minute ?? null,&lt;br&gt;
    home: m.home?.name,&lt;br&gt;
    homeScore: m.home?.score ?? 0,&lt;br&gt;
    away: m.away?.name,&lt;br&gt;
    awayScore: m.away?.score ?? 0,&lt;br&gt;
  }));&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Now the hook. Create src/useLiveScores.js:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import { useEffect, useRef, useState } from "react";&lt;br&gt;
import { normalize } from "./normalize";&lt;/p&gt;

&lt;p&gt;export function useLiveScores({ liveMs = 5000, idleMs = 30000 } = {}) {&lt;br&gt;
  const [matches, setMatches] = useState([]);&lt;br&gt;
  const [status, setStatus] = useState("loading"); // loading | ok | error&lt;br&gt;
  const [updatedAt, setUpdatedAt] = useState(null);&lt;br&gt;
  const timer = useRef(null);&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    let stopped = false;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function schedule(ms) {
  timer.current = setTimeout(load, ms);
}

async function load() {
  // Don't poll while the tab is hidden
  if (document.hidden) return schedule(idleMs);
  try {
    const res = await fetch("/api/live");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const list = normalize(await res.json());
    if (stopped) return;
    setMatches(list);
    setStatus("ok");
    setUpdatedAt(new Date());
    // Poll fast only while at least one match is live
    schedule(list.some((m) =&amp;gt; m.status === "live") ? liveMs : idleMs);
  } catch {
    if (stopped) return;
    setStatus("error");
    schedule(idleMs);
  }
}

// Refresh immediately when the user comes back to the tab
const onVisible = () =&amp;gt; {
  if (!document.hidden) {
    clearTimeout(timer.current);
    load();
  }
};

document.addEventListener("visibilitychange", onVisible);
load();

return () =&amp;gt; {
  stopped = true;
  clearTimeout(timer.current);
  document.removeEventListener("visibilitychange", onVisible);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}, [liveMs, idleMs]);&lt;/p&gt;

&lt;p&gt;return { matches, status, updatedAt };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Three small decisions make this production-friendly: adaptive intervals (5 s while live, 30 s when idle), no polling in background tabs, and an immediate refresh when the user returns.&lt;/p&gt;

&lt;p&gt;Step 4: The UI (6 min)&lt;/p&gt;

&lt;p&gt;Create src/MatchCard.jsx. The useRef trick compares the previous score with the new one, so the card flashes only when a goal actually happens:&lt;/p&gt;

&lt;p&gt;jsx&lt;br&gt;
import { useEffect, useRef, useState } from "react";&lt;/p&gt;

&lt;p&gt;export default function MatchCard({ m }) {&lt;br&gt;
  const prev = useRef({ h: m.homeScore, a: m.awayScore });&lt;br&gt;
  const [flash, setFlash] = useState(false);&lt;/p&gt;

&lt;p&gt;useEffect(() =&amp;gt; {&lt;br&gt;
    if (prev.current.h !== m.homeScore || prev.current.a !== m.awayScore) {&lt;br&gt;
      prev.current = { h: m.homeScore, a: m.awayScore };&lt;br&gt;
      setFlash(true);&lt;br&gt;
      const t = setTimeout(() =&amp;gt; setFlash(false), 1500);&lt;br&gt;
      return () =&amp;gt; clearTimeout(t);&lt;br&gt;
    }&lt;br&gt;
  }, [m.homeScore, m.awayScore]);&lt;/p&gt;

&lt;p&gt;const live = m.status === "live";&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;li&gt;

      &lt;span&gt;{m.home}&lt;/span&gt;
      &lt;span&gt;&lt;br&gt;
        {m.homeScore} – {m.awayScore}&lt;br&gt;
      &lt;/span&gt;
      &lt;span&gt;{m.away}&lt;/span&gt;
      &lt;span&gt;&lt;br&gt;
        {live ? &lt;code&gt;LIVE ${m.minute ?? ""}'&lt;/code&gt; : m.status}&lt;br&gt;
      &lt;/span&gt;
    &lt;/li&gt;
&lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;Replace src/App.jsx:&lt;/p&gt;

&lt;p&gt;jsx&lt;br&gt;
import { useLiveScores } from "./useLiveScores";&lt;br&gt;
import MatchCard from "./MatchCard";&lt;br&gt;
import "./App.css";&lt;/p&gt;

&lt;p&gt;export default function App() {&lt;br&gt;
  const { matches, status, updatedAt } = useLiveScores();&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;h1&gt;Live Football Scores&lt;/h1&gt;
&lt;br&gt;
      {status === "loading" &amp;amp;&amp;amp; &lt;p&gt;Loading matches…&lt;/p&gt;}&lt;br&gt;
      {status === "error" &amp;amp;&amp;amp; &lt;p&gt;Connection problem. Retrying…&lt;/p&gt;}&lt;br&gt;
      {status === "ok" &amp;amp;&amp;amp; matches.length === 0 &amp;amp;&amp;amp; &lt;p&gt;No matches right now.&lt;/p&gt;}&lt;br&gt;
      &lt;ul&gt;

        {matches.map((m) =&amp;gt; (
          
        ))}
      &lt;/ul&gt;
&lt;br&gt;
      {updatedAt &amp;amp;&amp;amp; &lt;small&gt;Updated {updatedAt.toLocaleTimeString()}&lt;/small&gt;}&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;Replace src/App.css:&lt;/p&gt;

&lt;p&gt;css&lt;br&gt;
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }&lt;br&gt;
main { max-width: 560px; margin: 2rem auto; padding: 0 1rem; }&lt;br&gt;
ul { list-style: none; padding: 0; display: grid; gap: .75rem; }&lt;br&gt;
.card {&lt;br&gt;
  display: grid; grid-template-columns: 1fr auto 1fr auto;&lt;br&gt;
  align-items: center; gap: .75rem; padding: .9rem 1rem;&lt;br&gt;
  border: 1px solid #8884; border-radius: 12px;&lt;br&gt;
}&lt;br&gt;
.team.away { text-align: right; }&lt;br&gt;
.score { font-weight: 700; font-size: 1.25rem; font-variant-numeric: tabular-nums; }&lt;br&gt;
.badge { font-size: .75rem; padding: .2rem .5rem; border-radius: 999px; background: #8883; }&lt;br&gt;
.badge.live { background: #e11d48; color: #fff; animation: pulse 1.4s infinite; }&lt;br&gt;
.flash { animation: flash 1.5s ease-out; }&lt;br&gt;
.warn { color: #b45309; }&lt;br&gt;
@keyframes pulse { 50% { opacity: .55; } }&lt;br&gt;
@keyframes flash { 0% { background: #22c55e55; } 100% { background: transparent; } }&lt;/p&gt;

&lt;p&gt;Run npm run dev in a second terminal and open the URL Vite prints. You should see three matches. Within a few seconds the minutes advance, and when a mock goal lands the card flashes green. You now have the whole UI working without spending a single API request.&lt;/p&gt;

&lt;p&gt;Step 5: Switch to real data (3 min)&lt;br&gt;
Get your key. Request access; after approval you receive an activation link. The access window starts when you open that link, so do this only now that your UI is ready.&lt;br&gt;
Confirm the endpoint path in the API reference and update ORBISTATS_LIVE_PATH in .env if needed. The live-match example in the documentation uses /football/matches/live.&lt;br&gt;
Edit .env: set USE_MOCK=0 and paste your key.&lt;br&gt;
Restart the proxy: npm run server. It should print live mode.&lt;/p&gt;

&lt;p&gt;Reload the page. The same UI now shows real matches. The proxy keeps your key private, and the 5-second cache means ten tabs still cost one upstream call every 5 seconds.&lt;/p&gt;

&lt;p&gt;Football is one of 13 sports. To show another sport, change the path segment (for example /basketball/...) and check the exact route on the sport’s page and in the docs.&lt;/p&gt;

&lt;p&gt;Common problems&lt;br&gt;
Symptom Likely cause    Fix&lt;br&gt;
401 from the proxy  Key missing, wrong, or .env not loaded  Start with npm run server (it uses --env-file), and check the Bearer header&lt;br&gt;
CORS error in the browser console   Calling the API directly from React Always call /api/live, never the upstream URL&lt;br&gt;
Empty scoreboard but no error   Response envelope differs from normalize()  console.log the raw JSON and adjust the list line&lt;br&gt;
Cards never flash   Unstable React key, so cards remount    Use the match id as key, as in App.jsx&lt;br&gt;
Quota disappears quickly    Every tab or user hits the API directly Keep the proxy cache, and keep background-tab polling off&lt;br&gt;
Access window ended mid-tutorial    Activation link opened too early    Build in mock mode first, open the link at Step 5&lt;br&gt;
Finished matches show a raw status text Status values differ from "live"    Check status values in the docs and map them to friendly labels&lt;br&gt;
Taking it further&lt;br&gt;
Go from polling to push. Because the data logic is isolated in one hook and one proxy, you can replace the proxy’s polling with a WebSocket connection and stream updates to the browser. The WebSocket API docs have the URL and message format, and this walkthrough covers the pattern end to end: Build a Live Sports Scoreboard in 50 Lines of JavaScript with a WebSocket API.&lt;br&gt;
Use webhooks on your backend if you need to react to events (goals, cards) without keeping a connection open: webhooks API.&lt;br&gt;
Add fixtures and standings with the Sports Data API so the page shows upcoming matches too.&lt;br&gt;
New to REST? Start with How to Make Your First API Request.&lt;/p&gt;

&lt;p&gt;Check the numbers on your side. The WebSocket feed targets under 500 ms, but latency depends on your region and network, so measure from where your server runs. Service health is public on the status page, and plan details are on the pricing page.&lt;/p&gt;

&lt;p&gt;Wrap-up&lt;/p&gt;

&lt;p&gt;You built a scoreboard that keeps secrets on the server, shares one upstream call between many users, polls only when it matters, and highlights goals. You also built it in an order that never wastes a request: mock first, real data last.&lt;/p&gt;

&lt;p&gt;If you want to try it on live data, request the free hour and run Step 5. Which would you like next: a WebSocket version of this hook, or an odds ticker on the same scoreboard? Tell me in the comments.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Top 10 Sports Data Providers in 2026: The Complete Ranked Guide</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Tue, 27 Oct 2026 09:05:33 +0000</pubDate>
      <link>https://dev.to/orbistats/top-10-sports-data-providers-in-2026-the-complete-ranked-guide-1f58</link>
      <guid>https://dev.to/orbistats/top-10-sports-data-providers-in-2026-the-complete-ranked-guide-1f58</guid>
      <description>&lt;p&gt;Choosing a sports data provider feels like a small decision in week one. By month six it decides your infrastructure bill, your data quality, your legal exposure, and how many weekends your team spends parsing weird edge cases at 2 a.m. on a match day.&lt;/p&gt;

&lt;p&gt;The market in 2026 is also more confusing than it’s ever been. There are official-data giants that sell licensed feeds to sportsbooks and leagues. There are developer-first APIs you can start using in five minutes with a credit card. There are odds-only aggregators, football-only specialists, and multi-sport platforms that try to do everything behind one schema. They all call themselves “the best.” They’re all best at something different.&lt;/p&gt;

&lt;p&gt;So instead of one more “best API” list written by someone who never integrated any of them, this guide ranks 10 sports data providers against the same criteria, tells you who each one is genuinely for, and — importantly — tells you where each one will hurt you. At the end you’ll also get a copy-paste benchmark script and a provider-agnostic adapter pattern so you can test any shortlist yourself in an afternoon.&lt;/p&gt;

&lt;p&gt;TL;DR — the ranking at a glance&lt;/p&gt;

&lt;h1&gt;
  
  
  Provider    Best for    Delivery    Entry point
&lt;/h1&gt;

&lt;p&gt;1   Sportradar  Licensed, enterprise-grade multi-sport data REST + push feeds   30-day free trial, then sales&lt;br&gt;
2   Genius Sports (Betgenius)   Regulated sportsbooks needing official data Feeds / APIs    Licensing + sales&lt;br&gt;
3   Stats Perform (Opta)    Deep football/event data, in-play betting, media    Feeds + APIs    Demo / quote&lt;br&gt;
4   SportsDataIO    US sports depth, fantasy, props REST    Free trial (scrambled data)&lt;br&gt;
5   Sportmonks  Football-first apps with broad league coverage  REST    Free plan + 14-day trial&lt;br&gt;
6   Orbistats   13 sports behind one schema, REST + WebSocket + webhooks    REST, WebSocket, webhooks, widgets  Free 1-hour access, paid from €19&lt;br&gt;
7   API-Sports  Prototypes and MVPs on a tight budget   REST    Free tier (100 req/day)&lt;br&gt;
8   The Odds API    Simple odds comparison, hobby and indie projects    REST    Free 500 credits/month&lt;br&gt;
9   Odds-API.io Bookmaker breadth, odds screeners   REST + WebSocket    Free tier, then paid&lt;br&gt;
10  LSports Betting operators wanting many sports and books Feeds / APIs    Quote-based&lt;/p&gt;

&lt;p&gt;Rankings are about fit for developer and product teams in 2026, not about which company is biggest. A giant that you can’t legally or financially use is not the best provider for you.&lt;/p&gt;

&lt;p&gt;How we ranked them&lt;/p&gt;

&lt;p&gt;Every provider was judged on the same six questions:&lt;/p&gt;

&lt;p&gt;Coverage — how many sports, leagues and data types (fixtures, live events, stats, lineups, odds, history)?&lt;br&gt;
Delivery &amp;amp; speed — REST only, or also WebSocket, push feeds and webhooks? What do they claim about latency?&lt;br&gt;
Data licensing — is the data official or licensed for betting use, or is it “mainstream coverage”?&lt;br&gt;
Pricing clarity — can you see a number without talking to sales?&lt;br&gt;
Developer experience — docs, sandbox, trial, SDKs, time-to-first-call.&lt;br&gt;
Fit for a team that isn’t an enterprise — can a small team realistically adopt it?&lt;/p&gt;

&lt;p&gt;No provider wins every category. The ranking blends all six, weighted toward breadth, reliability and licensing clarity, because those are the things that are hardest to fix after you’ve shipped.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Sportradar — the enterprise standard&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: sportsbooks, media companies and platforms that need licensed, deep, multi-sport data at scale.&lt;/p&gt;

&lt;p&gt;Sportradar is the name most procurement teams already know. Its Sports Data API markets coverage of 80+ sports, 500+ leagues and 750,000+ events a year, delivered as JSON or XML, with REST endpoints and push-based streaming feeds. It counts major US leagues such as the NBA, NFL, MLB, NHL and NASCAR among its official partners, and it offers both league-specific APIs (maximum depth for a single league) and general sport APIs (consistent structure across many leagues worldwide).&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Unmatched breadth and depth, including full play-by-play on major US leagues.&lt;br&gt;
A free 30-day trial and an API sandbox, so you can test before talking to sales.&lt;br&gt;
Extras beyond raw data: images, editorial content, odds and widgets.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Pricing is package- and sport-based and ends in a sales conversation.&lt;br&gt;
It’s a B2B service — calls are meant to come from your backend, never from a client app.&lt;br&gt;
Overkill (and over-budget) for a side project or an early MVP.&lt;/p&gt;

&lt;p&gt;Verdict: if licensing, depth and brand trust matter more than price, start here.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Genius Sports (Betgenius) — official data for regulated betting&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: licensed sportsbook operators in regulated markets.&lt;/p&gt;

&lt;p&gt;Genius Sports and its betting division Betgenius position themselves as an official betting data partner to more than 200 rights holders. The company became widely known after winning official live-data betting rights for English and Scottish football in 2019, and it works with governing bodies on the integrity side of the business. Commercial use of official data — including betting and predictive or fantasy games — typically requires a separate data licence.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Official, rights-holder-backed data is the safest legal foundation for a regulated sportsbook.&lt;br&gt;
Built around in-play betting products, not just stats display.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Not self-serve. Expect licensing, contracts and onboarding.&lt;br&gt;
Rights agreements change from cycle to cycle, so always confirm which competitions are currently covered.&lt;br&gt;
Not designed for developers who just want to experiment on a weekend.&lt;/p&gt;

&lt;p&gt;Verdict: the right call when “official data” is a legal or commercial requirement, the wrong call when it isn’t.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stats Perform (Opta) — depth, metrics and in-play&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: football-heavy products, media and broadcast, analytics-driven betting.&lt;/p&gt;

&lt;p&gt;Stats Perform sits behind the Opta brand that fans see on broadcasts, plus RunningBall, its ultra-fast in-play feed collected at the stadium by a global scouting network. It offers Opta data feeds, a Dynamic Stats API and betting-specific data including live expected-goals shot quality. It also announced a role as an official betting data and streaming rights distributor for FIFA tournaments.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Some of the richest event-level football data available commercially.&lt;br&gt;
Advanced metrics (xG and predictive layers) that are hard to rebuild yourself.&lt;br&gt;
Strong credentials in both media and betting.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Demo-and-quote model; there’s no “paste your card and go.”&lt;br&gt;
Premium pricing for premium depth — usually out of scope for small teams.&lt;/p&gt;

&lt;p&gt;Verdict: if your product is judged on the quality of the football analysis, Opta-grade data is worth the conversation.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;SportsDataIO — the US-sports specialist&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: fantasy apps, US sports media, props and betting content built around NFL, NBA, MLB and NHL.&lt;/p&gt;

&lt;p&gt;SportsDataIO is deepest where American sports are concerned: scores, stats, play-by-play, injuries, lineups, depth charts, projections and betting data. Its leagues API spans 13 sports, including NFL, NBA, MLB, NHL, WNBA, college football and basketball, MMA, golf, NASCAR, F1 and soccer, with a separate Global API for far more leagues that is sold through sales.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Fantasy-friendly data: projections, salaries and slates alongside stats.&lt;br&gt;
A free trial with realistic-but-scrambled data, plus a free Replay feature that plays back real historical events in real time — genuinely useful for testing live logic in the off-season.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Pricing varies by sport and volume, so the bill grows with every league you add.&lt;br&gt;
Trial data is scrambled, so you can’t validate real accuracy until you pay.&lt;br&gt;
International coverage depends on the Global API and a sales conversation.&lt;/p&gt;

&lt;p&gt;Verdict: a top pick for US-centric products; less compelling if your users follow cricket, handball or European leagues.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Sportmonks — football-first with broad league reach&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: football apps, fantasy platforms and live-score products that need many leagues without an enterprise contract.&lt;/p&gt;

&lt;p&gt;Sportmonks is a Dutch provider focused on football, with cricket and Formula 1 as additional products. It advertises 2,200–2,500+ football leagues, and its football plans are gated by how many leagues you pick rather than by features — mid-2026 listings show roughly €29/month for 5 leagues, €99 for 30 and €249 for 120, with enterprise pricing for everything. It also offers a free plan covering a couple of leagues and a 14-day trial on paid plans.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Very wide football league coverage, with xG, predictions and lineups available.&lt;br&gt;
Predictable cost if you only need a handful of competitions.&lt;br&gt;
Clean v3 REST design and human support.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;League-gated pricing gets complicated fast as you add competitions; odds and extras can be paid add-ons.&lt;br&gt;
Football is the main product — it’s not a 13-sport platform.&lt;/p&gt;

&lt;p&gt;Verdict: an excellent default if football is your product.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Orbistats — 13 sports, one schema, every delivery method&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: teams that want mainstream multi-sport coverage — including cricket, esports, combat sports and horse racing — behind one consistent API, and want REST, WebSocket, webhooks and drop-in widgets from the same account.&lt;/p&gt;

&lt;p&gt;This is us, so we’ll be both specific and candid. Orbistats covers 13 sports: football, basketball, American football, cricket, tennis, baseball, esports, combat sports, volleyball, handball, ice hockey, golf and horse racing. The platform is organised around a few products — the Sports Data API for fixtures, results, standings and teams; the Live Scores API for real-time events; the Odds API for pre-match and live odds normalised across bookmakers; and the Historical Data API built for backtesting. You can consume it via REST, the WebSocket API for persistent streaming, webhooks for push delivery, or embeddable widgets.&lt;/p&gt;

&lt;p&gt;What the pricing looks like. Orbistats sells access windows rather than monthly seat plans, and every tier includes all sports and endpoints. At the time of writing, the site lists Free (€0, 1 hour), Starter (€19, 24 hours), Growth (€79, 5 days) and Unlimited (€1,999/month, 30 days of unlimited usage). Your timer starts only when you open the activation link we email you after your access request is approved. See the live pricing page for current numbers.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Genuinely broad sport coverage on every tier, including sports many cheaper APIs skip.&lt;br&gt;
Four ways to consume the same feed, so you can start with REST and add streaming later without switching vendors.&lt;br&gt;
A public documentation, quickstart and sandbox so you can see real responses before you commit.&lt;/p&gt;

&lt;p&gt;Watch-outs (the honest list)&lt;/p&gt;

&lt;p&gt;We’re a younger provider with “mainstream coverage,” not a rights-holder-backed official data licensor. If your regulator or your contract demands official data, choose Sportradar or Genius Sports.&lt;br&gt;
Access is approval-based and time-windowed, which is great for sprints and evaluations, but you should confirm production terms and SLAs with the team before building a business on it.&lt;br&gt;
Our sub-50ms WebSocket figure is our own published claim. Treat it — and everyone else’s latency claim — as a hypothesis until you run the benchmark below.&lt;/p&gt;

&lt;p&gt;Verdict: a strong fit for startups, analytics teams and media products that want many sports and several delivery methods without an enterprise contract, and a poor fit if official-data licensing is non-negotiable. If cricket is your priority, start with the cricket coverage page.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;API-Sports — the cheapest way to start&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: prototypes, student projects, MVPs and apps where budget beats depth.&lt;/p&gt;

&lt;p&gt;API-Sports runs a family of single-sport APIs (API-Football, API-NBA and others). The free plan gives around 100 requests per day per API, and paid plans typically start in the low tens of dollars per month. It also offers free embeddable widgets.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Excellent free tier and the lowest cost of entry on this list.&lt;br&gt;
Large community, plenty of tutorials and wrappers.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Each sport is its own API and plan, so costs and integration work multiply as you add sports.&lt;br&gt;
Check statistics depth per league before launch; some lower leagues return fixtures but thinner match and player stats.&lt;br&gt;
Fine for an MVP, but test uptime and support carefully before you scale on it.&lt;/p&gt;

&lt;p&gt;Verdict: the best “learn it and ship a prototype this weekend” option.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The Odds API — odds, simply&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: odds comparison pages, hobby tools and indie projects.&lt;/p&gt;

&lt;p&gt;The Odds API has been running since 2017 and focuses on one job: betting odds. It covers 70+ sports and 40+ bookmakers across the US, UK, EU and Australia, with a free tier (500 credits a month), historical odds snapshots back to 2020, and paid plans from about $30 up to roughly $249 a month on a credit-based model.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Clean, well-regarded documentation and a gentle pricing curve.&lt;br&gt;
Strong on US books and mainstream leagues.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;It’s odds only — no deep stats, lineups or play-by-play.&lt;br&gt;
Credit-based pricing needs watching when you poll frequently.&lt;br&gt;
Not aimed at long-tail or Asian-market bookmaker depth.&lt;/p&gt;

&lt;p&gt;Verdict: the safe, simple choice when odds are the entire product.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Odds-API.io — bookmaker breadth&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: odds screeners, arbitrage and value-betting tools, and comparison sites that need many bookmakers.&lt;/p&gt;

&lt;p&gt;Odds-API.io advertises 250+ bookmakers, thousands of leagues, pre-match and live odds, 100+ market types and both REST and WebSocket delivery. All paid plans share the same rate limit (5,000 requests per hour); tiers differ mainly by how many bookmakers you can access, and there’s a free tier with a limited bookmaker selection.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Wide bookmaker coverage, including sharper and Asian books.&lt;br&gt;
Simple, rate-limit-based pricing.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;Odds only — pair it with a stats provider if you need fixtures, lineups or events.&lt;br&gt;
Most of the bookmaker and league numbers are the vendor’s own, so verify the books you care about.&lt;/p&gt;

&lt;p&gt;Verdict: a good specialist for odds-heavy products.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;LSports — operator-grade odds and sports feeds&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Best for: betting operators and trading teams that want many sports and bookmakers through a single commercial relationship.&lt;/p&gt;

&lt;p&gt;LSports sells betting-oriented data products; its OddService is marketed as covering 100+ sports and bookmakers, with custom, quote-based pricing. It sits in the same “talk to sales” tier as the enterprise providers, but with a stronger odds-and-trading focus than a general sports-data focus.&lt;/p&gt;

&lt;p&gt;Strengths&lt;/p&gt;

&lt;p&gt;Built for operators and trading rather than simple display apps.&lt;br&gt;
Broad sport and market coverage.&lt;/p&gt;

&lt;p&gt;Watch-outs&lt;/p&gt;

&lt;p&gt;No public price list, and coverage claims need to be validated in a trial.&lt;br&gt;
Not the right shape for a small team that wants to self-serve.&lt;/p&gt;

&lt;p&gt;Verdict: worth a call if you’re running a betting product at volume and want an alternative to the biggest names.&lt;/p&gt;

&lt;p&gt;Which provider should you actually pick?&lt;/p&gt;

&lt;p&gt;Skip the ranking for a minute and match your situation:&lt;/p&gt;

&lt;p&gt;You’re a regulated sportsbook: start with Sportradar or Genius Sports and confirm official-data coverage for your leagues.&lt;br&gt;
You’re building a football product: shortlist Sportmonks and Stats Perform; use API-Sports to prototype.&lt;br&gt;
You’re building for US sports and fantasy: SportsDataIO first, Sportradar if you need more depth.&lt;br&gt;
You need many sports behind one schema, plus streaming: Sportradar at the high end, Orbistats if you want multi-sport coverage and four delivery methods without an enterprise contract.&lt;br&gt;
You only need odds: The Odds API for simplicity, Odds-API.io for bookmaker breadth, LSports for operator-scale.&lt;br&gt;
You’re just learning: API-Sports or a free tier from Sportmonks.&lt;/p&gt;

&lt;p&gt;If you’re comparing providers head-to-head, Orbistats also publishes a comparison hub that goes into more detail on specific alternatives.&lt;/p&gt;

&lt;p&gt;Test any provider yourself in 15 minutes&lt;/p&gt;

&lt;p&gt;Marketing pages tell you what a provider wants you to believe. A quick benchmark tells you what happens from your servers. This script (Node 20+, no dependencies) hits each provider’s live-match endpoint 30 times and reports success rate plus p50 and p95 round-trip latency:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// benchmark.mjs — run with: node benchmark.mjs&lt;br&gt;
const RUNS = 30;&lt;/p&gt;

&lt;p&gt;const PROVIDERS = [&lt;br&gt;
  {&lt;br&gt;
    name: "orbistats",&lt;br&gt;
    url: "&lt;a href="https://api.orbistats.com/v1/football/matches/live" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/football/matches/live&lt;/a&gt;",&lt;br&gt;
    headers: { Authorization: &lt;code&gt;Bearer ${process.env.ORBISTATS_KEY}&lt;/code&gt; },&lt;br&gt;
  },&lt;br&gt;
  // Replace the placeholders below with the endpoint + auth of each provider you're testing&lt;br&gt;
  {&lt;br&gt;
    name: "provider-b",&lt;br&gt;
    url: "&lt;a href="https://api.provider-b.example/live" rel="noopener noreferrer"&gt;https://api.provider-b.example/live&lt;/a&gt;",&lt;br&gt;
    headers: { "x-api-key": process.env.PROVIDER_B_KEY },&lt;br&gt;
  },&lt;br&gt;
];&lt;/p&gt;

&lt;p&gt;const percentile = (values, p) =&amp;gt; {&lt;br&gt;
  const sorted = [...values].sort((a, b) =&amp;gt; a - b);&lt;br&gt;
  return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))];&lt;br&gt;
};&lt;/p&gt;

&lt;p&gt;async function probe({ name, url, headers }) {&lt;br&gt;
  const times = [];&lt;br&gt;
  let ok = 0;&lt;/p&gt;

&lt;p&gt;for (let i = 0; i &amp;lt; RUNS; i++) {&lt;br&gt;
    const start = performance.now();&lt;br&gt;
    try {&lt;br&gt;
      const res = await fetch(url, { headers });&lt;br&gt;
      await res.json();            // include parse time, like a real client&lt;br&gt;
      if (res.ok) ok++;&lt;br&gt;
    } catch {&lt;br&gt;
      /* network error counts as a failure */&lt;br&gt;
    }&lt;br&gt;
    times.push(performance.now() - start);&lt;br&gt;
    await new Promise((r) =&amp;gt; setTimeout(r, 500)); // be polite, avoid rate limits&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;return {&lt;br&gt;
    provider: name,&lt;br&gt;
    success: &lt;code&gt;${ok}/${RUNS}&lt;/code&gt;,&lt;br&gt;
    p50_ms: Math.round(percentile(times, 50)),&lt;br&gt;
    p95_ms: Math.round(percentile(times, 95)),&lt;br&gt;
  };&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;console.table(await Promise.all(PROVIDERS.map(probe)));&lt;/p&gt;

&lt;p&gt;Two honest caveats. First, this measures round-trip API latency from your machine, not the end-to-end delay between a goal being scored and the feed reporting it — for that you need to compare timestamps against a trusted live source during a real match. Second, run it from the region where your production servers will live, not from your laptop on café Wi-Fi.&lt;/p&gt;

&lt;p&gt;Don’t marry one provider: use an adapter&lt;/p&gt;

&lt;p&gt;Whichever provider you choose, the safest architecture is one that makes switching boring. Define your own match shape and write one tiny adapter per provider:&lt;/p&gt;

&lt;p&gt;ts&lt;br&gt;
// types.ts&lt;br&gt;
export interface LiveMatch {&lt;br&gt;
  id: string;&lt;br&gt;
  status: "scheduled" | "live" | "finished";&lt;br&gt;
  minute: number | null;&lt;br&gt;
  home: { name: string; score: number };&lt;br&gt;
  away: { name: string; score: number };&lt;br&gt;
  source: string;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// adapters/orbistats.ts — maps the documented live-match payload to our shape&lt;br&gt;
export const fromOrbistats = (raw: any): LiveMatch =&amp;gt; ({&lt;br&gt;
  id: raw.match_id,&lt;br&gt;
  status: raw.status,            // e.g. "live"&lt;br&gt;
  minute: raw.minute ?? null,&lt;br&gt;
  home: { name: raw.home.name, score: raw.home.score },&lt;br&gt;
  away: { name: raw.away.name, score: raw.away.score },&lt;br&gt;
  source: "orbistats",&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;// adapters/providerB.ts — same output, different input&lt;br&gt;
export const fromProviderB = (raw: any): LiveMatch =&amp;gt; ({&lt;br&gt;
  id: String(raw.fixture.id),&lt;br&gt;
  status: raw.fixture.state === "FT" ? "finished" : "live",&lt;br&gt;
  minute: raw.fixture.elapsed ?? null,&lt;br&gt;
  home: { name: raw.teams.home, score: raw.goals.home },&lt;br&gt;
  away: { name: raw.teams.away, score: raw.goals.away },&lt;br&gt;
  source: "provider-b",&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Your UI, database and alerting only ever see LiveMatch. When you outgrow a provider — or need a second one as a fallback during a big match — you add an adapter instead of rewriting your app.&lt;/p&gt;

&lt;p&gt;If you’d rather skip building the normalisation layer yourself for odds and stats across many sports, that’s exactly the problem a multi-sport API with a single schema is meant to solve. The Orbistats quickstart shows the full flow from request to first response, and the sandbox lets you try endpoints before you commit.&lt;/p&gt;

&lt;p&gt;Seven questions to ask every provider before you sign&lt;br&gt;
Which exact leagues and competitions are covered, and at what coverage level (scores only, or full events and lineups)?&lt;br&gt;
Is the data official or licensed for betting use? If you’re regulated, get this in writing.&lt;br&gt;
What’s the real latency, and how is it measured — API response time or event-to-delivery time?&lt;br&gt;
What are the rate limits and what happens when you exceed them — throttling, overage fees or a blocked key?&lt;br&gt;
Do you get WebSocket or webhooks, or only polling? Polling a live match every few seconds burns quota fast.&lt;br&gt;
How deep and how clean is the history? Backtesting a model on patchy history gives you confident wrong answers.&lt;br&gt;
What does the exit look like? Can you export data, and how hard is it to switch if prices rise?&lt;br&gt;
Common mistakes teams make when choosing a data provider&lt;br&gt;
Buying coverage you’ll never use. A 90-sport feed is no help if 95% of your traffic is cricket and football.&lt;br&gt;
Ignoring licensing until launch. Official-data requirements can kill a product late in the game.&lt;br&gt;
Trusting the free tier as a preview of production. Scrambled trial data, small quotas and short access windows don’t always reflect real-world behaviour.&lt;br&gt;
Polling instead of streaming. For live data, a persistent connection or webhook is cheaper and faster than hammering REST endpoints.&lt;br&gt;
Skipping the abstraction layer. Hard-coding one vendor’s schema into your database is a bill you pay later.&lt;br&gt;
FAQ&lt;br&gt;
What is the best sports data provider in 2026?&lt;/p&gt;

&lt;p&gt;There isn’t one winner. Sportradar and Genius Sports lead on official, enterprise-grade data; Stats Perform leads on football depth; SportsDataIO leads on US sports; Sportmonks is a strong football-first choice; and API-Sports or The Odds API are the cheapest places to start. The best provider is the one that covers your sports with the licensing and latency your product needs.&lt;/p&gt;

&lt;p&gt;What’s the cheapest sports data API?&lt;/p&gt;

&lt;p&gt;For football and basketball prototypes, API-Sports and Sportmonks’ free plan are the usual starting points, and The Odds API has a free monthly credit allowance for odds. For multi-sport evaluation, Orbistats offers a free one-hour access window across all sports and endpoints, with paid windows starting at €19. “Cheapest” depends on volume, so model your real request count before deciding.&lt;/p&gt;

&lt;p&gt;Do I need official data for a betting app?&lt;/p&gt;

&lt;p&gt;If you operate as a licensed sportsbook in a regulated market, usually yes — or at least data sourced through rights-holder-approved channels. Providers such as Genius Sports and Sportradar specialise in this. For odds-comparison tools, fantasy apps and analytics, licensed-official data is often not required, but check your local regulations and your contracts.&lt;/p&gt;

&lt;p&gt;REST, WebSocket or webhooks — which should I use?&lt;/p&gt;

&lt;p&gt;Use REST for fixtures, standings, stats and history. Use WebSocket for live scores and odds when you need continuous updates in the browser or a trading service. Use webhooks when you’d rather have events pushed to your server than hold a connection open. Providers that offer all three, like Orbistats, let you mix them as your product grows.&lt;/p&gt;

&lt;p&gt;How should I compare providers fairly?&lt;/p&gt;

&lt;p&gt;Pick two or three candidates, define a fixed test (the same match, the same endpoints, the same region), run the benchmark script above, and compare coverage on your specific leagues — not the vendor’s headline numbers.&lt;/p&gt;

&lt;p&gt;Final thoughts&lt;/p&gt;

&lt;p&gt;The right sports data provider isn’t the biggest, the cheapest or the one with the loudest marketing page. It’s the one whose coverage, licensing, latency and pricing model match the product you’re actually building — and that you can replace without a rewrite when your needs change.&lt;/p&gt;

&lt;p&gt;If you want to see how a multi-sport, multi-delivery API feels in practice, request access to Orbistats, read the documentation, or open the live feed on the homepage and run your first request. And if you’ve used any of the providers above in production, tell us in the comments where we got it wrong — we’ll update this guide.&lt;/p&gt;

</description>
      <category>api</category>
      <category>webdev</category>
      <category>backend</category>
      <category>datascience</category>
    </item>
    <item>
      <title>How to Evaluate a Sports Data API: A Developer’s Checklist (Benchmark Script Included)</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Mon, 26 Oct 2026 04:25:43 +0000</pubDate>
      <link>https://dev.to/orbistats/how-to-evaluate-a-sports-data-api-a-developers-checklist-benchmark-script-included-27bd</link>
      <guid>https://dev.to/orbistats/how-to-evaluate-a-sports-data-api-a-developers-checklist-benchmark-script-included-27bd</guid>
      <description>&lt;p&gt;Disclosure: I work on Orbistats, a sports data API, and it is used as one example below. The checklist and scripts work with any provider.&lt;/p&gt;

&lt;p&gt;Picking a sports data API usually goes like this: you read ten landing pages that all say “real-time, reliable, comprehensive,” sign up for two or three, and choose whichever one you got working first. Six months later you discover the cricket data lags, the odds schema changed without notice, or the rate limits do not fit your traffic.&lt;/p&gt;

&lt;p&gt;This post gives you a repeatable way to compare providers using numbers instead of marketing. You will get:&lt;/p&gt;

&lt;p&gt;A checklist of what to evaluate and why&lt;br&gt;
A Python benchmark script that measures latency and reliability&lt;br&gt;
A provider-agnostic client so switching providers later is a config change, not a rewrite&lt;br&gt;
A results template you can fill in for your own shortlist&lt;br&gt;
Why free tiers are the right place to start&lt;/p&gt;

&lt;p&gt;Free tiers are the cheapest way to test real endpoints. But they differ a lot in shape, and that matters when you compare:&lt;/p&gt;

&lt;p&gt;Some give a daily request cap.&lt;br&gt;
Some give limited sports or endpoints.&lt;br&gt;
Some give a time-boxed window. Orbistats’ Free plan, for example, is 1 hour of access across all sports and endpoints with no card, and the timer starts only when you open the activation link.&lt;/p&gt;

&lt;p&gt;A 1-hour window means you should prepare your test script before you activate. The script below is built for that.&lt;/p&gt;

&lt;p&gt;Part 1: The developer’s checklist&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Coverage: sports, leagues and depth&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Do not just count sports. Check the exact leagues and markets you need. A provider can list “cricket” and still lack the domestic tournaments your users care about.&lt;/p&gt;

&lt;p&gt;Orbistats covers 13 sports, including football, cricket and tennis. Whichever provider you test, pick three leagues you actually need and check them one by one.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Latency, measured from your own server&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Marketing pages quote best-case numbers from the provider’s network. Measure from where your code runs. Track p50 and p95, not just the average, because p95 is what your users feel on a bad day.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reliability&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Over a fixed number of requests, what percentage succeed? Which errors appear (429, 500, timeouts)? Is there a public status page with history?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Delivery methods&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;REST alone is fine for fixtures and standings. For live products, check whether the provider offers a WebSocket API for streaming and webhooks for push events, so you are not polling every second.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Schema quality and stability&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Look for consistent field names across sports, stable IDs, ISO timestamps and typed values. Then read the changelog to see how often things break. Also check the versioning policy: Orbistats uses /v1/ and moves breaking changes to a new version.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Odds normalization (if you need odds)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you consume prices from multiple bookmakers, check whether the Odds API normalizes formats and market names. Otherwise you will write that mapping layer yourself.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Historical depth&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;For modeling, check historical data for opening and closing odds, event data and how far back each sport goes. Verify coverage per sport rather than assuming it is uniform.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pricing transparency&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Can you see a number without a sales call? Does the plan structure match how you will actually use it (access window, request cap, monthly)? Compare against the pricing page and the provider comparison pages.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Developer experience&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Time yourself: from signup to first successful response. A good quickstart, a sandbox and clear documentation can save days.&lt;/p&gt;

&lt;p&gt;Part 2: The benchmark script&lt;/p&gt;

&lt;p&gt;This script sends a fixed number of requests to any endpoint, measures latency, records status codes and checks that the response contains the fields you expect. It uses httpx and runs requests concurrently in small batches to avoid tripping rate limits.&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
pip install httpx&lt;br&gt;
python&lt;br&gt;
import asyncio&lt;br&gt;
import statistics&lt;br&gt;
import time&lt;br&gt;
from collections import Counter&lt;br&gt;
from dataclasses import dataclass, field&lt;/p&gt;

&lt;p&gt;import httpx&lt;/p&gt;

&lt;p&gt;@dataclass&lt;br&gt;
class Target:&lt;br&gt;
    name: str&lt;br&gt;
    url: str&lt;br&gt;
    headers: dict = field(default_factory=dict)&lt;br&gt;
    required_fields: list[str] = field(default_factory=list)&lt;/p&gt;

&lt;p&gt;def has_fields(payload, required: list[str]) -&amp;gt; bool:&lt;br&gt;
    """Check that required top-level keys exist (or exist in the first item of a list)."""&lt;br&gt;
    if isinstance(payload, list):&lt;br&gt;
        payload = payload[0] if payload else {}&lt;br&gt;
    if isinstance(payload, dict) and "data" in payload:&lt;br&gt;
        inner = payload["data"]&lt;br&gt;
        payload = inner[0] if isinstance(inner, list) and inner else inner&lt;br&gt;
    return isinstance(payload, dict) and all(k in payload for k in required)&lt;/p&gt;

&lt;p&gt;async def one_request(client: httpx.AsyncClient, target: Target):&lt;br&gt;
    start = time.perf_counter()&lt;br&gt;
    try:&lt;br&gt;
        r = await client.get(target.url, headers=target.headers, timeout=10)&lt;br&gt;
        elapsed_ms = (time.perf_counter() - start) * 1000&lt;br&gt;
        schema_ok = False&lt;br&gt;
        if r.status_code == 200:&lt;br&gt;
            try:&lt;br&gt;
                schema_ok = has_fields(r.json(), target.required_fields)&lt;br&gt;
            except ValueError:&lt;br&gt;
                pass&lt;br&gt;
        return elapsed_ms, r.status_code, schema_ok&lt;br&gt;
    except httpx.HTTPError:&lt;br&gt;
        return (time.perf_counter() - start) * 1000, "timeout/error", False&lt;/p&gt;

&lt;p&gt;async def benchmark(target: Target, total=50, batch=5, pause=0.5):&lt;br&gt;
    results = []&lt;br&gt;
    async with httpx.AsyncClient() as client:&lt;br&gt;
        for _ in range(total // batch):&lt;br&gt;
            results += await asyncio.gather(&lt;br&gt;
                *[one_request(client, target) for _ in range(batch)]&lt;br&gt;
            )&lt;br&gt;
            await asyncio.sleep(pause)  # be polite to free tiers&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;latencies = sorted(r[0] for r in results if r[1] == 200)
statuses = Counter(r[1] for r in results)
ok = statuses.get(200, 0)

def pct(p):
    return latencies[min(int(len(latencies) * p), len(latencies) - 1)] if latencies else None

return {
    "provider": target.name,
    "requests": total,
    "success_rate": round(100 * ok / total, 1),
    "p50_ms": round(pct(0.50), 1) if latencies else None,
    "p95_ms": round(pct(0.95), 1) if latencies else None,
    "mean_ms": round(statistics.mean(latencies), 1) if latencies else None,
    "schema_ok_pct": round(100 * sum(r[2] for r in results) / total, 1),
    "status_codes": dict(statuses),
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;async def main():&lt;br&gt;
    targets = [&lt;br&gt;
        Target(&lt;br&gt;
            name="Orbistats",&lt;br&gt;
            url="&lt;a href="https://api.orbistats.com/v1/football/matches/live" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/football/matches/live&lt;/a&gt;",&lt;br&gt;
            headers={"Authorization": "Bearer YOUR_API_KEY"},&lt;br&gt;
            required_fields=["match_id", "status"],&lt;br&gt;
        ),&lt;br&gt;
        # Add up to 9 more providers here, using each one's own URL and auth.&lt;br&gt;
    ]&lt;br&gt;
    for t in targets:&lt;br&gt;
        print(await benchmark(t))&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    asyncio.run(main())&lt;/p&gt;

&lt;p&gt;Notes on running it fairly:&lt;/p&gt;

&lt;p&gt;Run from the same machine and network for every provider.&lt;br&gt;
Run at different times of day, including during live matches, because latency under load is what matters.&lt;br&gt;
Use the same type of endpoint for each provider (for example, live football matches).&lt;br&gt;
Check each provider’s terms before benchmarking. Keep request counts modest on free tiers.&lt;br&gt;
Adjust required_fields to match each provider’s actual response shape. The Orbistats example uses match_id and status, which appear in the live response.&lt;br&gt;
Part 3: A provider-agnostic client&lt;/p&gt;

&lt;p&gt;Once you pick a provider, you do not want it to leak into your whole codebase. Define your own model and write one small adapter per provider.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from abc import ABC, abstractmethod&lt;br&gt;
from dataclasses import dataclass&lt;/p&gt;

&lt;p&gt;import httpx&lt;/p&gt;

&lt;p&gt;@dataclass&lt;br&gt;
class LiveMatch:&lt;br&gt;
    match_id: str&lt;br&gt;
    status: str&lt;br&gt;
    minute: int | None&lt;br&gt;
    home_name: str&lt;br&gt;
    home_score: int&lt;br&gt;
    away_name: str&lt;br&gt;
    away_score: int&lt;/p&gt;

&lt;p&gt;class SportsProvider(ABC):&lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/abstractmethod"&gt;@abstractmethod&lt;/a&gt;&lt;br&gt;
    def live_matches(self, sport: str) -&amp;gt; list[LiveMatch]: ...&lt;/p&gt;

&lt;p&gt;class OrbistatsProvider(SportsProvider):&lt;br&gt;
    BASE = "&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;"&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __init__(self, api_key: str):
    self.client = httpx.Client(
        headers={"Authorization": f"Bearer {api_key}"}, timeout=10
    )

def live_matches(self, sport: str) -&amp;gt; list[LiveMatch]:
    r = self.client.get(f"{self.BASE}/{sport}/matches/live")
    r.raise_for_status()
    data = r.json()
    items = data if isinstance(data, list) else data.get("data", [data])
    return [
        LiveMatch(
            match_id=m["match_id"],
            status=m["status"],
            minute=m.get("minute"),
            home_name=m["home"]["name"],
            home_score=m["home"]["score"],
            away_name=m["away"]["name"],
            away_score=m["away"]["score"],
        )
        for m in items
    ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def get_provider(name: str, api_key: str) -&amp;gt; SportsProvider:&lt;br&gt;
    providers = {"orbistats": OrbistatsProvider}&lt;br&gt;
    return providers&lt;a href="https://dev.toapi_key"&gt;name&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To add another provider, write one more class that maps its response into LiveMatch. Your app only ever talks to SportsProvider, so switching is a one-line config change. It also lets you run two providers side by side and compare their output during a trial.&lt;/p&gt;

</description>
      <category>api</category>
      <category>python</category>
      <category>sportsdata</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
