<?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>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>
    <item>
      <title>How to Evaluate a Sports Data API: A Developer’s Checklist (Checked Against 10 Providers)</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Mon, 12 Oct 2026 03:33:39 +0000</pubDate>
      <link>https://dev.to/orbistats/how-to-evaluate-a-sports-data-api-a-developers-checklist-checked-against-10-providers-4pd9</link>
      <guid>https://dev.to/orbistats/how-to-evaluate-a-sports-data-api-a-developers-checklist-checked-against-10-providers-4pd9</guid>
      <description>&lt;p&gt;Why a checklist beats a feature table&lt;/p&gt;

&lt;p&gt;Every sports data vendor has a feature table, and most of them look alike: live scores, odds, history, WebSocket. The differences that hurt you in production are not on the table. They are things like unstable IDs, inconsistent timestamps, a quota that counts differently from what you assumed, or a licence that forbids the exact use you planned.&lt;/p&gt;

&lt;p&gt;So this post gives you a checklist you can run against any provider, plus a small Python script that automates the checks that can be automated. Use it before you sign a contract, during a trial, and again every time you reconsider your vendor.&lt;/p&gt;

&lt;p&gt;Read this first: I work with Orbistats, which is one of the ten providers I reference. I have not run benchmarks, so there are no performance numbers here. Vendor facts come from public pages as of 12 October 2026 and may change, so verify them before relying on them.&lt;/p&gt;

&lt;p&gt;The ten providers this checklist was built around&lt;/p&gt;

&lt;p&gt;The list covers the whole market, from enterprise licences to hobby-friendly free tiers:&lt;/p&gt;

&lt;p&gt;Sportradar: enterprise, quote-based, claims 80+ sports and 500+ leagues.&lt;br&gt;
Stats Perform (Opta): premium analytics depth, tailored licensing.&lt;br&gt;
Genius Sports: official data and integrity, custom quote.&lt;br&gt;
Sportmonks: self-serve football, €29, €99 and €249 per month plans.&lt;br&gt;
SportsDataIO: US leagues and fantasy, product-specific pricing.&lt;br&gt;
Orbistats: 13 sports, odds, WebSocket, webhooks, history, pass-based pricing.&lt;br&gt;
OddsPapi: odds-focused, details unverified.&lt;br&gt;
SportsGameOdds: odds-first, billed by returned objects.&lt;br&gt;
API-Football: football only, billed by daily requests.&lt;br&gt;
The Odds API: odds, quota scoped by sport, market and region.&lt;br&gt;
How to use the checklist&lt;/p&gt;

&lt;p&gt;Score each question as pass, fail or unknown. Unknown is a legitimate answer: it means ask the vendor, in writing, before you commit. Weight the sections by your product. A sportsbook cares most about rights and latency, a hobby app about price and ease of start, a machine-learning team about history.&lt;/p&gt;

&lt;p&gt;Section 1: Coverage&lt;br&gt;
Does it cover every sport you need, today and in your next two roadmap quarters?&lt;br&gt;
Does it cover the exact leagues and competitions, not just the sport?&lt;br&gt;
Are lower divisions, youth and women’s competitions included if you need them?&lt;br&gt;
Is coverage depth the same for all leagues, or do some only have scores without events and stats?&lt;br&gt;
Is there a written coverage matrix you can keep, not just a marketing claim?&lt;/p&gt;

&lt;p&gt;Vendors describe coverage differently: Sportradar claims 80+ sports, Sportmonks advertises 2,200+ football leagues, API-Football lists 1,248 leagues and cups, and Orbistats lists 13 sports. These are company claims. A big number tells you little until you check your own competitions. Orbistats, for example, has a page per sport, such as football, cricket, tennis and basketball, and its thirteen sports are football, basketball, American football, cricket, tennis, baseball, esports, combat sports, volleyball, handball, ice hockey, golf and horse racing.&lt;/p&gt;

&lt;p&gt;Section 2: Rights and licensing&lt;br&gt;
Are you allowed to display the data publicly?&lt;br&gt;
Are you allowed to redistribute it to your own customers?&lt;br&gt;
Is betting use permitted, and in which territories?&lt;br&gt;
Are derived metrics and models trained on the data covered?&lt;br&gt;
Is the data official or licensed, and from whom?&lt;br&gt;
What happens to your rights if you cancel?&lt;/p&gt;

&lt;p&gt;This section is the one developers skip and later regret. Enterprise vendors such as Sportradar, Stats Perform and Genius Sports sell on rights as much as on data, which is why their pricing is quote-based. Self-serve vendors publish prices, but you still need to read the terms. For Orbistats, check its data licensing and terms pages for your exact use.&lt;/p&gt;

&lt;p&gt;Section 3: Pricing model&lt;br&gt;
What is actually metered: requests, objects, leagues, or time?&lt;br&gt;
What counts as one unit? A single call, a returned event, a market?&lt;br&gt;
What are the per-minute limits on top of the daily or monthly quota?&lt;br&gt;
Which features are add-ons: odds, xG, predictions, history?&lt;br&gt;
What is the price jump between plan tiers?&lt;br&gt;
What happens when you exceed the limit: throttle, error or overage bill?&lt;/p&gt;

&lt;p&gt;The same price can mean very different things. API-Football meters daily requests, SportsGameOdds meters returned objects, Sportmonks meters leagues, and Orbistats sells time-window passes: Free is €0 for 1 hour, Starter €19 for 24 hours, Growth €79 for 5 days, and Unlimited €1,999 per month for 30 days, all with every sport and endpoint, per its pricing page. Always translate the price into your own expected usage before comparing.&lt;/p&gt;

&lt;p&gt;Section 4: Technical quality&lt;br&gt;
Is there a documented, versioned API, and what is the policy for breaking changes?&lt;br&gt;
Are IDs for matches, teams and players stable over time?&lt;br&gt;
Are timestamps ISO 8601 with an explicit timezone?&lt;br&gt;
Are errors returned in a consistent, documented format?&lt;br&gt;
Is pagination documented and consistent?&lt;br&gt;
Are rate-limit headers returned so you can self-throttle?&lt;br&gt;
Is there a sandbox or test environment?&lt;br&gt;
Are there SDKs and examples in your language?&lt;/p&gt;

&lt;p&gt;On versioning, Orbistats documents a /v1/ base and says breaking changes would ship under a new version such as /v2/, with non-breaking fields added to the current one, per its documentation. It also lists a changelog, SDKs, examples and a sandbox. Whatever vendor you consider, ask for the equivalent.&lt;/p&gt;

&lt;p&gt;Section 5: Delivery methods&lt;br&gt;
Is REST enough, or do you need WebSocket or webhooks for live data?&lt;br&gt;
Do WebSocket connections reconnect cleanly and resume without gaps?&lt;br&gt;
Are webhooks signed, retried and idempotent?&lt;br&gt;
What is the published latency, and how is it measured?&lt;br&gt;
Is push available on the plan you will actually pay for?&lt;/p&gt;

&lt;p&gt;Orbistats lists a WebSocket API, where the company cites sub-50ms, and webhooks, plus drop-in widgets. Treat any latency figure as a claim to measure yourself, not a fact. SportsGameOdds lists WebSocket for higher tiers, and Sportradar offers push on selected packages. Never assume a transport exists on your plan.&lt;/p&gt;

&lt;p&gt;Section 6: Odds&lt;br&gt;
Which bookmakers and markets are covered, and can you get a written list?&lt;br&gt;
Are odds normalised into one schema across bookmakers?&lt;br&gt;
Are odds decimal, American or fractional, and can you choose?&lt;br&gt;
Is line movement history available?&lt;br&gt;
Are closing odds stored for backtesting?&lt;br&gt;
How fresh is the live odds refresh?&lt;/p&gt;

&lt;p&gt;The Orbistats Odds API advertises pre-match and live odds normalised across bookmakers, including 1X2, moneyline, spreads, totals and props. The odds-first vendors, SportsGameOdds, OddsPapi and The Odds API, compete mainly on this section, so test them hardest here.&lt;/p&gt;

&lt;p&gt;Section 7: History&lt;br&gt;
How many seasons are available, per sport, not just overall?&lt;br&gt;
Does history include lineups, events and statistics, or only results?&lt;br&gt;
Are historical odds and closing odds included?&lt;br&gt;
Can you bulk export, or only page through an API?&lt;br&gt;
Is history included in your plan or a paid add-on?&lt;/p&gt;

&lt;p&gt;Orbistats describes a Historical Data API and says some seasons go back to 2010. Check retention for your specific sport and competition. Sportmonks notes that older history can be an add-on on some plans.&lt;/p&gt;

&lt;p&gt;Section 8: Reliability and support&lt;br&gt;
Is there a public status page?&lt;br&gt;
Is there an SLA, and what are the remedies?&lt;br&gt;
What are the support channels and response times?&lt;br&gt;
Is there a public changelog for incidents and changes?&lt;br&gt;
How does the vendor communicate deprecations?&lt;/p&gt;

&lt;p&gt;Orbistats links a public status page. For any vendor, compare the status page against your own monitoring over time rather than trusting either alone.&lt;/p&gt;

&lt;p&gt;Automate what you can: a checklist script&lt;/p&gt;

&lt;p&gt;Some checks are mechanical. This script tests six of them against any endpoint: does it reject a missing key, does it return a JSON content type, are timestamps ISO 8601, are IDs stable across calls, does it expose rate-limit headers, and does it respond within a time limit.&lt;/p&gt;

&lt;p&gt;Install the dependency:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
pip install requests&lt;/p&gt;

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

&lt;p&gt;python&lt;br&gt;
import json&lt;br&gt;
import re&lt;br&gt;
import sys&lt;br&gt;
import time&lt;br&gt;
import requests&lt;/p&gt;

&lt;p&gt;ISO_8601 = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(.\d+)?(Z|[+-]\d{2}:?\d{2})$")&lt;/p&gt;

&lt;p&gt;def walk(obj, path=""):&lt;br&gt;
    if isinstance(obj, dict):&lt;br&gt;
        for key, value in obj.items():&lt;br&gt;
            yield from walk(value, path + "." + key)&lt;br&gt;
    elif isinstance(obj, list):&lt;br&gt;
        for item in obj[:20]:&lt;br&gt;
            yield from walk(item, path + "[]")&lt;br&gt;
    else:&lt;br&gt;
        yield path, obj&lt;/p&gt;

&lt;p&gt;def check_rejects_missing_key(url, params):&lt;br&gt;
    r = requests.get(url, params=params, timeout=10)&lt;br&gt;
    return r.status_code in (401, 403), "status " + str(r.status_code) + " without credentials"&lt;/p&gt;

&lt;p&gt;def check_json_content_type(response):&lt;br&gt;
    kind = response.headers.get("Content-Type", "")&lt;br&gt;
    return "json" in kind.lower(), kind or "no Content-Type header"&lt;/p&gt;

&lt;p&gt;def check_iso_timestamps(data):&lt;br&gt;
    bad = []&lt;br&gt;
    seen = 0&lt;br&gt;
    for path, value in walk(data):&lt;br&gt;
        name = path.split(".")[-1].lower()&lt;br&gt;
        if isinstance(value, str) and any(word in name for word in ("time", "date", "at")):&lt;br&gt;
            seen += 1&lt;br&gt;
            if not ISO_8601.match(value):&lt;br&gt;
                bad.append(path + "=" + value)&lt;br&gt;
    if seen == 0:&lt;br&gt;
        return None, "no timestamp-like fields found"&lt;br&gt;
    return len(bad) == 0, "bad examples: " + str(bad[:3]) if bad else str(seen) + " fields look ISO 8601"&lt;/p&gt;

&lt;p&gt;def collect_ids(data):&lt;br&gt;
    ids = set()&lt;br&gt;
    for path, value in walk(data):&lt;br&gt;
        if path.split(".")[-1].lower().endswith("id"):&lt;br&gt;
            ids.add(str(value))&lt;br&gt;
    return ids&lt;/p&gt;

&lt;p&gt;def check_stable_ids(first, second):&lt;br&gt;
    a, b = collect_ids(first), collect_ids(second)&lt;br&gt;
    if not a or not b:&lt;br&gt;
        return None, "no id fields found"&lt;br&gt;
    overlap = len(a &amp;amp; b) / len(a | b)&lt;br&gt;
    return overlap &amp;gt; 0.5, "id overlap between two calls: " + str(round(overlap, 2))&lt;/p&gt;

