How to Build a Premier League Website with Python
You are going to build a Premier League website in Python with the SportAPI football API. One script requests the data and writes plain HTML pages: the league table, the fixtures for the next two weeks, a page for each of the 20 clubs, the top scorers and a page for each leading scorer.
The finished site is a folder of HTML files. It needs no database and no Python on the web server, so you can host it almost anywhere. A scheduled job runs the script every 15 minutes, and the pages stay up to date.
The full version of this idea is live at premier-league.sportapi.ai. It is built the same way, in Python, with about 750 pages.

What you need
You need Python 3.11 or newer, the requests package and a free SportAPI key. Sign up, confirm your e-mail address and copy the key from your dashboard.
pip install requestsThe complete example has three files: sportapi.py, build.py and style.css. The script reads your key from the SPORTAPI_KEY environment variable, so the key never ends up in your code.
export SPORTAPI_KEY="YOUR_API_KEY" # on Windows: set SPORTAPI_KEY=YOUR_API_KEY
python build.pyThe pages appear in the site folder. Open site/index.html to see them, or start a small local server with python -m http.server --directory site and open http://localhost:8000.
Find the Premier League ID in the API
Call /api/leagues and send your key in the X-API-Key header. The answer groups the leagues by country.
curl -H "X-API-Key: YOUR_API_KEY" https://sportapi.ai/api/leagues{
"success": true,
"data": [
{
"country": "England",
"geo": "GB-ENG",
"leagues": [
{ "id": 24, "name": "Premier League", "format": "league", "has_standings": true, "teams_count": 20 },
{ "id": 53, "name": "Championship", "format": "league", "has_standings": true, "teams_count": 24 },
{ "id": 58, "name": "FA Cup", "format": "cup", "has_standings": false, "teams_count": 741 }
]
}
]
}The Premier League has the ID 24. Every request below uses it.
Write one helper with a cache
All requests go through one function. It sends the key and saves each answer to a file in the cache folder. The next call within ttl seconds reads the file instead of the API.
"""sportapi.py: one helper that calls SportAPI and keeps each answer in a cache file."""
import hashlib
import json
import os
import time
from pathlib import Path
import requests
API_KEY = os.environ.get("SPORTAPI_KEY", "YOUR_API_KEY")
BASE = "https://sportapi.ai/api"
CACHE = Path(__file__).parent / "cache"
session = requests.Session()
session.headers["X-API-Key"] = API_KEY
def get(path, ttl=900):
"""Returns the API answer for path, from the cache if it is younger than ttl seconds."""
CACHE.mkdir(exist_ok=True)
file = CACHE / (hashlib.md5(path.encode()).hexdigest() + ".json")
if file.exists() and time.time() - file.stat().st_mtime < ttl:
return json.loads(file.read_text(encoding="utf-8"))
try:
response = session.get(BASE + path, timeout=20)
response.raise_for_status()
data = response.json()
except (requests.RequestException, ValueError):
# Daily limit reached or a network problem: use the last saved copy if there is one
return json.loads(file.read_text(encoding="utf-8")) if file.exists() else None
file.write_text(json.dumps(data), encoding="utf-8")
return data
def download(path, folder, name):
"""Saves a file such as a club logo once and returns its file name, or None."""
for ext in ("png", "svg", "jpg", "webp"):
if (folder / f"{name}.{ext}").exists():
return f"{name}.{ext}"
try:
response = session.get(BASE + path, timeout=20)
response.raise_for_status()
except requests.RequestException:
return None
types = {"image/png": "png", "image/svg+xml": "svg", "image/jpeg": "jpg", "image/webp": "webp"}
ext = types.get(response.headers.get("Content-Type", "").split(";")[0])
if not ext:
return None
folder.mkdir(parents=True, exist_ok=True)
(folder / f"{name}.{ext}").write_bytes(response.content)
return f"{name}.{ext}"The cache matters. A full build of this site makes about 75 requests the first time, logos included. The next run 15 minutes later makes only 2, for the table and today's matches, because everything else is still fresh in the cache. If the API can't be reached or you hit your limit, get() returns the last saved copy, so the site never breaks.
The download() helper saves each club logo once. The logos are served from your own site, so visitors never see your key.
Keep your API key on the server. Never call the API from JavaScript in the browser: the API does not allow calls from other sites, and every visitor would be able to see your key.
Build the league table page
build.py starts with two small functions. page() puts the same header, menu and footer around every page. write() saves a page only when its content has changed, so pages that stay the same keep their date.
"""build.py: builds a static Premier League site in the site/ folder from SportAPI data."""
from datetime import date, datetime, timedelta
from html import escape
from pathlib import Path
from zoneinfo import ZoneInfo
from sportapi import download, get
LEAGUE = 24 # Premier League
UK = ZoneInfo("Europe/London")
CET = ZoneInfo("Europe/Paris") # the "datetime" field of the API is Central European time
HERE = Path(__file__).parent
OUT = HERE / "site"
MINUTE, HOUR = 60, 3600
pages = [] # every page URL, for the sitemap
def page(title, body):
"""The same header, menu and footer on every page."""
return f"""<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{escape(title)}</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header><a class="brand" href="/">Premier League</a>
<nav><a href="/">Table</a><a href="/fixtures.html">Fixtures</a><a href="/top-scorers.html">Top scorers</a></nav>
</header>
<main>
{body}
</main>
<footer>Data from <a href="https://sportapi.ai/">SportAPI</a></footer>
</body>
</html>
"""
def write(name, html):
"""Writes a page only if it changed, so files that stay the same keep their date."""
pages.append("/" + name.removesuffix("index.html"))
file = OUT / name
file.parent.mkdir(parents=True, exist_ok=True)
if file.exists() and file.read_text(encoding="utf-8") == html:
return
file.write_text(html, encoding="utf-8")
print("wrote", name)The table comes from /api/standings/24. Each item in data is one row:
{
"success": true,
"season": "2026/27",
"data": [
{
"position": 1,
"team": { "id": 311, "name": "Arsenal", "slug": "arsenal" },
"played": 9,
"won": 8,
"draw": 0,
"lost": 1,
"goals_for": 14,
"goals_against": 5,
"goal_difference": 9,
"points": 24
}
]
}The code loops through the rows and builds an HTML table. escape() from Python's html module keeps names like Brighton & Hove Albion from breaking the page.
# --- table
standings = get(f"/standings/{LEAGUE}", ttl=10 * MINUTE)
if not standings:
raise SystemExit("No data from the API: check your key")
season = standings["season"]
logos = {}
for row in standings["data"]:
team = row["team"]
logos[team["id"]] = download(f"/teams/{team['id']}/logo", OUT / "logos", team["id"])
def crest(team_id):
file = logos.get(team_id)
return f'<img src="/logos/{file}" alt="" width="24" height="24">' if file else ""
rows = ""
for row in standings["data"]:
team = row["team"]
gd = row["goal_difference"]
gd = f"{gd:+d}" if gd else "0" # +3, -2 or 0
rows += (
f"<tr><td>{row['position']}</td>"
f'<td class="club">{crest(team["id"])}<a href="/clubs/{team["slug"]}.html">{escape(team["name"])}</a></td>'
f"<td>{row['played']}</td><td>{row['won']}</td><td>{row['draw']}</td><td>{row['lost']}</td>"
f"<td>{gd}</td><td><b>{row['points']}</b></td></tr>\n"
)
write("index.html", page(f"Premier League Table {season}", f"""<h1>Premier League table {season}</h1>
<table>
<tr><th>#</th><th>Club</th><th>P</th><th>W</th><th>D</th><th>L</th><th>GD</th><th>Pts</th></tr>
{rows}</table>"""))List the fixtures in UK time
Fixtures come from /api/fixtures/date/{date}, one day per request. The answer has every league that plays that day, so the code keeps the matches where league_id is 24.
{
"id": 16096706,
"date": "2026-11-07",
"datetime": "2026-11-07 13:30:00",
"kickoff_utc": "2026-11-07T12:30:00Z",
"status": "Scheduled",
"league_id": 24,
"home_id": 352,
"home_team": "Leeds United",
"away_id": 313,
"away_team": "Tottenham Hotspur",
"home_score": null,
"away_score": null
}Use kickoff_utc for the time. The datetime field is Central European time, an hour ahead of the UK. Python's zoneinfo turns the UTC time into UK time and handles the switch to summer time for you.
# --- fixtures
def kickoff(match):
"""Kick-off in UK time from the kickoff_utc field."""
return datetime.fromisoformat(match["kickoff_utc"]).astimezone(UK)
today = date.today()
matches = []
for i in range(14):
day = today + timedelta(days=i)
# Today's answer changes with live scores; later days rarely change
answer = get(f"/fixtures/date/{day}", ttl=10 * MINUTE if i == 0 else 6 * HOUR)
matches += [m for m in (answer or {}).get("data", []) if m["league_id"] == LEAGUE]
body, last_day = "<h1>Premier League fixtures</h1>\n<p>Kick-off times are UK time.</p>\n", None
for m in sorted(matches, key=kickoff):
k = kickoff(m)
if k.date() != last_day:
body += f"<h2>{k:%A} {k.day} {k:%B}</h2>\n"
last_day = k.date()
if m["status"] == "Scheduled":
middle = f"{k:%H:%M}"
elif m["home_score"] is None:
middle = escape(m["status"]) # postponed or cancelled
else:
middle = f"{m['home_score']}–{m['away_score']}"
body += (f'<p class="match"><span>{escape(m["home_team"])}{crest(m["home_id"])}</span>'
f"<b>{middle}</b><span>{crest(m['away_id'])}{escape(m['away_team'])}</span></p>\n")
write("fixtures.html", page("Premier League Fixtures", body))Today's answer is cached for 10 minutes, because scores change during the matches. The later days change rarely, so they are cached for 6 hours. That one decision saves about 1,200 requests a day.

