Skip to content

Livematches in play

Demo: Matchboard, opens in a new tab

Tutorial

Use a Premier League table API in Python

This tutorial calls a Premier League table API from Python with a free key. It finds the current season, fetches the standings and prints them as a tidy table, then loads them into pandas, reads the European places and each team's form, and caches the answer so a script that runs all day costs a handful of requests.

  • Free plan key
  • 15 min
  • Python
  • pandas
  • Updated

What you will build

A short Python script that prints the current Premier League table in your terminal: position, played, won, drawn, lost, goals, goal difference, points and the last five results. On top of it you will add three things a real project needs sooner or later:

  • A pandas DataFrame of the table, for sorting, new columns and CSV export. This step is optional; the rest runs on the standard library and the client.
  • Zones and form: which teams sit in the Champions League places or the relegation zone, and who is in the best run of results.
  • A small file cache, so the script can run every few minutes without spending requests on data that has not changed.

1. Install the client and set your key

The datasportsapi package on PyPI is a small client with no dependencies: one get() that adds your key, returns the JSON envelope as a dict and raises DataSportsAPIError for any answer that is not a success. It needs Python 3.10 or later.

Terminal
pip install datasportsapi
export DATASPORTSAPI_API_KEY="sk_live_…"

The key comes from your dashboard after you sign up. The client reads it from DATASPORTSAPI_API_KEY, so it never has to appear in your code or your repository. Without the package, any HTTP library works: send Authorization: Bearer sk_live_… to https://api.datasportsapi.com.

2. Find the league id

Leagues are addressed by a numeric id. The Premier League is 195828. For any other competition, ask the search endpoint and narrow it to leagues with type=league:

Terminal
curl -H "Authorization: Bearer $DATASPORTSAPI_API_KEY" \
  "https://api.datasportsapi.com/v2/search?q=premier%20league&type=league"
Response (trimmed)
{
  "data": [
    { "type": "league", "id": 195828, "name": "Premier League", "slug": "premier-league",
      "sport": "football", "image": "https://cdn.datasportsapi.com/v2/leagues/195828/logo" },
    { "type": "league", "id": 195829, "name": "Egyptian Premier League", "slug": "premier-league",
      "sport": "football", "image": "https://cdn.datasportsapi.com/v2/leagues/195829/logo" }
  ],
  "meta": { "query": "premier league", "type": "league", "page": 0, "count": 20, "hasNextPage": true }
}

Many countries have a "Premier League", and the slug alone does not tell them apart, so check name and sport before you hard-code an id. Two other ways in: GET /v2/leagues/popular?sport=football returns the big competitions with their ids, in the order a menu would show them, and the search reference covers paging and the other hit types.

3. Pick the current season

A table belongs to a season, and the standings endpoint will not guess which one you mean: season is required. GET /v2/leagues/195828/seasons lists every season, most recent first, so the current one is the first entry:

Response (trimmed)
{
  "data": [
    { "id": 200386, "name": "Premier League 26/27", "year": "26/27", "startYear": 2026, "endYear": 2027 },
    { "id": 201993, "name": "Premier League 25/26", "year": "25/26", "startYear": 2025, "endYear": 2026 },
    …
  ]
}

Do not hard-code 200386. In August the list gains a new first entry, and a script that reads it each time moves on to the new season by itself.

4. Fetch the standings

With both ids in hand, GET /v2/leagues/195828/standings?season=200386 returns one row per team, already sorted by position. One row of the real answer, and the meta block:

Response (trimmed)
{
  "data": [
    {
      "position": 1,
      "team": { "id": 3758, "name": "Arsenal", "slug": "arsenal", "shortName": "Arsenal", "code": "ARS",
                "image": "https://cdn.datasportsapi.com/v2/teams/3758/logo" },
      "played": 10, "wins": 9, "draws": 0, "losses": 1,
      "scoresFor": 15, "scoresAgainst": 5, "scoreDifference": 10, "points": 27,
      "zone": "Champions League",
      "form": ["win", "win", "win", "win", "win"]
    },
    …
  ],
  "meta": { "season": 200386, "type": "overall", "group": "Premier League 26/27",
            "count": 20, "overall": true, "scoreUnit": "goals" }
}

The column names are the same in every sport, which is why goals are called scoresFor and scoresAgainst; meta.scoreUnit says what they count. The real row also carries columns that only other sports fill, such as winPercentage or overtimeLosses, and they are null in football.