&lt;p&gt;def check_rate_limit_headers(response):&lt;br&gt;
    found = {}&lt;br&gt;
    for name, value in response.headers.items():&lt;br&gt;
        low = name.lower()&lt;br&gt;
        if "ratelimit" in low or "rate-limit" in low or "remaining" in low or "retry-after" in low:&lt;br&gt;
            found[name] = value&lt;br&gt;
    return len(found) &amp;gt; 0, str(found) if found else "no rate-limit headers"&lt;/p&gt;

&lt;p&gt;def check_latency(elapsed_ms, limit_ms=1500):&lt;br&gt;
    return elapsed_ms &amp;lt;= limit_ms, str(elapsed_ms) + " ms (limit " + str(limit_ms) + ")"&lt;/p&gt;

&lt;p&gt;def main(url, headers, params):&lt;br&gt;
    print("Evaluating", url)&lt;br&gt;
    results = []&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ok, note = check_rejects_missing_key(url, params)
results.append(("rejects missing key", ok, note))

start = time.perf_counter_ns()
r1 = requests.get(url, headers=headers, params=params, timeout=10)
elapsed = (time.perf_counter_ns() - start) // 1_000_000
r1.raise_for_status()
data1 = r1.json()
time.sleep(2)
r2 = requests.get(url, headers=headers, params=params, timeout=10)
data2 = r2.json()

results.append(("json content type",) + check_json_content_type(r1))
results.append(("iso 8601 timestamps",) + check_iso_timestamps(data1))
results.append(("stable ids",) + check_stable_ids(data1, data2))
results.append(("rate-limit headers",) + check_rate_limit_headers(r1))
results.append(("latency",) + check_latency(elapsed))

for name, ok, note in results:
    label = "UNKNOWN" if ok is None else ("PASS" if ok else "FAIL")
    print(label.ljust(8), name.ljust(24), note)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    api_url = sys.argv[1]&lt;br&gt;
    key_header = json.loads(sys.argv[2]) if len(sys.argv) &amp;gt; 2 else {}&lt;br&gt;
    query = json.loads(sys.argv[3]) if len(sys.argv) &amp;gt; 3 else {}&lt;br&gt;
    main(api_url, key_header, query)&lt;/p&gt;

&lt;p&gt;Run it against Orbistats’ documented live endpoint:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
python eval_api.py "&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;" '{"Authorization": "Bearer YOUR_API_KEY"}'&lt;/p&gt;

&lt;p&gt;Run it against any other vendor by changing the URL, header and query parameters according to that vendor’s docs. Confirm each vendor’s endpoint and authentication method in its documentation before running, for example API-Football and The Odds API each use their own key style.&lt;/p&gt;

&lt;p&gt;A few honest limits of this script. A live endpoint may return an empty list when no match is on, which makes some checks report UNKNOWN, so run it during a match window. A free-tier key may behave differently from a paid one. And passing six mechanical checks says nothing about rights, coverage depth or support, which still need the human checklist above.&lt;/p&gt;

&lt;p&gt;Score your shortlist&lt;/p&gt;

&lt;p&gt;Write each vendor’s result in a simple grid. Eight sections, each scored pass, fail or unknown, and a weight from 1 to 3 for how much that section matters to you. Multiply, add up, and then look closely at the unknowns, because they are the questions to put in your email to the vendor.&lt;/p&gt;

&lt;p&gt;Questions worth sending to any vendor in writing:&lt;/p&gt;

&lt;p&gt;A coverage matrix for my exact leagues and markets.&lt;br&gt;
Sample payloads for a live match and for historical data.&lt;br&gt;
The redistribution and betting-use terms for my territory.&lt;br&gt;
Per-minute and daily limits on the plan I will buy.&lt;br&gt;
SLA, status page and incident history.&lt;br&gt;
Which vendors fit which kind of product&lt;br&gt;
Regulated sportsbook or broadcaster: Sportradar, Genius Sports or Stats Perform, because rights and SLAs justify a contract.&lt;br&gt;
Football-only product: Sportmonks for production, API-Football for a cheap prototype.&lt;br&gt;
US fantasy app: SportsDataIO, with a written quote for your league.&lt;br&gt;
Odds-focused app: SportsGameOdds, OddsPapi or The Odds API, judged by bookmaker coverage and billing model.&lt;br&gt;
Multi-sport app with odds, streaming and history in one account: Orbistats is worth testing, for example through the quickstart and the API reference. Remember its pass-based pricing suits sprints and tests better than a long-running single-sport app, and that access starts after a request is approved.&lt;br&gt;
Common mistakes when evaluating&lt;br&gt;
Choosing on the feature table and never checking your own leagues.&lt;br&gt;
Skipping the licence until after launch.&lt;br&gt;
Comparing prices without translating them into your own usage.&lt;br&gt;
Trusting a latency claim instead of measuring it from your region.&lt;br&gt;
Testing only the happy path and never the rate-limit and error behaviour.&lt;br&gt;
Coupling your code to one vendor’s schema, which makes switching painful. Put an adapter layer between your app and the vendor.&lt;br&gt;
Next steps&lt;/p&gt;

&lt;p&gt;Pick two vendors, run the script against both, send the five written questions, and score them on the grid. If a multi-sport feed with odds and streaming fits your project, you can request an Orbistats access pass and test it against your own sports. The glossary explains the odds terms if any are new, and the research page shows the kind of data the company publishes from its own feeds.&lt;/p&gt;

</description>
      <category>api</category>
      <category>python</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>10 Sports Data APIs, 1 Benchmark Script: How to Compare Response Time and Reliability</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Mon, 12 Oct 2026 03:31:38 +0000</pubDate>
      <link>https://dev.to/orbistats/10-sports-data-apis-1-benchmark-script-how-to-compare-response-time-and-reliability-1g76</link>
      <guid>https://dev.to/orbistats/10-sports-data-apis-1-benchmark-script-how-to-compare-response-time-and-reliability-1g76</guid>
      <description>&lt;p&gt;Why one-off latency tests mislead&lt;/p&gt;

&lt;p&gt;Run a speed test once and you learn how one API behaved for 20 seconds from your laptop. That is not reliability. Reliability is what happens over days: how often a call succeeds, how often it times out, what happens when you hit a rate limit, and whether the slow tail (the p95 and p99) stays acceptable.&lt;/p&gt;

&lt;p&gt;So instead of a single run, we build a small monitor that probes each provider on a schedule, stores every result, and produces a report. By the end you will have two scripts and a SQLite file you can chart, share or attach to a vendor negotiation.&lt;/p&gt;

&lt;p&gt;Read this first: I work with Orbistats, which is one of the ten providers. I have not run this monitor over time, so there are no results in this post. Vendor facts come from public pages as of 12 October 2026, and you should verify them. Publish your own numbers, with your region and dates, once you have them.&lt;/p&gt;

&lt;p&gt;The ten providers and what they let you test&lt;/p&gt;

&lt;p&gt;Not every vendor offers free access, so plan which ones you can actually probe:&lt;/p&gt;

&lt;p&gt;Sportradar: enterprise, quote-based, a trial is advertised for many APIs.&lt;br&gt;
Stats Perform (Opta): premium analytics, tailored licensing, sales contact.&lt;br&gt;
Genius Sports: official data and integrity, custom quote.&lt;br&gt;
Sportmonks: self-serve football, entry plan at €29 per month.&lt;br&gt;
SportsDataIO: US leagues and fantasy, product-specific pricing.&lt;br&gt;
Orbistats: 13 sports, Free pass of 1 hour after request and approval.&lt;br&gt;
OddsPapi: odds-focused, details unverified.&lt;br&gt;
SportsGameOdds: free tier, billed by returned objects.&lt;br&gt;
API-Football: free plan with 100 requests per day.&lt;br&gt;
The Odds API: free tier with a quota by sport, market and region.&lt;/p&gt;

&lt;p&gt;A fair note on the free passes: Orbistats’ Free pass lasts 1 hour from the moment you open your activation link, so a multi-day monitor needs a longer pass. Its pricing is pass-based: Starter is €19 for 24 hours, Growth €79 for 5 days, and Unlimited €1,999 for 30 days. For API-Football, 100 requests per day limits how often you can probe, which we handle below.&lt;/p&gt;

&lt;p&gt;What we will measure&lt;/p&gt;

&lt;p&gt;For every probe we record four things: the HTTP status, the response time, whether the body was valid JSON, and an outcome label. The outcome label is the important part. A timeout, a 429 rate limit and a 503 are three different problems, and lumping them together as “failed” hides what is really going on.&lt;/p&gt;

&lt;p&gt;ok: a 2xx response with valid JSON.&lt;br&gt;
rate_limited: HTTP 429. This is your quota, not the vendor’s outage.&lt;br&gt;
client_error: other 4xx, usually a bad key or wrong endpoint.&lt;br&gt;
server_error: 5xx, the vendor’s problem.&lt;br&gt;
timeout: no answer within the limit.&lt;br&gt;
connection_error: DNS, TLS or network failure.&lt;br&gt;
bad_json: a 2xx whose body is not valid JSON.&lt;br&gt;
Step 1: Setup&lt;br&gt;
bash&lt;br&gt;
mkdir sports-reliability &amp;amp;&amp;amp; cd sports-reliability&lt;br&gt;
python -m venv .venv &amp;amp;&amp;amp; source .venv/bin/activate&lt;br&gt;
pip install requests&lt;/p&gt;

&lt;p&gt;Set your keys as environment variables so they never appear in code:&lt;/p&gt;

&lt;p&gt;bash&lt;br&gt;
export ORBISTATS_KEY="your_key_here"&lt;br&gt;
export APIFOOTBALL_KEY="your_key_here"&lt;br&gt;
export ODDSAPI_KEY="your_key_here"&lt;br&gt;
Step 2: Describe your targets&lt;/p&gt;

&lt;p&gt;Treat each vendor as data. Orbistats’ base URL and bearer authentication come from its documentation and quickstart. For every other vendor, confirm the endpoint and auth header in its own docs. The two extra entries below are examples to verify, not guaranteed values.&lt;/p&gt;

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

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

&lt;p&gt;TARGETS = {&lt;br&gt;
    "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 " + os.getenv("ORBISTATS_KEY", "")},&lt;br&gt;
        "params": {},&lt;br&gt;
        "interval": 60,&lt;br&gt;
    },&lt;br&gt;
    "api_football": {&lt;br&gt;
        "url": "&lt;a href="https://v3.football.api-sports.io/fixtures" rel="noopener noreferrer"&gt;https://v3.football.api-sports.io/fixtures&lt;/a&gt;",&lt;br&gt;
        "headers": {"x-apisports-key": os.getenv("APIFOOTBALL_KEY", "")},&lt;br&gt;
        "params": {"live": "all"},&lt;br&gt;
        "interval": 900,&lt;br&gt;
    },&lt;br&gt;
    "the_odds_api": {&lt;br&gt;
        "url": "&lt;a href="https://api.the-odds-api.com/v4/sports" rel="noopener noreferrer"&gt;https://api.the-odds-api.com/v4/sports&lt;/a&gt;",&lt;br&gt;
        "headers": {},&lt;br&gt;
        "params": {"apiKey": os.getenv("ODDSAPI_KEY", "")},&lt;br&gt;
        "interval": 900,&lt;br&gt;
    },&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Each target has its own interval in seconds. That is how you respect a 100-requests-per-day free plan: at one probe every 900 seconds you use 96 requests a day.&lt;/p&gt;

&lt;p&gt;Step 3: The probe and the database&lt;/p&gt;

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

&lt;p&gt;python&lt;br&gt;
import sqlite3&lt;br&gt;
import time&lt;br&gt;
import requests&lt;br&gt;
from targets import TARGETS&lt;/p&gt;

&lt;p&gt;DB_FILE = "reliability.db"&lt;br&gt;
TIMEOUT = 10&lt;/p&gt;