Make a page for each club
/api/teams/slug/{slug} returns everything for a club page in one answer: the club details, the squad, the next matches and the latest results in all competitions. The slug of each club is already in the table answer.
{
"success": true,
"team": {
"id": 369,
"name": "Everton",
"city": "Liverpool",
"founded_year": 1878,
"coach_name": "David Moyes",
"stadium_name": "Hill Dickinson Stadium"
},
"squad": [
{ "full_name": "Jordan Pickford", "position": "Goalkeeper", "jersey_number": 1, "nationality": "GB-ENG", "slug": "jordan-pickford" }
],
"upcoming": [
{ "id": 16053396, "date": "2026-11-06", "datetime": "2026-11-06 21:00:00", "home_team": "Everton", "away_team": "Coventry City", "league_name": "Premier League" }
],
"results": []
}# --- clubs
squads = {}
for row in standings["data"]:
team = row["team"]
club = get(f"/teams/slug/{team['slug']}", ttl=6 * HOUR)
if not club:
continue
squads[team["id"]] = club["squad"]
info = club["team"]
body = f"<h1>{crest(team['id'])}{escape(info['name'])}</h1>\n"
body += f"<p>Manager: {escape(info.get('coach_name') or '-')}. Stadium: {escape(info.get('stadium_name') or '-')}.</p>\n"
n = row["position"]
suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
body += f"<p>{n}{suffix} place, {row['points']} points.</p>\n<h2>Next matches</h2>\n<ul>\n"
for m in club["upcoming"][:5]:
k = datetime.fromisoformat(m["datetime"]).replace(tzinfo=CET).astimezone(UK)
body += f"<li>{k.day} {k:%b %H:%M}: {escape(m['home_team'])} v {escape(m['away_team'])} ({escape(m['league_name'])})</li>\n"
body += "</ul>\n<h2>Squad</h2>\n<table>\n<tr><th>No.</th><th>Player</th><th>Position</th></tr>\n"
for p in sorted(club["squad"], key=lambda p: p.get("jersey_number") or 99):
body += f"<tr><td>{p.get('jersey_number') or ''}</td><td>{escape(p['full_name'])}</td><td>{p['position']}</td></tr>\n"
body += "</table>"
write(f"clubs/{team['slug']}.html", page(f"{info['name']}: Squad and Fixtures", body))The upcoming list has datetime but no kickoff_utc, so this code reads the time as Central European time and converts it. The squads are also kept in a dictionary, because the next step needs them.