5. Print a clean table

Save this as table.py. The call() helper is the part worth copying into other projects: on 429 rate_limited it sleeps for the Retry-After seconds the API sent and tries again, and on a network error it backs off and retries a few times. It does not retry 429 quota_exceeded, because the daily allowance only refills at midnight UTC.

table.py
import sys
import time

from datasportsapi import DataSportsAPI, DataSportsAPIError

LEAGUE_ID = 195828  # Premier League
client = DataSportsAPI()  # reads DATASPORTSAPI_API_KEY


def call(path, **params):
    """GET with a polite retry: waits out 429 rate_limited and brief network errors."""
    for attempt in range(4):
        try:
            return client.get(path, **params)
        except DataSportsAPIError as e:
            # rate_limited: the minute window is full; Retry-After is a few seconds.
            # quota_exceeded: the day's allowance is spent; waiting makes no sense.
            if e.status == 429 and e.code == "rate_limited" and attempt < 3:
                time.sleep((e.retry_after or 60) + 1)
                continue
            raise
        except OSError:  # DNS failure, refused connection, timeout
            if attempt < 3:
                time.sleep(5 * 2**attempt)
                continue
            raise


def current_season(league_id):
    seasons = call(f"/v2/leagues/{league_id}/seasons")["data"]
    return seasons[0]  # the list is most recent first


def standings(league_id, season_id):
    return call(f"/v2/leagues/{league_id}/standings", season=season_id)["data"]


FORM = {"win": "W", "draw": "D", "loss": "L"}


def form_text(row):
    return "".join(FORM.get(r, "?") for r in row["form"] or [])


def print_table(rows):
    print(f"{'#':>2}  {'Team':<16}{'P':>3}{'W':>3}{'D':>3}{'L':>3}{'GF':>4}{'GA':>4}{'GD':>5}{'Pts':>5}  Form")
    for r in rows:
        print(
            f"{r['position']:>2}  {r['team']['shortName']:<16}"
            f"{r['played']:>3}{r['wins']:>3}{r['draws']:>3}{r['losses']:>3}"
            f"{r['scoresFor']:>4}{r['scoresAgainst']:>4}{r['scoreDifference']:>+5}"
            f"{r['points']:>5}  {form_text(r)}"
        )


if __name__ == "__main__":
    try:
        season = current_season(LEAGUE_ID)
        rows = standings(LEAGUE_ID, season["id"])
    except DataSportsAPIError as e:
        sys.exit(f"API error {e.status} {e.code}: {e.message}")
    except OSError as e:
        sys.exit(f"Network error: {e}")
    print(season["name"])
    print_table(rows)
Terminal
python table.py
Output (first rows)
Premier League 26/27
 #  Team              P  W  D  L  GF  GA   GD  Pts  Form
 1  Arsenal          10  9  0  1  15   5  +10   27  WWWWW
 2  Brighton         10  7  1  2  26   7  +19   22  WWLWW
 3  Man City         10  7  0  3  21  13   +8   21  WWLLL
 4  Liverpool        10  5  3  2  14  10   +4   18  LWWLW
 5  Chelsea          10  5  1  4  19  16   +3   16  WWLWL
 6  Everton          10  4  4  2  12  10   +2   16  DLLWW
…

shortName keeps the team column narrow ("Man City" rather than "Manchester City"); switch to name if you have the room. The + in the format spec gives goal difference its sign, as printed tables usually show it.

6. Load it into pandas (optional)

For anything beyond printing, a DataFrame is the natural home for a table. Install pandas with pip install pandas and build one row per team, with the column names you want rather than the nested JSON:

frame.py
import pandas as pd

from table import LEAGUE_ID, current_season, form_text, standings

POINTS = {"win": 3, "draw": 1, "loss": 0}

season = current_season(LEAGUE_ID)
rows = standings(LEAGUE_ID, season["id"])

df = pd.DataFrame(
    [
        {
            "pos": r["position"],
            "team": r["team"]["name"],
            "code": r["team"]["code"],
            "p": r["played"],
            "w": r["wins"],
            "d": r["draws"],
            "l": r["losses"],
            "gf": r["scoresFor"],
            "ga": r["scoresAgainst"],
            "gd": r["scoreDifference"],
            "pts": r["points"],
            "zone": r["zone"],
            "form": form_text(r),
            "form_pts": sum(POINTS.get(x, 0) for x in r["form"] or []),
        }
        for r in rows
    ]
).set_index("pos")

