Skip to content

Livematches in play

Demo: Matchboard, opens in a new tab

Tutorial

Build a football fixtures calendar as an ICS feed

This tutorial turns a league's upcoming matches into a football fixtures calendar: an ICS file that Google Calendar, Apple Calendar or Outlook can subscribe to. A Python script of about 130 lines writes it to the iCalendar standard, with kick-off times in UTC and the stadium as the location, and a daily cron job keeps it current on a free key.

  • Free plan key
  • 25 min
  • Python
  • iCalendar
  • cron
  • Updated

What you will build

A file, premier-league.ics, that holds one event per match for the next four weeks: "Manchester City vs Fulham" at 12:30 UTC, at the Etihad Stadium, Manchester. You host it at any HTTPS address and subscribe to it once. Each morning a cron job rewrites the file, and the calendar apps pick up moved kick-offs on their next refresh without anyone importing anything again.

1. Install the client and set your key

Terminal
pip install datasportsapi
export DATASPORTSAPI_API_KEY="sk_live_…"

The datasportsapi package is a small client with no dependencies: client.get(path, **params) sends your key as a Bearer token, returns the { data, meta } envelope as a dict and raises DataSportsAPIError (with .status, .code and .retry_after) on any error. It reads the key from the environment, and it needs Python 3.10 or later. Get the key from your dashboard after you sign up.

2. Find the days with matches

Rather than ask for every date in the next four weeks, ask the league which dates have matches. GET /v2/leagues/{id}/calendar takes a season id and lists the UTC days that carry fixtures, oldest first. The season comes from GET /v2/leagues/{id}/seasons, whose first entry is the most recent (for the Premier League, league 195828, that is 26/27, season 200386):

GET /v2/leagues/195828/calendar?season=200386 (trimmed)
{
  "data": [
    { "date": "2026-11-21", "fixtureCount": 7 },
    { "date": "2026-11-22", "fixtureCount": 2 },
    { "date": "2026-11-23", "fixtureCount": 1 },
    { "date": "2026-11-27", "fixtureCount": 1 },
    …
  ],
  "meta": { "season": 200386, "count": 77, "fixtureCount": 380 }
}

The script keeps the days from today to four weeks ahead. In a normal stretch of the season that is ten to fourteen days, so ten to fourteen more calls.

3. Fetch each day's fixtures

For each of those days, GET /v2/fixtures?date=2026-11-22&league=195828 returns that league's matches on that UTC date, on one page. Each fixture includes its venue, which becomes the event's location. One fixture, trimmed to the fields the script reads:

Response (trimmed)
{
  "data": [
    {
      "id": 211525,
      "status": { "type": "notstarted", "description": "Not started" },
      "startTime": "2026-11-22T14:00:00.000Z",
      "round": { "number": 11 },
      "league": { "id": 195828, "name": "Premier League" },
      "home": { "name": "Hull City" },
      "away": { "name": "Brighton & Hove Albion" },
      "venue": { "id": 703125, "name": "MKM Stadium", "city": "Hull", "capacity": 25586 }
    },
    …
  ],
  "meta": { "date": "2026-11-22", "league": 195828, "page": 0, "count": 2, "hasNextPage": false }
}

startTime is always UTC, which is exactly what an ICS file wants. venue can be null when the source has not published one yet, so the script adds a location only when there is one.

4. The iCalendar rules that matter

The format is RFC 5545. Calendar apps forgive some mistakes and silently drop events over others. The rules the script follows:

  • CRLF line endings. Every line ends in \r\n, not a bare newline. The file is opened with newline="" so Python never rewrites them.
  • Lines of at most 75 octets. Longer lines are folded: broken with CRLF and continued on a line that starts with a single space. Octets, not characters: "Sarandë" or "Beşiktaş" take more bytes than letters, and a fold must not cut a character in half.
  • Escaped text. In values such as SUMMARY and LOCATION, a backslash, semicolon or comma gets a backslash in front, and a newline becomes \n. A venue like "Etihad Stadium, Manchester" is written Etihad Stadium\, Manchester.
  • Times in UTC. DTSTART:20261122T140000Z: the trailing Z means UTC, so every app shows the kick-off in its user's own time zone and no VTIMEZONE block is needed.
  • A stable `UID` per event. Built from the fixture id, it lets an app recognise a match it already has and move it when the kick-off changes, instead of adding a copy.
  • `DTSTAMP` on every event, the time the file was written. It is required.
  • A `DTEND`. The API gives a start, not an end, so the script estimates 115 minutes: 90 of play, the half-time break and some stoppage time.