Link the top scorers to player pages
/api/leagues/24/topscorers returns the top 20 scorers of the season:
{
"success": true,
"season_from": "2026-08-21",
"data": [
{ "rank": 1, "player_name": "E. Haaland", "team_id": 324, "team_name": "Manchester City", "goals": 9, "penalties": 0 },
{ "rank": 2, "player_name": "A. Isak", "team_id": 312, "team_name": "Liverpool", "goals": 6, "penalties": 0 }
]
}The list writes names with an initial, like E. Haaland, and has no player ID. To link a scorer to a player page, find the player in the club squad by the initial and the surname. The function returns a player only when exactly one name fits, so it never links to the wrong person.
# --- scorers
def find_player(name, team_id):
"""The top scorers list writes "E. Haaland": find him in the club squad by initial and surname."""
initial, _, surname = name.rpartition(". ")
hits = [p for p in squads.get(team_id, [])
if (p["full_name"].endswith(" " + surname) or p["full_name"] == surname)
and p["full_name"].startswith(initial)]
return hits[0] if len(hits) == 1 else None
top = get(f"/leagues/{LEAGUE}/topscorers", ttl=HOUR)
scorers = top["data"]
rows = ""
for s in scorers:
player = find_player(s["player_name"], s["team_id"])
name = escape(s["player_name"])
if player:
name = f'<a href="/players/{player["slug"]}.html">{name}</a>'
rows += f"<tr><td>{s['rank']}</td><td>{name}</td><td>{crest(s['team_id'])}{escape(s['team_name'])}</td><td><b>{s['goals']}</b></td></tr>\n"
write("top-scorers.html", page("Premier League Top Scorers", f"""<h1>Premier League top scorers</h1>
<table>
<tr><th>#</th><th>Player</th><th>Club</th><th>Goals</th></tr>
{rows}</table>"""))
Each player in a squad has a slug, and /api/players/{slug} returns the profile with every match the player played, in all competitions:
{
"success": true,
"player": { "id": 5070, "full_name": "Erling Haaland", "slug": "erling-haaland", "position": "Forward", "nationality": "NO", "jersey_number": 9 },
"team": { "id": 324, "full_name": "Manchester City", "slug": "manchester-city" },
"matches": [
{
"date": "2026-10-31",
"home_team": "Manchester City",
"away_team": "Brighton & Hove Albion",
"home_score": 0,
"away_score": 1,
"league_name": "Premier League",
"mins_played": 90,
"goals": 0,
"assists": 0
}
]
}The code keeps the Premier League matches since the start of the season and adds up the goals, assists and minutes. A player who sat on the bench is in the list with 0 minutes, so those games are left out. The minutes are sometimes missing for a player who did play, so a game with a goal or an assist counts too.
# --- players
for s in scorers:
player = find_player(s["player_name"], s["team_id"])
profile = player and get(f"/players/{player['slug']}", ttl=24 * HOUR)
if not profile:
continue
# League games this season. Minutes are sometimes 0 for a player who scored, so a goal counts too.
games = [m for m in profile["matches"] if m["league_name"] == "Premier League"
and m["date"] >= top["season_from"] and (m["mins_played"] or m["goals"] or m["assists"])]
goals = sum(m["goals"] for m in games)
assists = sum(m["assists"] for m in games)
minutes = sum(m["mins_played"] or 0 for m in games)
p = profile["player"]
body = f"<h1>{escape(p['full_name'])}</h1>\n<p>{escape(profile['team']['full_name'])}, {p['position']}</p>\n"
body += (f'<p class="stats"><span><b>{len(games)}</b> games</span><span><b>{goals}</b> goals</span>'
f'<span><b>{assists}</b> assists</span><span><b>{minutes}</b> minutes</span></p>\n')
body += "<h2>Last league games</h2>\n<ul>\n"
for m in games[:5]:
scored = f", {m['goals']} goal{'s' if m['goals'] > 1 else ''}" if m["goals"] else ""
body += (f"<li>{m['date']}: {escape(m['home_team'])} {m['home_score']}–{m['away_score']} "
f"{escape(m['away_team'])}, {m['mins_played']} min{scored}</li>\n")
body += "</ul>"
write(f"players/{player['slug']}.html", page(f"{p['full_name']}: Premier League Stats", body))
Add a sitemap and run the script every 15 minutes
The last part of the script copies the stylesheet and writes sitemap.xml with every page, so search engines find the club and player pages. Change SITE to your domain.
# --- sitemap
(OUT / "style.css").write_text((HERE / "style.css").read_text(encoding="utf-8"), encoding="utf-8")
SITE = "https://www.example.com" # your domain
urls = "".join(f"<url><loc>{SITE}{u}</loc></url>" for u in pages)
(OUT / "sitemap.xml").write_text(
'<?xml version="1.0" encoding="UTF-8"?>'
f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{urls}</urlset>',
encoding="utf-8")On Linux or macOS, add one line to your crontab with crontab -e. On Windows, use Task Scheduler to run the same command.
*/15 * * * * cd /home/you/premier-league && SPORTAPI_KEY=YOUR_API_KEY python3 build.py >> build.log 2>&1With these cache times the site uses about 370 requests a day: the table and today's matches 96 times each, the later days and the clubs four times a day, the scorers every hour and the players once a day. That is around 11,000 requests a month. The Free plan allows 1,000 a day and 7,000 a month, so double the cache times (about 5,600 a month) or use a paid plan, which has no monthly cap.
Put the site online
The site folder is a plain static website. If the script runs on your web server, point the server at that folder and you are done. If it runs on another computer, copy the folder to your host after each run, for example with rsync.
rsync -a site/ you@your-host:/var/www/premier-league/The pages link to each other with addresses like /clubs/arsenal.html, which work on any host. For addresses without .html, the full site uses this nginx rule:
location / {
try_files $uri $uri.html $uri/index.html =404;
}See what the full site adds
premier-league.sportapi.ai is built the same way, with a script that saves the API answers and a script that writes the pages, and it adds more pages and details. Every part of it comes from the same API.