df["ppg"] = (df["pts"] / df["p"]).round(2)

print(df[["team", "pts", "gd", "ppg"]].head())
print(df.sort_values("form_pts", ascending=False)[["team", "form", "form_pts"]].head(5))
df.to_csv("premier-league-table.csv")
Output
                       team  pts  gd  ppg
pos                                      
1                   Arsenal   27  10  2.7
2    Brighton & Hove Albion   22  19  2.2
3           Manchester City   21   8  2.1
4              Liverpool FC   18   4  1.8
5                   Chelsea   16   3  1.6
                       team   form  form_pts
pos                                         
1                   Arsenal  WWWWW        15
7               Bournemouth  LWWWW        12
2    Brighton & Hove Albion  WWLWW        12
11        Tottenham Hotspur  DWWWL        10
5                   Chelsea  WWLWL         9

form_pts scores the last five results the usual way, three for a win and one for a draw, and makes "who is in form" a simple sort. The CSV opens in any spreadsheet.

7. Zones and form

zone is the label the competition itself gives a position: in the Premier League table above it reads Champions League, Europa League or Relegation, and it is null for mid-table. The labels differ from league to league, so treat them as text to display, not as a fixed list to match against. Grouping the teams by zone takes a few lines:

zones.py
from table import LEAGUE_ID, current_season, standings
season = current_season(LEAGUE_ID)
rows = standings(LEAGUE_ID, season["id"])
zones = {}
for r in rows:
    if r["zone"]:
        zones.setdefault(r["zone"], []).append(r["team"]["shortName"])
for zone, teams in zones.items():
    print(f"{zone}: {', '.join(teams)}")
Output
Champions League: Arsenal, Brighton, Man City, Liverpool
Europa League: Chelsea
Relegation: Man Utd, Sunderland, Crystal Palace

form holds up to five of the team's most recent results in this competition, oldest first, so the last letter is the latest match. It can be null where the source keeps no form guide. Add type=home or type=away to the standings call to get the home-only or away-only table; form then follows that table too.

8. Cache the answer

A table only moves when matches finish, and according to the standings reference it is rebuilt once a day. Asking every minute gains nothing and spends quota. A file cache with a one-hour lifetime keeps a bot, a dashboard or a cron job cheap: at most two requests an hour, 48 a day, whatever the number of runs.

cache.py
import json
import time
from pathlib import Path

from table import call, print_table

CACHE_DIR = Path(".cache")
MAX_AGE = 3600  # seconds


def cached(name, fetch):
    """Return the JSON stored under name if it is fresh enough, else fetch and store it."""
    path = CACHE_DIR / f"{name}.json"
    if path.exists() and time.time() - path.stat().st_mtime < MAX_AGE:
        return json.loads(path.read_text())
    data = fetch()
    CACHE_DIR.mkdir(exist_ok=True)
    path.write_text(json.dumps(data))
    return data


def table(league_id):
    season = cached(f"season-{league_id}", lambda: call(f"/v2/leagues/{league_id}/seasons")["data"][0])
    rows = cached(
        f"standings-{league_id}-{season['id']}",
        lambda: call(f"/v2/leagues/{league_id}/standings", season=season["id"])["data"],
    )
    return season, rows


if __name__ == "__main__":
    season, rows = table(195828)
    print(season["name"])
    print_table(rows)

The cache keys on the season id as well as the league, so the August switch to a new season starts a fresh file. In a web app, the same idea fits in your framework's cache or in Redis; the lifetime is the part that matters.

9. Other leagues

Nothing in the code is specific to England. Change LEAGUE_ID and the same three calls give you any other table:

LeagueidNote
LaLiga4408
Serie A195910
Bundesliga195937
Ligue 1195793
Süper Lig172801
MLS6540Conferences: add group=all for every table
UEFA Champions League4409The league phase is one table

When a season has several tables (conferences, divisions, groups), the endpoint returns the primary one unless you pass group=all, which returns them all as a list of groups. Check meta.overall: it is true only when the table holds every team in the season.

Where to go next

More guides

Try it with your own key.

1,000 free requests a day during the beta. No card, no sales call.