5. The script

Save this as fixtures_ics.py. Change LEAGUE_ID and CALENDAR_NAME for another competition, and set UID_DOMAIN to a domain you control so the event ids are unique to you:

fixtures_ics.py
import os
import sys
import time
from datetime import datetime, timedelta, timezone

from datasportsapi import DataSportsAPI, DataSportsAPIError

LEAGUE_ID = 195828          # Premier League
CALENDAR_NAME = "Premier League fixtures"
DAYS_AHEAD = 28             # how far ahead the feed reaches
MATCH_LENGTH = timedelta(minutes=115)  # 90 minutes, half-time and stoppage time
UID_DOMAIN = "fixtures.example.org"    # any domain you control
OUT = "premier-league.ics"

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:
            if e.status == 429 and e.code == "rate_limited" and attempt < 3:
                time.sleep((e.retry_after or 60) + 1)
                continue
            raise  # quota_exceeded and every other error: stop here
        except OSError:
            if attempt < 3:
                time.sleep(5 * 2**attempt)
                continue
            raise


def upcoming_fixtures(league_id):
    season = call(f"/v2/leagues/{league_id}/seasons")["data"][0]
    days = call(f"/v2/leagues/{league_id}/calendar", season=season["id"])["data"]
    today = datetime.now(timezone.utc).date()
    last = today + timedelta(days=DAYS_AHEAD)
    wanted = [d["date"] for d in days if today.isoformat() <= d["date"] <= last.isoformat()]
    fixtures = []
    for i, day in enumerate(wanted):
        if i:
            time.sleep(7)  # at most ~9 calls a minute: under the Free plan's 10
        fixtures += call("/v2/fixtures", date=day, league=league_id)["data"]
    return fixtures


def text(value):
    """Escape a TEXT value (RFC 5545, 3.3.11)."""
    return (value.replace("\\", "\\\\").replace(";", "\\;")
                 .replace(",", "\\,").replace("\n", "\\n"))


def fold(line):
    """Fold a content line at 75 octets (RFC 5545, 3.1) without splitting a UTF-8 character."""
    parts, current, size = [], "", 0
    for ch in line:
        n = len(ch.encode("utf-8"))
        if size + n > 75:
            parts.append(current)
            current, size = " ", 1  # a continuation line starts with one space
        current += ch
        size += n
    parts.append(current)
    return "\r\n".join(parts)


def stamp(dt):
    return dt.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")


def event(f, now):
    start = datetime.fromisoformat(f["startTime"].replace("Z", "+00:00"))
    lines = [
        "BEGIN:VEVENT",
        f"UID:fixture-{f['id']}@{UID_DOMAIN}",
        f"DTSTAMP:{stamp(now)}",
        f"DTSTART:{stamp(start)}",
        f"DTEND:{stamp(start + MATCH_LENGTH)}",
    ]
    summary = f"{f['home']['name']} vs {f['away']['name']}"
    if f["status"]["type"] == "postponed":
        summary = "Postponed: " + summary
    lines.append(f"SUMMARY:{text(summary)}")
    venue = f.get("venue")
    if venue and venue.get("name"):
        place = venue["name"] + (", " + venue["city"] if venue.get("city") else "")
        lines.append(f"LOCATION:{text(place)}")
    detail = f["league"]["name"]
    if f.get("round") and f["round"].get("number"):
        detail += f", round {f['round']['number']}"
    lines.append(f"DESCRIPTION:{text(detail)}")
    if f["status"]["type"] == "canceled":
        lines.append("STATUS:CANCELLED")  # marks the event as called off
    lines.append("END:VEVENT")
    return lines


def calendar(fixtures):
    now = datetime.now(timezone.utc)
    lines = [
        "BEGIN:VCALENDAR",
        "VERSION:2.0",
        "PRODID:-//Example//Football fixtures//EN",
        "CALSCALE:GREGORIAN",
        "METHOD:PUBLISH",
        f"X-WR-CALNAME:{text(CALENDAR_NAME)}",
        "REFRESH-INTERVAL;VALUE=DURATION:PT12H",
        "X-PUBLISHED-TTL:PT12H",
    ]
    for f in fixtures:
        lines += event(f, now)
    lines.append("END:VCALENDAR")
    return "".join(fold(line) + "\r\n" for line in lines)


