How to Build La Liga Season Stats with Python
You are going to build season statistics for La Liga in Python: team averages, goals by minute, a league table that stops at minute 80, and derby pages. The SportAPI football API gives you the data of each match. Your script saves it once and adds it up.
The whole example is one Python file of about 220 lines. A fuller version of the same idea is live, in Spanish, at laliga.sportapi.ai.

What you need
You need Python 3.10 or newer, the requests package and a free SportAPI key. Sign up, confirm your e-mail address and copy the key from your dashboard.
Download the complete example, then install the package and run the script:
cd la-liga-season-stats-example
pip install -r requirements.txt
export SPORTAPI_KEY="YOUR_API_KEY" # on Windows: set SPORTAPI_KEY=YOUR_API_KEY
python season_stats.pyThe first run takes about half a minute and saves its data in the data folder. The result is output/index.html.
See what the API gives you for one match
Send your key in the X-API-Key header. /api/fixtures/{id}/stats returns the numbers of both teams:
curl -H "X-API-Key: YOUR_API_KEY" https://sportapi.ai/api/fixtures/16122904/stats{
"success": true,
"fixture_id": 16122904,
"available": true,
"data": {
"home": { "shots": 9, "shots_on_target": 4, "fouls": 14, "total_passes": 391, "pass_accuracy": 81.1, "tackles": 30, "saves": 3, "yellow_cards": 4 },
"away": { "shots": 19, "shots_on_target": 4, "fouls": 14, "total_passes": 675, "pass_accuracy": 91.1, "tackles": 15, "saves": 3, "yellow_cards": 1 }
}
}/api/fixtures/{id}/events returns goals, assists, cards and substitutions in one list, each with its minute:
{
"success": true,
"data": [
{ "event_type": "assist", "team_side": "home", "player_name": "J. Alvarez", "minute": "10'", "extra_info": null },
{ "event_type": "goal", "team_side": "home", "player_name": "G. Simeone", "minute": "10'", "extra_info": "Goal" }
]
}The API has no season totals for shots or passes, and no count of goals by minute. You make those yourself, and that's why this page looks different from a page that only prints an API answer.
Set up the script
The script reads your key from an environment variable, so the key stays out of your code. The get helper counts the requests, which helps later when you check your limit.
"""La Liga season statistics from the SportAPI football API.
Saves every finished match once, then builds output/index.html with team averages,
goals by minute, the table at minute 80 and the derbies. Run it once a day.
"""
import json
import os
import re
from datetime import date, timedelta
from html import escape
from pathlib import Path
import requests
LEAGUE = 1 # La Liga
SEASON_START = date(2026, 8, 14)
BASE = "https://sportapi.ai/api"
DATA = Path("data")
OUTPUT = Path("output")
FINISHED = {"FT", "AET", "PEN", "PENS"}
DERBIES = [
("El Clásico", "Real Madrid", "Barcelona"),
("Madrid derby", "Real Madrid", "Atletico Madrid"),
("Seville derby", "Sevilla", "Real Betis"),
("Basque derby", "Athletic Club", "Real Sociedad"),
]
session = requests.Session()
session.headers["X-API-Key"] = os.environ["SPORTAPI_KEY"]
calls = 0
def get(path):
global calls
calls += 1
response = session.get(BASE + path, timeout=25)
response.raise_for_status()
return response.json()
def load(path, default):
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default
def save(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False), encoding="utf-8")La Liga has the league id 1. /api/leagues lists the ids of all competitions.
Find the finished matches
/api/fixtures/date/{date} returns every match on one date, in all leagues, so the script keeps only those with the right league_id. It asks once for each date since the start of the season.
def update_calendar():
"""One request per date. A date counts as settled two days after it."""
file = DATA / "calendar.json"
calendar = load(file, {"matches": {}, "settled": []})
day = SEASON_START
while day <= date.today():
key = day.isoformat()
if key not in calendar["settled"]:
rows = get(f"/fixtures/date/{key}")["data"]
calendar["matches"] = {i: m for i, m in calendar["matches"].items() if m["date"] != key}
for m in rows:
if int(m.get("league_id") or 0) == LEAGUE:
calendar["matches"][str(m["id"])] = m
if day <= date.today() - timedelta(days=2):
calendar["settled"].append(key)
save(file, calendar)
day += timedelta(days=1)
return list(calendar["matches"].values())A date is settled two days after it, and a settled date is never requested again. That leaves room for late corrections, and a daily run costs only the last two dates.
Save each match once
A finished match doesn't change, so two requests are enough for its whole life. The script writes each match to its own file and skips the files it already has.
def update_details(matches):
"""Two requests per finished match, once. Incomplete answers aren't saved, so they are tried again."""
games = []
for m in matches:
if m["status"] not in FINISHED:
continue
file = DATA / "matches" / f"{m['id']}.json"
game = load(file, None)
if game is None:
stats = get(f"/fixtures/{m['id']}/stats").get("data")
events = get(f"/fixtures/{m['id']}/events").get("data") or []
goals = sum(1 for e in events if e["event_type"] == "goal")
if not stats or goals != m["home_score"] + m["away_score"]:
continue
game = {"match": m, "stats": stats, "events": events}
save(file, game)
games.append(game)
return gamesThe source sometimes adds statistics a little after the final whistle. So the script checks the answer before saving: statistics must be there, and the goals in the events must add up to the final score. If they don't, nothing is saved and the next run tries again. On 10 November 2026 all 119 finished matches passed this check.
Add up the team averages
Most columns are a sum divided by the number of games. Percentages need more care.
def team_averages(games):
teams = {}
for game in games:
m = game["match"]
for side in ("home", "away"):
s = game["stats"][side]
t = teams.setdefault(m[f"{side}_team"], {"games": 0, "shots": 0, "on_target": 0, "passes": 0, "completed": 0.0, "fouls": 0})
t["games"] += 1
t["shots"] += s["shots"]
t["on_target"] += s["shots_on_target"]
t["passes"] += s["total_passes"]
t["completed"] += s["total_passes"] * s["pass_accuracy"] / 100
t["fouls"] += s["fouls"]
rows = []
for name, t in teams.items():
rows.append({
"name": name,
"games": t["games"],
"shots": round(t["shots"] / t["games"], 1),
"on_target": round(100 * t["on_target"] / t["shots"], 1),
"passes": round(t["passes"] / t["games"]),
"accuracy": round(100 * t["completed"] / t["passes"], 1),
"fouls": round(t["fouls"] / t["games"], 1),
})
return sorted(rows, key=lambda r: -r["shots"])Don't average the pass_accuracy values. A team that completes 90% of 700 passes and 70% of 100 passes hasn't completed 80% of its passes. Turn each percentage back into completed passes, add those up, and divide by all passes.