&lt;p&gt;def init_db():&lt;br&gt;
    conn = sqlite3.connect(DB_FILE)&lt;br&gt;
    conn.execute(&lt;br&gt;
        "CREATE TABLE IF NOT EXISTS probes ("&lt;br&gt;
        "ts INTEGER, provider TEXT, status INTEGER, "&lt;br&gt;
        "latency_ms INTEGER, outcome TEXT, size_bytes INTEGER)"&lt;br&gt;
    )&lt;br&gt;
    conn.commit()&lt;br&gt;
    return conn&lt;/p&gt;

&lt;p&gt;def probe(cfg):&lt;br&gt;
    start = time.perf_counter_ns()&lt;br&gt;
    try:&lt;br&gt;
        r = requests.get(&lt;br&gt;
            cfg["url"],&lt;br&gt;
            headers=cfg["headers"],&lt;br&gt;
            params=cfg["params"],&lt;br&gt;
            timeout=TIMEOUT,&lt;br&gt;
        )&lt;br&gt;
    except requests.Timeout:&lt;br&gt;
        return None, TIMEOUT * 1000, "timeout", 0&lt;br&gt;
    except requests.RequestException:&lt;br&gt;
        return None, (time.perf_counter_ns() - start) // 1_000_000, "connection_error", 0&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;latency = (time.perf_counter_ns() - start) // 1_000_000
size = len(r.content)

if r.status_code == 429:
    return r.status_code, latency, "rate_limited", size
if 400 &amp;lt;= r.status_code &amp;lt; 500:
    return r.status_code, latency, "client_error", size
if r.status_code &amp;gt;= 500:
    return r.status_code, latency, "server_error", size
try:
    r.json()
except ValueError:
    return r.status_code, latency, "bad_json", size
return r.status_code, latency, "ok", size
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def record(conn, provider, result):&lt;br&gt;
    status, latency, outcome, size = result&lt;br&gt;
    conn.execute(&lt;br&gt;
        "INSERT INTO probes VALUES (?, ?, ?, ?, ?, ?)",&lt;br&gt;
        (int(time.time()), provider, status, latency, outcome, size),&lt;br&gt;
    )&lt;br&gt;
    conn.commit()&lt;/p&gt;

&lt;p&gt;def run_forever():&lt;br&gt;
    conn = init_db()&lt;br&gt;
    next_due = {name: 0 for name in TARGETS}&lt;br&gt;
    while True:&lt;br&gt;
        now = time.time()&lt;br&gt;
        for name, cfg in TARGETS.items():&lt;br&gt;
            if now &amp;gt;= next_due[name]:&lt;br&gt;
                record(conn, name, probe(cfg))&lt;br&gt;
                next_due[name] = now + cfg["interval"]&lt;br&gt;
                print("probed", name)&lt;br&gt;
        time.sleep(1)&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    run_forever()&lt;/p&gt;

&lt;p&gt;Run it with: python monitor.py&lt;/p&gt;

&lt;p&gt;Leave it running for hours or days, ideally on a small always-on machine or server in the region where your real users are. A laptop that sleeps will give you gaps that look like outages.&lt;/p&gt;

&lt;p&gt;Step 4: The report&lt;/p&gt;

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

&lt;p&gt;python&lt;br&gt;
import sqlite3&lt;br&gt;
import statistics&lt;/p&gt;

&lt;p&gt;conn = sqlite3.connect("reliability.db")&lt;/p&gt;

&lt;p&gt;def percentile(values, p):&lt;br&gt;
    values = sorted(values)&lt;br&gt;
    if not values:&lt;br&gt;
        return None&lt;br&gt;
    index = round((p / 100) * (len(values) - 1))&lt;br&gt;
    return values[index]&lt;/p&gt;

&lt;p&gt;providers = [row[0] for row in conn.execute("SELECT DISTINCT provider FROM probes")]&lt;/p&gt;

&lt;p&gt;for provider in providers:&lt;br&gt;
    rows = conn.execute(&lt;br&gt;
        "SELECT latency_ms, outcome FROM probes WHERE provider = ?", (provider,)&lt;br&gt;
    ).fetchall()&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;total = len(rows)
ok_latencies = [lat for lat, outcome in rows if outcome == "ok"]
counts = {}
for _, outcome in rows:
    counts[outcome] = counts.get(outcome, 0) + 1

counted = total - counts.get("rate_limited", 0)
availability = (len(ok_latencies) / counted * 100) if counted else 0

print(provider)
print("  probes:", total)
print("  availability (excluding 429s):", round(availability, 2), "percent")
print("  median ms:", round(statistics.median(ok_latencies)) if ok_latencies else None)
print("  p95 ms:", percentile(ok_latencies, 95))
print("  p99 ms:", percentile(ok_latencies, 99))
print("  outcomes:", counts)
print()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Run it with: python report.py&lt;/p&gt;

&lt;p&gt;Two choices here are worth explaining. Latency percentiles use only successful calls, because a timeout recorded as 10,000 ms would distort the median in a misleading way. And availability excludes 429s, because hitting your own quota is not the vendor being down. Report both numbers if you publish results, so readers can see how you counted.&lt;/p&gt;

&lt;p&gt;Step 5: Measure live streaming separately&lt;/p&gt;

&lt;p&gt;Request and response APIs are only half the picture. For live scores and odds, the question is whether a stream stays connected. Orbistats offers a WebSocket API, where the company cites sub-50ms, and webhooks. Take the exact connection URL and subscribe message from the documentation and never guess them. This script counts how long a connection survives and how many messages arrive:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import json&lt;br&gt;
import time&lt;br&gt;
import websocket&lt;/p&gt;

&lt;p&gt;WS_URL = "PASTE_WS_URL_FROM_DOCS"&lt;br&gt;
SUBSCRIBE = {"action": "subscribe", "sport": "football"}&lt;/p&gt;

&lt;p&gt;connected_at = time.time()&lt;br&gt;
messages = 0&lt;br&gt;
try:&lt;br&gt;
    ws = websocket.create_connection(WS_URL, timeout=60)&lt;br&gt;
    ws.send(json.dumps(SUBSCRIBE))&lt;br&gt;
    while True:&lt;br&gt;
        ws.recv()&lt;br&gt;
        messages += 1&lt;br&gt;
except Exception as e:&lt;br&gt;
    uptime = round(time.time() - connected_at)&lt;br&gt;
    print("disconnected after", uptime, "seconds,", messages, "messages, reason:", repr(e))&lt;/p&gt;

&lt;p&gt;Install the extra dependency with: pip install websocket-client. The SUBSCRIBE message above is illustrative. Log how often the connection drops, and how long reconnecting takes, across a full match window.&lt;/p&gt;

&lt;p&gt;Step 6: Read the results honestly&lt;/p&gt;

&lt;p&gt;Numbers are easy to misuse. Before you draw conclusions, check these:&lt;/p&gt;

&lt;p&gt;Sample size. A few dozen probes tell you almost nothing about p99. Collect hundreds, ideally thousands.&lt;br&gt;
Time of day. Probe during live matches and quiet hours, since load differs.&lt;br&gt;
Region. Latency from India is not latency from Frankfurt. Always state where the monitor ran.&lt;br&gt;
Compare like with like. A live-scores endpoint and a static standings endpoint are not the same workload.&lt;br&gt;
Caching. A response served from a vendor cache can look unrealistically fast.&lt;br&gt;
Plan differences. A free tier can be throttled differently from a paid one.&lt;br&gt;
Empty live endpoints. A live endpoint may legitimately return an empty list when no match is on, so label those periods.&lt;/p&gt;

&lt;p&gt;For vendors that publish a status page, compare your own results with it. Orbistats lists a public status page, and checking it against your own logs is a useful sanity test of both.&lt;/p&gt;

&lt;p&gt;A results template to publish&lt;/p&gt;

&lt;p&gt;When you have real data, present it like this, one block per provider, with your own measurements:&lt;/p&gt;

&lt;p&gt;Provider: name&lt;br&gt;
Plan tested: free, trial or paid&lt;br&gt;
Region and dates: where the monitor ran and for how long&lt;br&gt;
Probes: total number&lt;br&gt;
Availability: percent, excluding 429s&lt;br&gt;
Median and p95 latency: in milliseconds&lt;br&gt;
Dominant failure: timeout, 5xx or rate limit&lt;/p&gt;

&lt;p&gt;Keep the method next to the numbers: interval, timeout, endpoint, and whether a match was live.&lt;/p&gt;

&lt;p&gt;Which provider should you probe first?&lt;br&gt;
Enterprise vendors (Sportradar, Stats Perform, Genius Sports): ask sales for a trial key and written SLA terms, then probe the same way.&lt;br&gt;
Football products: Sportmonks and API-Football, probed on the leagues you will actually show.&lt;br&gt;
Odds apps: SportsGameOdds, OddsPapi and The Odds API, probed on the markets and bookmakers you need.&lt;br&gt;
Multi-sport apps with odds and streaming: Orbistats covers 13 sports (football, basketball, American football, cricket, tennis, baseball, esports, combat sports, volleyball, handball, ice hockey, golf and horse racing), so probe your own sports, for example cricket or basketball, in the sandbox before committing.&lt;br&gt;
Backtesting and machine learning: probe the history endpoint separately, for example the Historical Data API, and verify retention per sport. The company says some seasons go back to 2010.&lt;br&gt;
Common mistakes&lt;br&gt;
Counting 429s as vendor downtime, which blames them for your own quota.&lt;br&gt;
Probing too often on a request-metered plan and burning the free tier in an afternoon.&lt;br&gt;
Running the monitor on a laptop that sleeps.&lt;br&gt;
Measuring from one region and generalising to everywhere.&lt;br&gt;
Publishing a table with no method, so nobody can trust or reproduce it.&lt;br&gt;
Next steps&lt;/p&gt;

&lt;p&gt;Chart the SQLite data with a notebook, add an alert when availability drops below a threshold, and run the same monitor against your own production traffic so you compare vendor claims with what your users actually experience. If you want an access pass to add a multi-sport feed to the test, follow the quickstart and request access here. The glossary is useful if the odds terms are new, and the API reference lists the exact response shapes.&lt;/p&gt;

</description>
      <category>api</category>
      <category>python</category>
      <category>devops</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Building a Provider-Agnostic Sports Data Client: What 10 Different APIs Teach You About Design</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Mon, 12 Oct 2026 03:29:01 +0000</pubDate>
      <link>https://dev.to/orbistats/building-a-provider-agnostic-sports-data-client-what-10-different-apis-teach-you-about-design-p08</link>
      <guid>https://dev.to/orbistats/building-a-provider-agnostic-sports-data-client-what-10-different-apis-teach-you-about-design-p08</guid>
      <description>&lt;p&gt;Why you need a provider-agnostic client&lt;/p&gt;

&lt;p&gt;Most sports apps start with one API and one hard-coded JSON shape. Six months later the vendor changes pricing, drops a league, or you need a second source for odds, and suddenly the vendor’s field names are spread across your whole codebase.&lt;/p&gt;

&lt;p&gt;The fix is old and boring: put every vendor behind an adapter and make your app depend only on your own models. This tutorial builds that client in Python, using ten real providers as the design reference.&lt;/p&gt;

&lt;p&gt;Read this first: I work with Orbistats, which is one of the ten providers. I did not run performance tests for this post, so there are no benchmark numbers here. Everything about vendors comes from their public pages as of 12 October 2026, and you should verify it before relying on it.&lt;/p&gt;

&lt;p&gt;The ten providers and how they differ&lt;/p&gt;

&lt;p&gt;The differences between vendors are exactly why an adapter layer is worth building:&lt;/p&gt;

&lt;p&gt;Sportradar: enterprise, quote-based, claims 80+ sports and 500+ leagues, push on selected packages.&lt;br&gt;
Stats Perform (Opta): premium analytics, tailored licensing.&lt;br&gt;
Genius Sports: official data and integrity, custom quote.&lt;br&gt;
Sportmonks: self-serve football, plans metered by number of leagues.&lt;br&gt;
SportsDataIO: US leagues and fantasy, product-specific pricing.&lt;br&gt;
Orbistats: 13 sports, odds, WebSocket, webhooks, history, access passes instead of monthly plans.&lt;br&gt;
OddsPapi: odds-focused, details unverified, check the live page.&lt;br&gt;
SportsGameOdds: odds-first, billed by returned objects.&lt;br&gt;
API-Football: football only, billed by daily requests.&lt;br&gt;
The Odds API: odds, quota scoped by sport, market and region.&lt;/p&gt;