if __name__ == "__main__":
    try:
        fixtures = upcoming_fixtures(LEAGUE_ID)
    except DataSportsAPIError as e:
        sys.exit(f"API error {e.status} {e.code}: {e.message}")  # the old file stays in place
    except OSError as e:
        sys.exit(f"Network error: {e}")
    tmp = OUT + ".tmp"
    with open(tmp, "w", encoding="utf-8", newline="") as fh:
        fh.write(calendar(fixtures))
    os.replace(tmp, OUT)  # swap in one step: a reader never sees half a file
    print(f"{OUT}: {len(fixtures)} fixtures")

Three details are worth a second look. The 7-second pause between day requests keeps the run under the free plan's 10 calls a minute, so a full refresh takes a minute or two. call() waits out a 429 rate_limited using the Retry-After the API sends, retries network errors with a growing pause, and gives up on 429 quota_exceeded, which only clears at midnight UTC. And the file is written to a temporary name and swapped in with os.replace, so if anything fails the old calendar stays online untouched.

Terminal
python fixtures_ics.py
premier-league.ics (start)
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Football fixtures//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Premier League fixtures
REFRESH-INTERVAL;VALUE=DURATION:PT12H
X-PUBLISHED-TTL:PT12H
BEGIN:VEVENT
UID:fixture-211675@fixtures.example.org
DTSTAMP:20261118T122832Z
DTSTART:20261121T123000Z
DTEND:20261121T142500Z
SUMMARY:Manchester City vs Fulham
LOCATION:Etihad Stadium\, Manchester
DESCRIPTION:Premier League\, round 11
END:VEVENT
…

Postponed matches stay in the feed with "Postponed:" in front of the title until a new date is set, and canceled ones carry STATUS:CANCELLED. X-WR-CALNAME names the calendar in Apple Calendar and Google, and REFRESH-INTERVAL (RFC 7986) suggests how often to check for changes; apps treat it as a hint, not an order.

6. Host it and subscribe

Calendar apps subscribe to a URL, so the file has to be reachable over HTTPS: a folder your web server already serves, object storage with public read, or GitHub Pages. Set OUT to that path. If your server does not know the extension, send it with Content-Type: text/calendar.

  • Google Calendar (on a computer): next to Other calendars, choose +, then From URL, and paste the address. Google's help page on subscribing to a calendar covers the details. Google fetches subscribed calendars on its own schedule, which can be many hours apart, and there is no button to force it.
  • Apple Calendar on a Mac: File, then New Calendar Subscription, then paste the address and choose how often to refresh. On an iPhone or iPad, add it as a subscribed calendar under the Calendar accounts in Settings, or open a webcal:// link to the file, which offers the subscription directly.

7. Refresh it every day with cron

Kick-off times move as broadcasters pick their matches, usually a few weeks ahead, so a daily run is enough. Keep the key in a file only you can read, not in the crontab itself:

crontab
# /srv/fixtures/.env  (chmod 600)
export DATASPORTSAPI_API_KEY="sk_live_…"

# crontab -e: every day at 05:30
30 5 * * * cd /srv/fixtures && . ./.env && python3 fixtures_ics.py >> fixtures.log 2>&1

Cron uses the server's own time zone; pick an hour when the league is not playing. One run costs two calls plus one per match day, about 15 requests. A file per league, five leagues, one run each: around 70 requests a day, still a small part of the free 1,000, as long as the jobs start a few minutes apart so their calls do not share the same minute.

Where to go next

  • One team instead of a league: keep only fixtures whose home.id or away.id is that team, and call the file after it.
  • Keep the results: the feed starts at today, so past matches drop out of subscribers' calendars. Fetch the last few days as well and put the score in DESCRIPTION; the Free plan reaches back 7 days, and paid plans much further (historical data).
  • Every competition in a country at once: /v2/fixtures also takes category or sport with country; the fixtures reference lists the options.
  • Other sports, same code: the football page lists the competitions we cover, and every sport's fixtures share this shape.

More guides

Try it with your own key.

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