Count goals by minute
The minute field is text such as "36'" or "45'+2". A regular expression takes the first number, so stoppage time at the end of the first half stays in the 31-45 band.
BANDS = [(1, 15), (16, 30), (31, 45), (46, 60), (61, 75), (76, 200)]
def goals_of(game):
"""(minute, side) of each goal. "45'+2" counts as 45. An own goal is listed under the side that gets it."""
return [(int(re.match(r"\d+", e["minute"]).group()), e["team_side"]) for e in game["events"] if e["event_type"] == "goal"]
def goals_by_band(games):
teams = {}
for game in games:
m = game["match"]
for name in (m["home_team"], m["away_team"]):
teams.setdefault(name, [0] * len(BANDS))
for minute, side in goals_of(game):
band = next(i for i, (low, high) in enumerate(BANDS) if low <= max(minute, 1) <= high)
teams[m[f"{side}_team"]][band] += 1
return sorted(teams.items(), key=lambda kv: -sum(kv[1]))An own goal is listed under the team that gets the goal, so team_side is always the side that the goal counts for. You don't need a special case for it.
On 10 November 2026 La Liga had 344 goals, and 88 of them came from minute 76 onwards, more than in any other band.

Rebuild the table at minute 80
Once you know the minute of every goal, you can replay any match up to any moment. This function works out the score at last_minute and gives the points for that score.
def table_at(games, last_minute):
table = {}
for game in games:
m = game["match"]
goals = goals_of(game)
home = sum(1 for minute, side in goals if minute <= last_minute and side == "home")
away = sum(1 for minute, side in goals if minute <= last_minute and side == "away")
for name, scored, conceded in ((m["home_team"], home, away), (m["away_team"], away, home)):
t = table.setdefault(name, {"name": name, "points": 0, "difference": 0, "scored": 0})
t["points"] += 3 if scored > conceded else 1 if scored == conceded else 0
t["difference"] += scored - conceded
t["scored"] += scored
return sorted(table.values(), key=lambda t: (-t["points"], -t["difference"], -t["scored"], t["name"]))Call table_at(games, 80) for the table at minute 80. Call it with a number above the last minute of any match, and you get the real points. That's a useful test, and it matched the official table when we ran it.
Real tie-breaks in La Liga start with the matches between the tied teams. This table uses goal difference, so call it an exercise with the data and not the official table.