- A page for every match of the season, with goals, cards, stats and line-ups from
/api/fixtures/{id}/events,/api/fixtures/{id}/statsand/api/fixtures/{id}/lineups. - A page for every squad player, about 580 in all, with this season's numbers for club and country.
- Top assists and cards from
/api/leagues/24/topassistsand/api/leagues/24/topcards. - Live scores: a small
live.jsonfile is written on every run, and a few lines of JavaScript update open pages once a minute. - Club trophies from
/api/teams/{id}/trophies. - Match predictions from FootyMath, which are not part of the SportAPI data.
The club pages show the top five scorers of each club. The full top scorers list has only 20 players, and a club like Everton may have none of them, so the site adds up each player's league goals from the match lists, like the player pages above.

The fixtures page has a club filter. All matches are on the page, and a few lines of JavaScript hide the other clubs' matches, so the filter needs no extra pages or requests.

The player pages add the season numbers from the season part of the profile. Those numbers count every game, club and national team, so the page labels them that way and shows the Premier League numbers separately.

Where to go next
- The API documentation lists every endpoint and field.
- To show a league table or top scorers on a site without code, use the free widgets. The Serie A guide shows how, with PHP examples.
- To build the same site for another league, change
LEAGUEto its ID from/api/leagues. The Championship is 53, and other leagues work the same way.