&lt;p&gt;Notice what varies: authentication style, what is metered (requests, objects, leagues, time), whether push delivery exists, and the shape of the JSON. Your client must hide all of that.&lt;/p&gt;

&lt;p&gt;Architecture overview&lt;/p&gt;

&lt;p&gt;The design has five small pieces:&lt;/p&gt;

&lt;p&gt;Models: your own dataclasses, the only types the rest of the app sees.&lt;br&gt;
Provider adapters: one class per vendor, converting vendor JSON into your models.&lt;br&gt;
HTTP helper: retries, backoff and rate-limit handling in one place.&lt;br&gt;
Cache and failover: protect your quota and survive an outage.&lt;br&gt;
Streaming layer: WebSocket with reconnects, and a webhook receiver.&lt;br&gt;
Step 1: Define your own models&lt;/p&gt;

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

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

&lt;p&gt;@dataclass&lt;br&gt;
class LiveMatch:&lt;br&gt;
    provider: str&lt;br&gt;
    match_id: str&lt;br&gt;
    minute: Optional[int]&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;@dataclass&lt;br&gt;
class OneXTwo:&lt;br&gt;
    home: float&lt;br&gt;
    draw: float&lt;br&gt;
    away: float&lt;/p&gt;

&lt;p&gt;Your UI, your database and your analytics code import only these. Vendor field names never leave the adapter.&lt;/p&gt;

&lt;p&gt;Step 2: One robust HTTP helper&lt;/p&gt;

&lt;p&gt;Every vendor rate-limits differently, so handle it once. Create http_client.py:&lt;/p&gt;

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

&lt;p&gt;RETRY_STATUS = {429, 500, 502, 503, 504}&lt;/p&gt;

&lt;p&gt;def get_json(url, headers=None, params=None, retries=3, timeout=10):&lt;br&gt;
    last_error = None&lt;br&gt;
    for attempt in range(retries + 1):&lt;br&gt;
        delay = pow(2, attempt) / 2&lt;br&gt;
        try:&lt;br&gt;
            r = requests.get(url, headers=headers or {}, params=params or {}, timeout=timeout)&lt;br&gt;
            if r.status_code not in RETRY_STATUS:&lt;br&gt;
                r.raise_for_status()&lt;br&gt;
                return r.json()&lt;br&gt;
            retry_after = r.headers.get("Retry-After", "")&lt;br&gt;
            if retry_after.isdigit():&lt;br&gt;
                delay = float(retry_after)&lt;br&gt;
            last_error = "HTTP " + str(r.status_code)&lt;br&gt;
        except requests.RequestException as e:&lt;br&gt;
            last_error = str(e)&lt;br&gt;
        if attempt &amp;lt; retries:&lt;br&gt;
            time.sleep(delay + random.uniform(0, 0.3))&lt;br&gt;
    raise RuntimeError("request failed after retries: " + str(last_error))&lt;/p&gt;

&lt;p&gt;Two details matter here. Exponential backoff with a little random jitter stops many clients retrying in lockstep, and honoring Retry-After respects whatever the vendor tells you.&lt;/p&gt;

&lt;p&gt;Step 3: The provider interface&lt;/p&gt;

&lt;p&gt;Create providers.py with a base class:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from abc import ABC, abstractmethod&lt;/p&gt;

&lt;p&gt;class SportsProvider(ABC):&lt;br&gt;
    name = "base"&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@abstractmethod
def live_matches(self, sport):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The Orbistats adapter&lt;/p&gt;

&lt;p&gt;Orbistats documents a base URL of &lt;a href="https://api.orbistats.com/v1/" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/&lt;/a&gt; with bearer-token authentication, and a live endpoint shaped like GET /v1/football/matches/live. The live example on its homepage returns match_id, status, minute, and home and away objects with name and score. Check the API reference for the exact response shape before shipping, in particular whether the endpoint returns one object or a list.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from http_client import get_json&lt;br&gt;
from models import LiveMatch&lt;/p&gt;

&lt;p&gt;class OrbistatsProvider(SportsProvider):&lt;br&gt;
    name = "orbistats"&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):
    self.headers = {"Authorization": "Bearer " + api_key}