Build a derby page
/api/fixtures/h2h/{team1}/{team2} returns the recent meetings of two teams in all competitions, plus a match that is already scheduled. One more request each brings the form from the standings and the top scorers.
def build_derbies(matches):
standings = get(f"/standings/{LEAGUE}")["data"]
form = {r["team"]["name"]: "".join(f["result"] for f in sorted(r["form"], key=lambda f: f["date"])[-5:]) for r in standings}
ids = {r["team"]["name"]: r["team"]["id"] for r in standings}
scorers = get(f"/leagues/{LEAGUE}/topscorers")["data"]
top = {}
for s in scorers:
top.setdefault(s["team_name"], f"{s['player_name']} ({s['goals']})")
derbies = []
for name, a, b in DERBIES:
meetings = get(f"/fixtures/h2h/{ids[a]}/{ids[b]}")["data"]
played = sorted((m for m in meetings if m["status"] in FINISHED), key=lambda m: m["date"], reverse=True)
coming = sorted((m for m in meetings if m["status"] == "Scheduled"), key=lambda m: m["date"])
derbies.append({"name": name, "a": a, "b": b, "played": played, "next": coming[0]["date"] if coming else None,
"form": (form[a], form[b]), "top": (top.get(a, "none in the top list"), top.get(b, "none in the top list"))})
return derbiesTwo limits shape this page. The head-to-head answer is short: on 10 November 2026 El Clásico had four meetings, going back to October 2025, so this works as a page about the current rivalry and not as its history. And the calendar reaches only about a month ahead, so the next date is often missing. Show a clear message for that instead of an empty box.
The script finds the team ids by name in the standings. If a club goes down, ids[a] stops working, so update DERBIES when the season changes.

Run it every day
The rest of the file turns these results into one HTML page. Run the script once a day with cron, and copy output/index.html to any web host. Visitors read a static file and never touch the API.
0 6 * * * cd /home/you/la-liga-season-stats-example && SPORTAPI_KEY=YOUR_API_KEY python3 season_stats.pyDon't put your real key in a shared crontab. On a server you share with other people, keep it in a file that only your user can read.
Stay within your request limit
The free plan includes 1,000 requests a day and 7,000 a month. These numbers come from running this script:
- The first run in November, with 119 finished matches: 333 requests.
- A day with no new matches: 8 requests.
- Each new finished match: 2 more requests.
A month of daily runs with about 40 new matches costs about 320 requests. If you start at the end of a season, with 380 matches and about 290 dates, the first run needs about 1,050 requests, a little over the daily limit. The API then answers with HTTP 429 and the script stops, but everything saved so far stays on disk. Run it again the next day and it continues where it stopped.
Where to go next
- Change
LEAGUE,SEASON_STARTandDERBIESto use another competition. - Replace the single page with a page for each team, as in the Premier League site guide.
- Add a list of matches with kick-off times by building on
kickoff_utc, which is always in UTC.
The full list of endpoints is in the API documentation, and the Football API page shows which leagues and data are covered.