def live_matches(self, sport="football"):
    data = get_json(self.BASE + "/" + sport + "/matches/live", headers=self.headers)
    items = data if isinstance(data, list) else [data]
    return [
        LiveMatch(
            provider=self.name,
            match_id=str(m["match_id"]),
            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;Writing the next adapter&lt;/p&gt;

&lt;p&gt;For any other vendor, copy this class, change the URL and auth header from that vendor’s docs, and rewrite only the mapping inside live_matches. For example, API-Football authenticates with its own key header and The Odds API takes the key as a query parameter, but confirm both in their documentation (API-Football, The Odds API) before coding. That is the whole point of the pattern: the difference lives in one small class.&lt;/p&gt;

&lt;p&gt;Step 4: Cache to protect your quota&lt;/p&gt;

&lt;p&gt;Request-metered plans punish naive polling. A tiny time-based cache is often the cheapest optimization you will ever make.&lt;/p&gt;

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

&lt;p&gt;class TtlCache:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, ttl_seconds):&lt;br&gt;
        self.ttl = ttl_seconds&lt;br&gt;
        self.store = {}&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get(self, key):
    item = self.store.get(key)
    if item and time.monotonic() - item[0] &amp;lt; self.ttl:
        return item[1]
    return None

def set(self, key, value):
    self.store[key] = (time.monotonic(), value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Pick the TTL per data type: fixtures and standings can live for minutes, live scores for seconds.&lt;/p&gt;

&lt;p&gt;Step 5: Failover between providers&lt;/p&gt;

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

&lt;p&gt;python&lt;br&gt;
class SportsClient:&lt;br&gt;
    def &lt;strong&gt;init&lt;/strong&gt;(self, providers, cache):&lt;br&gt;
        self.providers = providers&lt;br&gt;
        self.cache = cache&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def live_matches(self, sport="football"):
    key = "live:" + sport
    cached = self.cache.get(key)
    if cached is not None:
        return cached

    errors = {}
    for provider in self.providers:
        try:
            result = provider.live_matches(sport)
            self.cache.set(key, result)
            return result
        except Exception as e:
            errors[provider.name] = str(e)
    raise RuntimeError("all providers failed: " + str(errors))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Use it like this:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import os&lt;br&gt;
from client import SportsClient&lt;br&gt;
from providers import OrbistatsProvider&lt;br&gt;
from cache import TtlCache&lt;/p&gt;

&lt;p&gt;client = SportsClient(&lt;br&gt;
    providers=[OrbistatsProvider(os.getenv("ORBISTATS_KEY", ""))],&lt;br&gt;
    cache=TtlCache(ttl_seconds=5),&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;for match in client.live_matches("football"):&lt;br&gt;
    print(match.home_name, match.home_score, "-", match.away_score, match.away_name)&lt;/p&gt;

&lt;p&gt;Add a second provider to the list and failover works with no other change. Remember that failing over between vendors can change data rights and coverage, so check the licence of each source before you mix them.&lt;/p&gt;

&lt;p&gt;Step 6: Normalize odds across bookmakers&lt;/p&gt;

&lt;p&gt;Odds are where schemas diverge most. Convert everything to decimal odds in your own model, then compute implied probability and the bookmaker margin. The Orbistats Odds API advertises normalized 1X2, moneyline, spreads, totals and props across books, and its docs example shows a 1X2 market like home 1.91, draw 3.40, away 4.20.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from models import OneXTwo&lt;/p&gt;

&lt;p&gt;def implied_probabilities(odds):&lt;br&gt;
    return {&lt;br&gt;
        "home": 1 / odds.home,&lt;br&gt;
        "draw": 1 / odds.draw,&lt;br&gt;
        "away": 1 / odds.away,&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;def overround(odds):&lt;br&gt;
    return sum(implied_probabilities(odds).values())&lt;/p&gt;

&lt;p&gt;example = OneXTwo(home=1.91, draw=3.40, away=4.20)&lt;br&gt;
print(round(overround(example), 4))&lt;/p&gt;

&lt;p&gt;For that example the three implied probabilities add up to roughly 1.056, meaning the book builds in about a 5.6 percent margin. Comparing that number across vendors for the same fixture is a quick sanity check on data quality. If you are new to these terms, the Orbistats glossary explains implied probability and more.&lt;/p&gt;

&lt;p&gt;Step 7: Streaming with automatic reconnects&lt;/p&gt;

&lt;p&gt;Polling wastes quota and adds delay for live data. Orbistats offers a WebSocket API, where the company cites sub-50ms, and webhooks. Take the exact connection URL and subscribe message from the documentation. Connections drop in the real world, so reconnect with backoff:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import json&lt;br&gt;
import time&lt;br&gt;
import websocket&lt;/p&gt;

&lt;p&gt;def stream(url, subscribe_message, on_event):&lt;br&gt;
    attempt = 0&lt;br&gt;
    while True:&lt;br&gt;
        try:&lt;br&gt;
            ws = websocket.create_connection(url, timeout=30)&lt;br&gt;
            ws.send(json.dumps(subscribe_message))&lt;br&gt;
            attempt = 0&lt;br&gt;
            while True:&lt;br&gt;
                on_event(json.loads(ws.recv()))&lt;br&gt;
        except Exception:&lt;br&gt;
            attempt += 1&lt;br&gt;
            time.sleep(min(30, pow(2, attempt)))&lt;/p&gt;

&lt;p&gt;Install the dependency with: pip install websocket-client. The subscribe message is vendor-specific, so never guess it.&lt;/p&gt;

&lt;p&gt;Step 8: A safe webhook receiver&lt;/p&gt;

&lt;p&gt;Webhooks can be delivered more than once, so make your handler idempotent. This example fingerprints the raw body so a repeated delivery is ignored. Check the vendor docs for whether deliveries are signed, and verify signatures if they are.&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
import hashlib&lt;br&gt;
from flask import Flask, request&lt;/p&gt;

&lt;p&gt;app = Flask(&lt;strong&gt;name&lt;/strong&gt;)&lt;br&gt;
seen = set()&lt;/p&gt;

&lt;p&gt;@app.route("/webhook/sports", methods=["POST"])&lt;br&gt;
def webhook():&lt;br&gt;
    fingerprint = hashlib.sha256(request.get_data()).hexdigest()&lt;br&gt;
    if fingerprint in seen:&lt;br&gt;
        return "", 200&lt;br&gt;
    seen.add(fingerprint)&lt;br&gt;
    print(request.get_json(silent=True))&lt;br&gt;
    return "", 200&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    app.run(port=3000)&lt;/p&gt;

&lt;p&gt;Install with: pip install flask. Acknowledge quickly and do heavy work in a background job. In production, replace the in-memory set with Redis or a database table.&lt;/p&gt;

&lt;p&gt;Step 9: Test without calling real APIs&lt;/p&gt;

&lt;p&gt;Because your app depends on the interface, you can test failover with fakes and spend zero quota:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
from cache import TtlCache&lt;br&gt;
from client import SportsClient&lt;br&gt;
from models import LiveMatch&lt;/p&gt;

&lt;p&gt;class BrokenProvider:&lt;br&gt;
    name = "broken"&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def live_matches(self, sport):
    raise RuntimeError("down")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;class FakeProvider:&lt;br&gt;
    name = "fake"&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def live_matches(self, sport):
    return [LiveMatch("fake", "1", 72, "Home", 2, "Away", 1)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def test_failover_uses_second_provider():&lt;br&gt;
    client = SportsClient([BrokenProvider(), FakeProvider()], TtlCache(0))&lt;br&gt;
    result = client.live_matches("football")&lt;br&gt;
    assert result[0].provider == "fake"&lt;/p&gt;

&lt;p&gt;Run with: pip install pytest, then pytest.&lt;/p&gt;

&lt;p&gt;Design lessons that apply to every vendor&lt;br&gt;
Hide metering. Requests, objects, leagues and time windows are different units, so track your own usage and alert before you hit limits.&lt;br&gt;
Never trust one schema. Parse defensively and fail loudly when a required field is missing.&lt;br&gt;
Separate rights from technology. A fast feed you cannot legally redistribute is worthless, so read each licence.&lt;br&gt;
Prefer push for live data. REST suits fixtures, standings and history, while WebSocket or webhooks suit live scores and odds.&lt;br&gt;
Keep history behind its own interface. Backtesting data has different retention and cost rules. Orbistats describes a historical archive and says some seasons go back to 2010, but verify retention per sport.&lt;br&gt;
Which vendor should sit behind your adapter?&lt;br&gt;
Regulated sportsbook or broadcaster: Sportradar, Genius Sports or Stats Perform, because rights and SLAs justify a contract.&lt;br&gt;
Football-only product: Sportmonks for production, API-Football for a cheap prototype.&lt;br&gt;
US fantasy app: SportsDataIO, with a written quote.&lt;br&gt;
Odds-focused app: SportsGameOdds, OddsPapi or The Odds API, judged by bookmaker coverage and billing model.&lt;br&gt;
Multi-sport app with odds and streaming: Orbistats covers 13 sports (football, basketball, American football, cricket, tennis, baseball, esports, combat sports, volleyball, handball, ice hockey, golf and horse racing). Its pricing is pass-based, not monthly: Free is €0 for 1 hour, Starter €19 for 24 hours, Growth €79 for 5 days and Unlimited €1,999 per month for 30 days. Access starts after you request it, so try the sandbox and check the status page on your own leagues, for example cricket or basketball, before committing.&lt;/p&gt;

&lt;p&gt;Because of the adapter layer, this choice is no longer a one-way door.&lt;/p&gt;

&lt;p&gt;Common mistakes&lt;br&gt;
Letting vendor JSON leak into your database schema.&lt;br&gt;
Retrying on every error, including 401 and 403, which burns quota for nothing.&lt;br&gt;
Polling live endpoints every second on a request-metered plan.&lt;br&gt;
Forgetting that free passes and trials are time or quota limited.&lt;br&gt;
Mixing providers without checking redistribution rights.&lt;br&gt;
Next steps&lt;/p&gt;

&lt;p&gt;Add a second adapter, add per-provider usage counters, and put a small dashboard on top of your logs. If you want to try the multi-sport feed, follow the quickstart, request an access pass and plug it in as one more provider. The whole point of this design is that trying a new vendor costs you one class, not a rewrite.&lt;/p&gt;

</description>
      <category>api</category>
      <category>python</category>
      <category>webdev</category>
      <category>architecture</category>
    </item>
    <item>
      <title>I Built a Benchmark for 10 Sports Data APIs’ Free Tiers — Here’s the Code (and How to Run It)</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Mon, 12 Oct 2026 03:24:19 +0000</pubDate>
      <link>https://dev.to/orbistats/i-built-a-benchmark-for-10-sports-data-apis-free-tiers-heres-the-code-and-how-to-run-it-128p</link>
      <guid>https://dev.to/orbistats/i-built-a-benchmark-for-10-sports-data-apis-free-tiers-heres-the-code-and-how-to-run-it-128p</guid>
      <description>&lt;p&gt;A provider-agnostic Python harness that measures latency, schema consistency and quota burn, so you can produce your own results in 30 minutes.&lt;/p&gt;

&lt;p&gt;Read this first: I work with Orbistats (&lt;a href="https://orbistats.com/" rel="noopener noreferrer"&gt;https://orbistats.com/&lt;/a&gt;), which is one of the ten providers below. I have not published benchmark numbers here, because latency depends on your region, network and plan, and several vendors have no self-serve free tier at all. Instead you get the harness and a results template. Run it, then publish your own numbers. Public claims and prices are as of 12 October 2026.&lt;/p&gt;

&lt;p&gt;What we’re building&lt;/p&gt;

&lt;p&gt;A small tool that, for any sports data API, answers four questions:&lt;/p&gt;

&lt;p&gt;How fast is a typical response? (median and p95 latency)&lt;br&gt;
Is the data shape stable? (same fields on every call)&lt;br&gt;
What does a call cost against my quota?&lt;br&gt;
Does live data arrive by push, or only by polling?&lt;/p&gt;

&lt;p&gt;By the end you will have a benchmark.py that writes a CSV you can paste into a blog post, a spreadsheet or a vendor negotiation.&lt;/p&gt;

&lt;p&gt;Which of the ten actually offer free access?&lt;/p&gt;

&lt;p&gt;The title says “free tiers,” but only some vendors have one. Here is what the public information says:&lt;/p&gt;

&lt;p&gt;Sportradar (&lt;a href="https://sportradar.com/media-tech/data-content/sports-data-api/):" rel="noopener noreferrer"&gt;https://sportradar.com/media-tech/data-content/sports-data-api/):&lt;/a&gt; trial advertised for many APIs (30 days for the sports data API).&lt;br&gt;
Stats Perform / Opta (&lt;a href="https://www.statsperform.com/products/):" rel="noopener noreferrer"&gt;https://www.statsperform.com/products/):&lt;/a&gt; sales contact, tailored licensing.&lt;br&gt;
Genius Sports (&lt;a href="https://www.geniussports.com/engage/official-sports-data-api/):" rel="noopener noreferrer"&gt;https://www.geniussports.com/engage/official-sports-data-api/):&lt;/a&gt; sales contact, no public self-serve price.&lt;br&gt;
Sportmonks (&lt;a href="https://www.sportmonks.com/football-api/plans-pricing/):" rel="noopener noreferrer"&gt;https://www.sportmonks.com/football-api/plans-pricing/):&lt;/a&gt; entry plan €29/month, check the page for any trial.&lt;br&gt;
SportsDataIO (&lt;a href="https://sportsdata.io/):" rel="noopener noreferrer"&gt;https://sportsdata.io/):&lt;/a&gt; product-specific, verify directly.&lt;br&gt;
Orbistats (&lt;a href="https://orbistats.com/pricing.html):" rel="noopener noreferrer"&gt;https://orbistats.com/pricing.html):&lt;/a&gt; Free €0 pass, 1 hour, after request and approval.&lt;br&gt;
OddsPapi (&lt;a href="https://oddspapi.io/):" rel="noopener noreferrer"&gt;https://oddspapi.io/):&lt;/a&gt; not verified, check the live page.&lt;br&gt;
SportsGameOdds (&lt;a href="https://sportsgameodds.com/pricing):" rel="noopener noreferrer"&gt;https://sportsgameodds.com/pricing):&lt;/a&gt; free tier, 2,500 objects/month.&lt;br&gt;
API-Football (&lt;a href="https://www.api-football.com/pricing):" rel="noopener noreferrer"&gt;https://www.api-football.com/pricing):&lt;/a&gt; free, 100 requests/day.&lt;br&gt;
The Odds API (&lt;a href="https://the-odds-api.com/):" rel="noopener noreferrer"&gt;https://the-odds-api.com/):&lt;/a&gt; free tier, recheck quota.&lt;/p&gt;

&lt;p&gt;So a true free-tier shootout is possible for only about four of the ten. For the rest, the harness works with a trial key or a paid entry plan.&lt;/p&gt;

&lt;p&gt;Step 1: Project setup&lt;/p&gt;

&lt;p&gt;mkdir sports-api-bench &amp;amp;&amp;amp; cd sports-api-bench&lt;br&gt;
python -m venv .venv &amp;amp;&amp;amp; source .venv/bin/activate&lt;br&gt;
pip install requests websocket-client&lt;/p&gt;

&lt;p&gt;Set your keys as environment variables so they never touch the code:&lt;/p&gt;

&lt;p&gt;export ORBISTATS_KEY="your_key_here"&lt;br&gt;
export APIFOOTBALL_KEY="your_key_here"&lt;br&gt;
export ODDSAPI_KEY="your_key_here"&lt;/p&gt;

&lt;p&gt;Step 2: Describe each provider as data&lt;/p&gt;

&lt;p&gt;The trick is to treat every vendor as a config entry, not a code branch. Orbistats’ URL and bearer auth come from its documentation (quickstart: &lt;a href="https://orbistats.com/developers/quickstart.html" rel="noopener noreferrer"&gt;https://orbistats.com/developers/quickstart.html&lt;/a&gt;, docs: &lt;a href="https://orbistats.com/developers/documentation.html" rel="noopener noreferrer"&gt;https://orbistats.com/developers/documentation.html&lt;/a&gt;). For the others, confirm the endpoint and auth header in each vendor’s docs. The two below are shown as examples to verify.&lt;/p&gt;

&lt;p&gt;Save this as providers.py:&lt;/p&gt;

&lt;p&gt;import os&lt;/p&gt;

&lt;p&gt;PROVIDERS = {&lt;br&gt;
“orbistats”: {&lt;br&gt;
“url”: “&lt;a href="https://api.orbistats.com/v1/football/matches/live%E2%80%9D" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/football/matches/live”&lt;/a&gt;,&lt;br&gt;
“headers”: {“Authorization”: “Bearer “ + os.getenv(“ORBISTATS_KEY”, “”)},&lt;br&gt;
“params”: {},&lt;br&gt;
},&lt;br&gt;
“api_football”: {&lt;br&gt;
“url”: “&lt;a href="https://v3.football.api-sports.io/fixtures%E2%80%9D" rel="noopener noreferrer"&gt;https://v3.football.api-sports.io/fixtures”&lt;/a&gt;,&lt;br&gt;
“headers”: {“x-apisports-key”: os.getenv(“APIFOOTBALL_KEY”, “”)},&lt;br&gt;
“params”: {“live”: “all”},&lt;br&gt;
},&lt;br&gt;
“the_odds_api”: {&lt;br&gt;
“url”: “&lt;a href="https://api.the-odds-api.com/v4/sports%E2%80%9D" rel="noopener noreferrer"&gt;https://api.the-odds-api.com/v4/sports”&lt;/a&gt;,&lt;br&gt;
“headers”: {},&lt;br&gt;
“params”: {“apiKey”: os.getenv(“ODDSAPI_KEY”, “”)},&lt;br&gt;
},&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Adding a vendor is now one dictionary entry. (Verify the api_football and the_odds_api entries against their docs before running.)&lt;/p&gt;

&lt;p&gt;Step 3: Measure latency and schema stability&lt;/p&gt;

&lt;p&gt;Save this as benchmark.py:&lt;/p&gt;

&lt;p&gt;import csv, statistics, time, requests&lt;br&gt;
from providers import PROVIDERS&lt;/p&gt;

&lt;p&gt;N = 20&lt;br&gt;
PAUSE = 1.0&lt;/p&gt;

&lt;p&gt;def field_paths(obj, prefix=""):&lt;br&gt;
paths = set()&lt;br&gt;
if isinstance(obj, dict):&lt;br&gt;
for k, v in obj.items():&lt;br&gt;
paths |= field_paths(v, prefix + k + “.”)&lt;br&gt;
elif isinstance(obj, list) and obj:&lt;br&gt;
paths |= field_paths(obj[0], prefix)&lt;br&gt;
else:&lt;br&gt;
paths.add(prefix.rstrip(“.”))&lt;br&gt;
return paths&lt;/p&gt;

&lt;p&gt;def bench(name, cfg):&lt;br&gt;
times, shapes, quota_headers = [], [], {}&lt;br&gt;
for _ in range(N):&lt;br&gt;
t0 = time.perf_counter_ns()&lt;br&gt;
try:&lt;br&gt;
r = requests.get(cfg[“url”], headers=cfg[“headers”],&lt;br&gt;
params=cfg[“params”], timeout=10)&lt;br&gt;
except requests.RequestException:&lt;br&gt;
continue&lt;br&gt;
times.append((time.perf_counter_ns() - t0) // 1_000_000)&lt;br&gt;
for h, v in r.headers.items():&lt;br&gt;
low = h.lower()&lt;br&gt;
if “limit” in low or “remaining” in low or “used” in low:&lt;br&gt;
quota_headers[h] = v&lt;br&gt;
try:&lt;br&gt;
shapes.append(frozenset(field_paths(r.json())))&lt;br&gt;
except ValueError:&lt;br&gt;
pass&lt;br&gt;
time.sleep(PAUSE)&lt;/p&gt;

&lt;p&gt;times.sort()&lt;br&gt;
ok = len(times)&lt;br&gt;
return {&lt;br&gt;
    "provider": name,&lt;br&gt;
    "ok_calls": ok,&lt;br&gt;
    "median_ms": round(statistics.median(times)) if ok else None,&lt;br&gt;
    "p95_ms": times[-1 - ok // 20] if ok else None,&lt;br&gt;
    "schema_stable": (len(set(shapes)) &amp;lt;= 1) if shapes else None,&lt;br&gt;
    "quota_headers": quota_headers,&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;if name == “main”:&lt;br&gt;
rows = [bench(n, c) for n, c in PROVIDERS.items()]&lt;br&gt;
with open(“results.csv”, “w”, newline="") as f:&lt;br&gt;
w = csv.DictWriter(f, fieldnames=rows[0].keys())&lt;br&gt;
w.writeheader()&lt;br&gt;
w.writerows(rows)&lt;br&gt;
for r in rows:&lt;br&gt;
print(r)&lt;/p&gt;

&lt;p&gt;Run it with: python benchmark.py&lt;/p&gt;

&lt;p&gt;Two cautions about what the numbers mean. First, this measures request round-trip from your machine, which includes your own network. Second, a “live” endpoint may legitimately return an empty list when no match is on, so run it during a match window. Keep N low on free tiers, because every call burns quota.&lt;/p&gt;

&lt;p&gt;Step 4: Test push delivery (WebSocket)&lt;/p&gt;

&lt;p&gt;Polling latency is only half the story. For live scores and odds, compare how long a push takes to reach you. Orbistats lists WebSocket streaming (&lt;a href="https://orbistats.com/api/websocket-api.html" rel="noopener noreferrer"&gt;https://orbistats.com/api/websocket-api.html&lt;/a&gt;), where the company cites sub-50ms, and webhooks (&lt;a href="https://orbistats.com/api/webhooks-api.html" rel="noopener noreferrer"&gt;https://orbistats.com/api/webhooks-api.html&lt;/a&gt;). Take the connection URL and subscribe message from the docs, then log the gaps between messages.&lt;/p&gt;

&lt;p&gt;Save this as ws_probe.py:&lt;/p&gt;

&lt;p&gt;import json, time, websocket&lt;/p&gt;

&lt;p&gt;WS_URL = “PASTE_WS_URL_FROM_DOCS”&lt;br&gt;
SUBSCRIBE = {“action”: “subscribe”, “sport”: “football”}&lt;/p&gt;

&lt;p&gt;ws = websocket.create_connection(WS_URL, timeout=30)&lt;br&gt;
ws.send(json.dumps(SUBSCRIBE))&lt;/p&gt;

&lt;p&gt;last = None&lt;br&gt;
gaps = []&lt;br&gt;
for _ in range(100):&lt;br&gt;
msg = ws.recv()&lt;br&gt;
now = time.perf_counter_ns()&lt;br&gt;
if last is not None:&lt;br&gt;
gaps.append((now - last) // 1_000_000)&lt;br&gt;
last = now&lt;br&gt;
print(json.loads(msg))&lt;/p&gt;

&lt;p&gt;gaps.sort()&lt;br&gt;
print(“messages:”, len(gaps) + 1, “median gap ms:”, gaps[len(gaps) // 2])&lt;/p&gt;

&lt;p&gt;The SUBSCRIBE message above is illustrative. Use the exact one from the documentation.&lt;/p&gt;

&lt;p&gt;Honest limitation: gaps between messages show update cadence, not true end-to-end latency. To measure that, compare each event’s timestamp against a trusted reference such as an official match clock or a second vendor.&lt;/p&gt;

&lt;p&gt;Step 5: Receive webhooks locally&lt;/p&gt;

&lt;p&gt;Save this as server.js:&lt;/p&gt;

&lt;p&gt;import express from “express”;&lt;br&gt;
const app = express();&lt;br&gt;
app.use(express.json());&lt;/p&gt;

&lt;p&gt;app.post(“/webhook/sports”, (req, res) =&amp;gt; {&lt;br&gt;
const receivedAt = Date.now();&lt;br&gt;
console.log(receivedAt, JSON.stringify(req.body).slice(0, 200));&lt;br&gt;
res.sendStatus(200);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;app.listen(3000, () =&amp;gt; console.log(“listening on port 3000”));&lt;/p&gt;

&lt;p&gt;Acknowledge fast and process asynchronously. Expose the server with a tunnel such as ngrok during testing, and register the URL as described in the documentation (&lt;a href="https://orbistats.com/developers/documentation.html" rel="noopener noreferrer"&gt;https://orbistats.com/developers/documentation.html&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Step 6: Your results template&lt;/p&gt;

&lt;p&gt;Fill this in after running the harness. Replace every dash with your own measurement, region and date.&lt;/p&gt;

&lt;p&gt;Orbistats | Free pass | Region: - | Median ms: - | p95 ms: - | Schema stable: - | Push: WebSocket + webhooks (per docs) | Quota used: -&lt;br&gt;
API-Football | Free | Region: - | Median ms: - | p95 ms: - | Schema stable: - | Push: verify | Quota used: -&lt;br&gt;
SportsGameOdds | Free | Region: - | Median ms: - | p95 ms: - | Schema stable: - | Push: higher tiers (per docs) | Quota used: -&lt;br&gt;
The Odds API | Free | Region: - | Median ms: - | p95 ms: - | Schema stable: - | Push: verify | Quota used: -&lt;br&gt;
Sportmonks | Entry | Region: - | Median ms: - | p95 ms: - | Schema stable: - | Push: verify | Quota used: -&lt;/p&gt;

&lt;p&gt;Publish the methodology next to the table: region, time of day, number of samples and whether a match was live.&lt;/p&gt;

&lt;p&gt;What the public docs already tell you&lt;/p&gt;

&lt;p&gt;While you wait for your own data, here is what the vendors say about themselves. Verify all of it.&lt;/p&gt;

&lt;p&gt;Sportradar (&lt;a href="https://developer.sportradar.com/getting-started/docs/get-started):" rel="noopener noreferrer"&gt;https://developer.sportradar.com/getting-started/docs/get-started):&lt;/a&gt; 80+ sports, 500+ leagues, push on selected packages, quote-based.&lt;br&gt;
Sportmonks (&lt;a href="https://www.sportmonks.com/football-api/coverage/):" rel="noopener noreferrer"&gt;https://www.sportmonks.com/football-api/coverage/):&lt;/a&gt; 2,200+ football leagues, plans at €29, €99 and €249 per month.&lt;br&gt;
SportsGameOdds (&lt;a href="https://sportsgameodds.com/docs/basics):" rel="noopener noreferrer"&gt;https://sportsgameodds.com/docs/basics):&lt;/a&gt; 67+ leagues, 28+ sports, 85+ bookmakers depending on plan, object-based billing.&lt;br&gt;
API-Football (&lt;a href="https://www.api-football.com/coverage):" rel="noopener noreferrer"&gt;https://www.api-football.com/coverage):&lt;/a&gt; 1,248 leagues and cups, 100 free requests a day.&lt;br&gt;
Orbistats (&lt;a href="https://orbistats.com/):" rel="noopener noreferrer"&gt;https://orbistats.com/):&lt;/a&gt; 13 sports (football, basketball, American football, cricket, tennis, baseball, esports, combat sports, volleyball, handball, ice hockey, golf, horse racing). Passes at €0, €19, €79 and €1,999 per month. Some seasons back to 2010, per the company. Try its sandbox (&lt;a href="https://orbistats.com/developers/sandbox.html" rel="noopener noreferrer"&gt;https://orbistats.com/developers/sandbox.html&lt;/a&gt;) and check the status page (&lt;a href="https://orbistats.com/developers/status.html" rel="noopener noreferrer"&gt;https://orbistats.com/developers/status.html&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Pitfalls to avoid&lt;/p&gt;

&lt;p&gt;Benchmarking one endpoint and generalising to the whole API.&lt;br&gt;
Forgetting that free tiers can be throttled differently from paid ones.&lt;br&gt;
Comparing a cached response to a fresh one.&lt;br&gt;
Ignoring commercial rights: a fast feed you cannot redistribute is useless.&lt;br&gt;
Burning your free quota in the first run. Lower N.&lt;/p&gt;

&lt;p&gt;Next steps&lt;/p&gt;

&lt;p&gt;Extend the harness with odds checks (compare the same fixture’s 1X2 prices across vendors), a coverage check for your target leagues using Orbistats’ per-sport pages (&lt;a href="https://orbistats.com/sports/cricket.html" rel="noopener noreferrer"&gt;https://orbistats.com/sports/cricket.html&lt;/a&gt;), and a nightly GitHub Action that appends to results.csv so you can chart reliability over weeks. If you want an access pass to try the multi-sport feed, you can request one here (&lt;a href="https://orbistats.com/request-access.html" rel="noopener noreferrer"&gt;https://orbistats.com/request-access.html&lt;/a&gt;), and the glossary (&lt;a href="https://orbistats.com/resources/glossary.html" rel="noopener noreferrer"&gt;https://orbistats.com/resources/glossary.html&lt;/a&gt;) helps if odds terms are new.&lt;/p&gt;

</description>
      <category>api</category>
      <category>python</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Surviving a 150-Requests-a-Day Free Tier: Caching Patterns for Sports APIs</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Sat, 10 Oct 2026 12:37:21 +0000</pubDate>
      <link>https://dev.to/orbistats/surviving-a-150-requests-a-day-free-tier-caching-patterns-for-sports-apis-3hf7</link>
      <guid>https://dev.to/orbistats/surviving-a-150-requests-a-day-free-tier-caching-patterns-for-sports-apis-3hf7</guid>
      <description>&lt;p&gt;Surviving a 150-Requests-a-Day Free Tier: Caching Patterns for Sports APIs&lt;/p&gt;

&lt;p&gt;You sign up for a free sports API key, make your first request, and it works. Then you read the limit: 150 requests per day.&lt;/p&gt;

&lt;p&gt;In a terminal, that feels generous. In a real app, it disappears fast.&lt;/p&gt;

&lt;p&gt;Here is the math. 150 calls spread over 24 hours is one call every 9.6 minutes. If your app gets 10,000 page views a day and each view calls the API, your quota is gone in about 90 seconds of traffic. To survive, your cache hit rate must be at least 98.5%.&lt;/p&gt;

&lt;p&gt;That is not a tuning problem. It is an architecture problem, and this guide solves it step by step in plain Node.js.&lt;/p&gt;

&lt;p&gt;A note on limits. 150/day is a common free-tier ceiling across sports-data providers, and it is the constraint this guide designs for. Limits differ by provider and plan. The Orbistats Free plan, for example, is a time-boxed access window rather than a daily counter. The discipline is the same: every call is precious.&lt;/p&gt;

&lt;p&gt;Prerequisites: Node.js 18+ (built-in fetch), basic JavaScript, and an API key. The quickstart guide takes you from signup to your first request.&lt;/p&gt;

&lt;p&gt;About endpoints: the paths below follow the pattern in the Orbistats docs (&lt;a href="https://api.orbistats.com/v1/%7Bsport%7D/" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1/{sport}/&lt;/a&gt;... with Bearer auth). Confirm exact paths and query parameters in the API reference before shipping.&lt;/p&gt;

&lt;p&gt;Step 1: Know the shelf life of your data&lt;/p&gt;

&lt;p&gt;The most common mistake with a small quota is using one TTL for everything. Sports data has very different shelf lives:&lt;/p&gt;

&lt;p&gt;Data    Changes Sensible TTL&lt;br&gt;
Countries, competitions Almost never    7 days&lt;br&gt;
Teams, player profiles  Rarely  24 hours&lt;br&gt;
Fixtures    A few times a day   3-6 hours&lt;br&gt;
Standings   After each match ends   30-60 minutes&lt;br&gt;
Live score  Every few seconds   30-60 seconds&lt;br&gt;
Finished match  Never   Forever&lt;br&gt;
Historical seasons  Never   Forever&lt;/p&gt;

&lt;p&gt;The last two rows are where free tiers are won. A finished match is immutable. Asking for it twice wastes a call.&lt;/p&gt;

&lt;p&gt;Step 2: Budget your 150 calls like money&lt;/p&gt;

&lt;p&gt;Write the budget before you write any cache code. Here is one for an app covering all 13 sports, including football, basketball and cricket:&lt;/p&gt;

&lt;p&gt;Bucket  Calls/day   Why&lt;br&gt;
Live reserve    40  Spent only when a match is on&lt;br&gt;
Fixtures (13 sports x 1)    13  Schedules barely move&lt;br&gt;
Standings (13 sports x 2)   26  Morning and late evening&lt;br&gt;
Results sync (13 sports x 2)    26  Save finished matches forever&lt;br&gt;
Cache-miss buffer   45  Retries and surprises&lt;br&gt;
Total   150 &lt;/p&gt;

&lt;p&gt;That is about 11.5 calls per sport per day.&lt;/p&gt;

&lt;p&gt;Notice what is missing: “one call per user request.” Users never talk to the API. Users talk to your cache. Only your background jobs talk to the API.&lt;/p&gt;

&lt;p&gt;Covering fewer sports? Your budget is much roomier. Start with the sports your audience actually watches.&lt;/p&gt;

&lt;p&gt;Step 3: Build a TTL cache with LRU eviction&lt;/p&gt;

&lt;p&gt;The foundation is an in-memory cache that tracks freshness and staleness separately. Later steps depend on that split.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// cache.js&lt;br&gt;
export class TTLCache {&lt;br&gt;
  constructor({ maxEntries = 500 } = {}) {&lt;br&gt;
    this.store = new Map();&lt;br&gt;
    this.maxEntries = maxEntries;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;get(key) {&lt;br&gt;
    const entry = this.store.get(key);&lt;br&gt;
    if (!entry) return null;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// LRU bump: re-insert so recently used keys sit at the end
this.store.delete(key);
this.store.set(key, entry);

const now = Date.now();
return {
  value: entry.value,
  fresh: now &amp;lt; entry.freshUntil,   // serve with zero network
  usable: now &amp;lt; entry.staleUntil,  // serve, but refresh in background
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

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

&lt;p&gt;set(key, value, ttlMs, staleMs = 0) {&lt;br&gt;
    const now = Date.now();&lt;br&gt;
    this.store.delete(key);&lt;br&gt;
    this.store.set(key, {&lt;br&gt;
      value,&lt;br&gt;
      freshUntil: now + ttlMs,&lt;br&gt;
      staleUntil: now + ttlMs + staleMs,&lt;br&gt;
    });&lt;br&gt;
    if (this.store.size &amp;gt; this.maxEntries) {&lt;br&gt;
      this.store.delete(this.store.keys().next().value); // evict LRU&lt;br&gt;
    }&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Each entry has two clocks:&lt;/p&gt;

&lt;p&gt;Fresh: serve instantly, no call.&lt;br&gt;
Stale but usable: serve instantly and refresh quietly.&lt;br&gt;
Expired: keep it only as an emergency fallback (Step 5).&lt;/p&gt;

&lt;p&gt;Step 4: Stop cache stampedes with single-flight&lt;/p&gt;

&lt;p&gt;Here is a quiet quota killer. Your football standings entry expires at 12:00:00. At 12:00:01, 200 users load your page. Every request sees an empty cache and fires its own API call. You just spent 200 calls on one piece of data.&lt;/p&gt;

&lt;p&gt;The fix is single-flight: if a request for key X is already running, everyone else waits for the same promise.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
refresh(key, url, ttlMs, staleMs, kind) {&lt;br&gt;
  // Someone is already fetching this key? Join them.&lt;br&gt;
  if (this.inflight.has(key)) return this.inflight.get(key);&lt;/p&gt;

&lt;p&gt;const promise = (async () =&amp;gt; {&lt;br&gt;
    // budget check + fetch + cache.set (full version in Step 7)&lt;br&gt;
  })().finally(() =&amp;gt; this.inflight.delete(key));&lt;/p&gt;

&lt;p&gt;this.inflight.set(key, promise);&lt;br&gt;
  return promise;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;200 simultaneous users now cost 1 call. This one pattern often saves more quota than any TTL tweak.&lt;/p&gt;

&lt;p&gt;Step 5: Serve stale data on purpose&lt;/p&gt;

&lt;p&gt;Stale-while-revalidate (SWR) works like this:&lt;/p&gt;

&lt;p&gt;The entry is a bit old, so return it immediately.&lt;br&gt;
Start one background refresh.&lt;br&gt;
The next visitor gets fresh data.&lt;/p&gt;

&lt;p&gt;Stale-if-error is its cousin. If the API fails or your quota is spent, serve the last known value instead of an error page. A ten-minute-old standings table beats a 500 every time.&lt;/p&gt;

&lt;p&gt;When something looks wrong, check the provider’s status page first. It is the fastest way to learn whether the problem is your cache or their infrastructure.&lt;/p&gt;

&lt;p&gt;Step 6: Add a budget guard&lt;/p&gt;

&lt;p&gt;Caching reduces calls. A budget guard guarantees you never exceed the limit, even when you ship a bug. It also reserves part of the quota for live data, so a runaway standings job cannot starve a live match.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// budget.js&lt;br&gt;
export class DailyBudget {&lt;br&gt;
  constructor({ limit = 150, reserveForLive = 40 } = {}) {&lt;br&gt;
    this.limit = limit;&lt;br&gt;
    this.reserveForLive = reserveForLive;&lt;br&gt;
    this.day = this.today();&lt;br&gt;
    this.used = 0;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;today() {&lt;br&gt;
    // Check your provider: UTC midnight reset, or a rolling 24h window?&lt;br&gt;
    return new Date().toISOString().slice(0, 10);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;roll() {&lt;br&gt;
    const t = this.today();&lt;br&gt;
    if (t !== this.day) { this.day = t; this.used = 0; }&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;canSpend(kind = 'static') {&lt;br&gt;
    this.roll();&lt;br&gt;
    const ceiling = kind === 'live' ? this.limit : this.limit - this.reserveForLive;&lt;br&gt;
    return this.used &amp;lt; ceiling;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;spend() { this.roll(); this.used += 1; }&lt;br&gt;
  remaining() { this.roll(); return this.limit - this.used; }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;This counter lives in memory, so it resets on restart. Step 14 shows how to persist it.&lt;/p&gt;

&lt;p&gt;Step 7: Assemble the cached client&lt;/p&gt;

&lt;p&gt;Now combine everything: cache, single-flight, SWR, stale-if-error and the budget guard.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// client.js&lt;br&gt;
import { TTLCache } from './cache.js';&lt;br&gt;
import { DailyBudget } from './budget.js';&lt;/p&gt;

&lt;p&gt;export class SportsClient {&lt;br&gt;
  constructor({&lt;br&gt;
    apiKey,&lt;br&gt;
    baseUrl = '&lt;a href="https://api.orbistats.com/v1" rel="noopener noreferrer"&gt;https://api.orbistats.com/v1&lt;/a&gt;',&lt;br&gt;
    cache = new TTLCache(),&lt;br&gt;
    budget = new DailyBudget(),&lt;br&gt;
  }) {&lt;br&gt;
    Object.assign(this, { apiKey, baseUrl, cache, budget });&lt;br&gt;
    this.inflight = new Map();&lt;br&gt;
    this.stats = { hits: 0, stale: 0, network: 0, errors: 0 };&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;buildUrl(path, params = {}) {&lt;br&gt;
    const url = new URL(this.baseUrl + path);&lt;br&gt;
    // Sorted params: ?a=1&amp;amp;b=2 and ?b=2&amp;amp;a=1 share one cache key&lt;br&gt;
    Object.keys(params).sort().forEach((k) =&amp;gt; url.searchParams.set(k, params[k]));&lt;br&gt;
    return url;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async get(path, { params, ttlMs, staleMs = 0, kind = 'static' } = {}) {&lt;br&gt;
    const url = this.buildUrl(path, params);&lt;br&gt;
    const key = url.pathname + url.search;&lt;br&gt;
    const hit = this.cache.get(key);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (hit?.fresh) {                       // 1) fresh: free answer
  this.stats.hits++;
  return { data: hit.value, source: 'cache' };
}

if (hit?.usable) {                      // 2) stale: answer now, refresh quietly
  this.stats.stale++;
  this.refresh(key, url, ttlMs, staleMs, kind).catch(() =&amp;gt; {});
  return { data: hit.value, source: 'stale' };
}

try {                                   // 3) miss: network, fall back on failure
  const data = await this.refresh(key, url, ttlMs, staleMs, kind);
  return { data, source: 'network' };
} catch (err) {
  this.stats.errors++;
  if (hit) return { data: hit.value, source: 'stale-if-error' };
  throw err;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

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

&lt;p&gt;refresh(key, url, ttlMs, staleMs, kind) {&lt;br&gt;
    if (this.inflight.has(key)) return this.inflight.get(key);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise = (async () =&amp;gt; {
  if (!this.budget.canSpend(kind)) throw new Error('BUDGET_EXHAUSTED');
  this.budget.spend();
  this.stats.network++;

  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${this.apiKey}` },
  });

  if (res.status === 429) {
    this.budget.used = this.budget.limit; // our count was wrong; stop spending
    throw new Error('RATE_LIMITED');
  }
  if (!res.ok) throw new Error(`HTTP_${res.status}`);

  const data = await res.json();
  this.cache.set(key, data, ttlMs, staleMs);
  return data;
})().finally(() =&amp;gt; this.inflight.delete(key));

this.inflight.set(key, promise);
return promise;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

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

&lt;p&gt;hitRate() {&lt;br&gt;
    const { hits, stale, network } = this.stats;&lt;br&gt;
    const total = hits + stale + network;&lt;br&gt;
    return total ? (hits + stale) / total : 0;&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Usage:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
const client = new SportsClient({ apiKey: process.env.ORBISTATS_KEY });&lt;/p&gt;

&lt;p&gt;const { data, source } = await client.get('/football/standings', {&lt;br&gt;
  params: { competition: 'premier-league' },&lt;br&gt;
  ttlMs: 2_700_000,       // fresh for 45 minutes&lt;br&gt;
  staleMs: 10_800_000,    // then usable for 3 more hours&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Every call site declares its own TTL. Standings and live scores never share a lifetime by accident.&lt;/p&gt;

&lt;p&gt;Step 8: Store finished matches forever&lt;/p&gt;

&lt;p&gt;An in-memory cache vanishes on restart. For data that can never change, use a permanent store. SQLite is perfect: no server, one file, very fast.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
// finished.js&lt;br&gt;
import Database from 'better-sqlite3';&lt;/p&gt;

&lt;p&gt;const db = new Database('sports.db');&lt;br&gt;
db.exec(&lt;code&gt;&lt;br&gt;
  CREATE TABLE IF NOT EXISTS finished_matches (&lt;br&gt;
    id       TEXT PRIMARY KEY,&lt;br&gt;
    sport    TEXT NOT NULL,&lt;br&gt;
    payload  TEXT NOT NULL,&lt;br&gt;
    saved_at INTEGER NOT NULL&lt;br&gt;
  )&lt;br&gt;
&lt;/code&gt;);&lt;/p&gt;

&lt;p&gt;const selectOne = db.prepare('SELECT payload FROM finished_matches WHERE id = ?');&lt;br&gt;
const upsert = db.prepare(&lt;br&gt;
  'INSERT OR REPLACE INTO finished_matches VALUES (?, ?, ?, ?)'&lt;br&gt;
);&lt;/p&gt;

&lt;p&gt;export const getFinished = (id) =&amp;gt; {&lt;br&gt;
  const row = selectOne.get(id);&lt;br&gt;
  return row ? JSON.parse(row.payload) : null;&lt;br&gt;
};&lt;/p&gt;

&lt;p&gt;export function saveFinished(match, sport) {&lt;br&gt;
  // Confirm the exact "finished" status value in the API reference&lt;br&gt;
  if (match.status !== 'finished') return false;&lt;br&gt;
  upsert.run(match.match_id, sport, JSON.stringify(match), Date.now());&lt;br&gt;
  return true;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;A nightly results-sync job now makes one call per sport, saves every finished match, and never asks for it again.&lt;/p&gt;

&lt;p&gt;The same idea powers model training. If you are backtesting on past seasons, download once and keep your own copy. The Historical Sports Data API is built for exactly that, and the Sports Statistics API pairs well with it for player and team aggregates.&lt;/p&gt;

&lt;p&gt;Step 9: Warm the cache on a schedule&lt;/p&gt;

&lt;p&gt;This is the mental shift that makes 150 calls viable.&lt;/p&gt;

&lt;p&gt;Before: user opens page, your server calls the API, user waits.&lt;br&gt;
After: a scheduled job calls the API, the cache stays warm, the user gets an instant answer with zero API calls.&lt;br&gt;
js&lt;br&gt;
// warmer.js&lt;br&gt;
const SPORTS = [&lt;br&gt;
  'football', 'basketball', 'american-football', 'cricket', 'tennis',&lt;br&gt;
  'baseball', 'esports', 'combat-sports', 'volleyball', 'handball',&lt;br&gt;
  'ice-hockey', 'golf', 'horse-racing',&lt;br&gt;
];&lt;/p&gt;

&lt;p&gt;const ONE_HOUR = 3_600_000;&lt;br&gt;
const SIX_HOURS = 21_600_000;&lt;br&gt;
const TWELVE_HOURS = 43_200_000;&lt;/p&gt;

&lt;p&gt;async function warm(client, resource, ttlMs, staleMs) {&lt;br&gt;
  for (const sport of SPORTS) {&lt;br&gt;
    try {&lt;br&gt;
      await client.get(&lt;code&gt;/${sport}/${resource}&lt;/code&gt;, { ttlMs, staleMs });&lt;br&gt;
    } catch (err) {&lt;br&gt;
      console.warn(&lt;code&gt;warm ${sport}/${resource} failed:&lt;/code&gt;, err.message);&lt;br&gt;
    }&lt;br&gt;
  }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;export function startWarmers(client) {&lt;br&gt;
  warm(client, 'fixtures', SIX_HOURS, TWELVE_HOURS);   // on boot&lt;br&gt;
  setInterval(() =&amp;gt; warm(client, 'fixtures', SIX_HOURS, TWELVE_HOURS), SIX_HOURS);&lt;br&gt;
  setInterval(() =&amp;gt; warm(client, 'standings', ONE_HOUR, SIX_HOURS), TWELVE_HOURS);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Public routes then read only from the cache and never fall through to the network:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
app.get('/api/standings/:sport', (req, res) =&amp;gt; {&lt;br&gt;
  const hit = client.cache.get(&lt;code&gt;/v1/${req.params.sport}/standings&lt;/code&gt;);&lt;br&gt;
  if (!hit) return res.status(503).json({ error: 'Warming up, retry shortly' });&lt;br&gt;
  res.set('Cache-Control', 'public, max-age=60'); // CDN/browser = second cache layer&lt;br&gt;
  res.json(hit.value);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;That Cache-Control header gives you a free second cache layer at your CDN and in the browser.&lt;/p&gt;

&lt;p&gt;Step 10: Fetch wide, slice locally&lt;/p&gt;

&lt;p&gt;Per-item endpoints drain quota:&lt;/p&gt;

&lt;p&gt;text&lt;br&gt;
GET /football/matches/101   &amp;lt;- 1 call&lt;br&gt;
GET /football/matches/102   &amp;lt;- 1 call&lt;br&gt;
GET /football/matches/103   &amp;lt;- 1 call&lt;/p&gt;

&lt;p&gt;List endpoints are cheap:&lt;/p&gt;

&lt;p&gt;text&lt;br&gt;
GET /football/fixtures      &amp;lt;- 1 call, filter in your own code&lt;/p&gt;

&lt;p&gt;Whenever you write a loop that makes one API call per item, stop and look for a list endpoint. The Sports Data API covers fixtures, results, standings, teams and competitions, so a list is usually available. Check the documentation for date and competition filters.&lt;/p&gt;

&lt;p&gt;Fetch the day’s fixtures once, then slice by team, league or kickoff time in memory.&lt;/p&gt;

&lt;p&gt;Step 11: Push instead of poll for live data&lt;/p&gt;

&lt;p&gt;Live scores are the hardest data to cache, because a 30-second TTL on a busy match still means two calls a minute. Poll one match for 2 hours and you have spent 240 calls on a single game.&lt;/p&gt;

&lt;p&gt;Polling live data on a small quota does not work. Switch to push.&lt;/p&gt;

&lt;p&gt;Webhooks: the provider calls your endpoint when something happens (goal, card, full time).&lt;br&gt;
WebSocket API: one persistent connection streams events as they occur.&lt;br&gt;
Live Scores API: the REST endpoint for snapshots when you need current state.&lt;/p&gt;

&lt;p&gt;A webhook receiver that writes straight into your cache:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import crypto from 'node:crypto';&lt;br&gt;
import express from 'express';&lt;/p&gt;

&lt;p&gt;const app = express();&lt;/p&gt;

&lt;p&gt;// Verify signatures against the RAW body, so use express.raw here&lt;br&gt;
app.post('/webhooks/sports', express.raw({ type: 'application/json' }), (req, res) =&amp;gt; {&lt;br&gt;
  const sig = req.get('X-Signature') || '';   // header name: confirm in the webhooks docs&lt;br&gt;
  const expected = crypto&lt;br&gt;
    .createHmac('sha256', process.env.WEBHOOK_SECRET)&lt;br&gt;
    .update(req.body)&lt;br&gt;
    .digest('hex');&lt;/p&gt;

&lt;p&gt;const ok =&lt;br&gt;
    sig.length === expected.length &amp;amp;&amp;amp;&lt;br&gt;
    crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));&lt;br&gt;
  if (!ok) return res.sendStatus(401);&lt;/p&gt;

&lt;p&gt;const event = JSON.parse(req.body.toString('utf8'));&lt;br&gt;
  client.cache.set(&lt;code&gt;live:${event.match_id}&lt;/code&gt;, event, 60_000, 300_000);&lt;/p&gt;

&lt;p&gt;res.sendStatus(200);  // acknowledge fast, do heavy work elsewhere&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Pushed events do not count as polling calls, so your live reserve stays untouched. Verify the real signature scheme in the webhook docs before trusting this code.&lt;/p&gt;

&lt;p&gt;If you only need a score box on a page, a drop-in widget can remove your live-data work entirely.&lt;/p&gt;

&lt;p&gt;Step 12: Measure your hit rate&lt;/p&gt;

&lt;p&gt;You cannot protect a quota you do not measure. Expose three numbers:&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
app.get('/internal/metrics', (_req, res) =&amp;gt; {&lt;br&gt;
  res.json({&lt;br&gt;
    hitRate: client.hitRate(),          // target: above 0.985&lt;br&gt;
    callsRemaining: client.budget.remaining(),&lt;br&gt;
    ...client.stats,&lt;br&gt;
  });&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Check them like this:&lt;/p&gt;

&lt;p&gt;Hit rate below 95%? A TTL is too short, or a cache key is unstable (unsorted params, timestamps in the URL).&lt;br&gt;
callsRemaining falling fast in the morning? A warmer is running too often.&lt;br&gt;
Many stale-if-error responses? Check the upstream status page, then your network.&lt;/p&gt;

&lt;p&gt;Step 13: Test without spending a single call&lt;/p&gt;

&lt;p&gt;Here is the most useful habit on a small quota: never spend real calls on testing your cache. Stub fetch and assert on call counts.&lt;/p&gt;

&lt;p&gt;js&lt;br&gt;
import assert from 'node:assert';&lt;br&gt;
import { SportsClient } from './client.js';&lt;/p&gt;

&lt;p&gt;const calls = [];&lt;br&gt;
globalThis.fetch = async (url) =&amp;gt; {&lt;br&gt;
  calls.push(String(url));&lt;br&gt;
  return new Response(JSON.stringify({ table: [] }), { status: 200 });&lt;br&gt;
};&lt;/p&gt;

&lt;p&gt;const client = new SportsClient({ apiKey: 'test' });&lt;/p&gt;

&lt;p&gt;// 200 simultaneous users, one standings table&lt;br&gt;
await Promise.all(&lt;br&gt;
  Array.from({ length: 200 }, () =&amp;gt;&lt;br&gt;
    client.get('/football/standings', { ttlMs: 60_000 })&lt;br&gt;
  )&lt;br&gt;
);&lt;/p&gt;

&lt;p&gt;assert.equal(calls.length, 1, 'single-flight should collapse 200 calls into 1');&lt;br&gt;
console.log('OK, network calls:', calls.length);&lt;/p&gt;

&lt;p&gt;One practical tip: Orbistats access works in time windows. The Free plan is one hour with no card, and the timer starts when you open your activation link. Starter is 24 hours and Growth is five days, with every sport and endpoint on every plan. Current details are on the pricing page.&lt;/p&gt;

&lt;p&gt;So build and test everything above locally, with stubbed responses, before you start the clock. Steps 1 to 12 need no live data. Then spend your window verifying real payloads and field names, using the sandbox and SDKs, and let one real match prove the pipeline.&lt;/p&gt;

&lt;p&gt;Step 14: Production hardening checklist&lt;/p&gt;

&lt;p&gt;The tutorial version is correct. A production version is also operable:&lt;/p&gt;

&lt;p&gt;Persist the budget in Redis. An in-memory counter resets on every deploy. Use an atomic increment:&lt;br&gt;
js&lt;br&gt;
const key = &lt;code&gt;budget:${new Date().toISOString().slice(0, 10)}&lt;/code&gt;;&lt;br&gt;
const used = await redis.incr(key);&lt;br&gt;
if (used === 1) await redis.expire(key, 129_600); // 36 hours&lt;br&gt;
if (used &amp;gt; ceiling) { await redis.decr(key); return false; }&lt;br&gt;
Move the cache to Redis too if you run more than one server. Otherwise each instance warms its own copy and multiplies your calls.&lt;br&gt;
Run warmers in a single process. Two warmers means double spend. Use one worker or a distributed lock.&lt;br&gt;
Add jitter to TTLs. If 13 sports all expire at the same second, you create your own stampede. Add 5-10% random variation.&lt;br&gt;
Alert at 80% quota. Page yourself before the limit, not after.&lt;br&gt;
Cache errors briefly. If an endpoint returns 404 or 5xx, remember that for 30-60 seconds so retries do not burn calls.&lt;br&gt;
Log the source of every response (cache, stale, network). It makes debugging trivial.&lt;br&gt;
Watch the changelog. Field changes can silently break cached payload shapes. Follow the changelog and version your cache keys (v1:).&lt;br&gt;
Know when to upgrade. If your hit rate is above 98% and you still run out, you have outgrown the free tier. That is a good problem, and the comparison pages show how providers stack up.&lt;/p&gt;

&lt;p&gt;Wrapping up&lt;/p&gt;

&lt;p&gt;Surviving a tiny quota is not about clever tricks. It is about never asking the same question twice:&lt;/p&gt;

&lt;p&gt;Give each data type its own TTL&lt;br&gt;
Collapse duplicate requests with single-flight&lt;br&gt;
Serve stale data on purpose&lt;br&gt;
Guard the budget with a live reserve&lt;br&gt;
Store immutable data forever&lt;br&gt;
Warm caches from schedules, not users&lt;br&gt;
Push, don’t poll, for live data&lt;/p&gt;

&lt;p&gt;Do these and 150 calls a day can comfortably serve thousands of users.&lt;/p&gt;

&lt;p&gt;Want to try it on real data? Request access, and keep the glossary and odds converter tools handy if you plan to add the Odds API later.&lt;/p&gt;

&lt;p&gt;What caching trick saved your quota? Tell me in the comments.&lt;/p&gt;

</description>
      <category>api</category>
      <category>redis</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Live Score Widget in React: Embed or Build It in 10 Minutes</title>
      <dc:creator>orbistats</dc:creator>
      <pubDate>Sat, 10 Oct 2026 12:26:47 +0000</pubDate>
      <link>https://dev.to/orbistats/live-score-widget-in-react-embed-or-build-it-in-10-minutes-2dn4</link>
      <guid>https://dev.to/orbistats/live-score-widget-in-react-embed-or-build-it-in-10-minutes-2dn4</guid>
      <description>&lt;p&gt;Liquid syntax error: Variable '{{% raw %}' was not properly terminated with regexp: /\}\}/&lt;/p&gt;
</description>
      <category>react</category>
      <category>javascript</category>
      <category>api</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
