Starter project

FastAPI soccer analytics backend starter

Summary

This starter is a FastAPI service that wraps StrikerAPI standings and Elo ratings behind your own endpoints. It adds an in-memory TTL cache, single-flight loading so concurrent requests share one upstream call, and a stale-on-error fallback. One extra route joins table rank with Elo rank. Run it with uvicorn and curl it.

What you'll build

A small backend that your own frontend, notebook or bot can call instead of calling the data API directly. The service has four routes.

  • GET /leagues/{league}/standings returns the league table as published, with points, goal difference, home and away records and form.
  • GET /leagues/{league}/ratings returns our Elo ratings, strongest club first.
  • GET /leagues/{league}/overview joins the two by club id and adds points per game and the gap between a club's table position and its rating rank.
  • GET /health reports cache hits, misses and stale serves.

Every data route sets an X-Cache header with HIT, MISS or STALE, so you can see the cache working from curl without reading logs.

The point of the wrapper is control. Your API key stays on the server. You decide which leagues and parameters are allowed. You cap how often upstream is called, and you can reshape the response once instead of in every client.

Prerequisites

  • Python 3.10 or newer. The code uses the int | None type syntax, which fails on Python 3.9. This page was tested on 3.12.
  • A StrikerAPI key in the environment variable STRIKER_API_KEY.
  • A terminal with curl. No database or Docker.

The tool costs matter for planning. On StrikerAPI, get_standings and get_ratings are 2 credits each, so a cold overview call costs 4 credits and every cached repeat costs nothing.

The project

soccer-backend/
  requirements.txt
  app/
    __init__.py          empty file
    cache.py             TTL cache with per-key locks and stale fallback
    main.py              routes, upstream client, overview join

Pin the three dependencies so a fresh install matches what was tested.

`requirements.txt`

fastapi==0.128.8
uvicorn==0.39.0
httpx==0.28.1

The cache is the interesting part. get_or_load checks for a fresh entry and returns it as a HIT. On a miss it takes a lock for that one key, checks again in case another request filled the entry while it waited, and only then calls the loader. This is single-flight loading. Ten simultaneous requests for the same table make one upstream call, and nine of them wait for it. If the loader raises and an expired copy exists, the cache returns the old copy as STALE instead of failing, which keeps the service answering through a short outage.

`app/cache.py`

import asyncio
import json
import time
from typing import Any, Awaitable, Callable


class TTLCache:
    """In-memory cache with per-key expiry and single-flight loading."""

    def __init__(self) -> None:
        self._data: dict[str, tuple[float, Any]] = {}
        self._locks: dict[str, asyncio.Lock] = {}
        self.hits = 0
        self.misses = 0
        self.stale = 0

    def key(self, tool: str, body: dict) -> str:
        return tool + ":" + json.dumps(body, sort_keys=True)

    async def get_or_load(
        self,
        key: str,
        ttl: float,
        loader: Callable[[], Awaitable[Any]],
    ) -> tuple[Any, str]:
        now = time.monotonic()
        entry = self._data.get(key)
        if entry and entry[0] > now:
            self.hits += 1
            return entry[1], "HIT"

        lock = self._locks.setdefault(key, asyncio.Lock())
        async with lock:
            # Another request may have filled the cache while we waited.
            entry = self._data.get(key)
            if entry and entry[0] > time.monotonic():
                self.hits += 1
                return entry[1], "HIT"
            try:
                value = await loader()
            except Exception:
                if entry:  # serve the expired copy rather than fail
                    self.stale += 1
                    return entry[1], "STALE"
                raise
            self._data[key] = (time.monotonic() + ttl, value)
            self.misses += 1
            return value, "MISS"

main.py builds one shared httpx.AsyncClient in the app lifespan, so connections are reused. The call helper turns a tool name and a request body into a cached upstream post, unwraps the data envelope that every response uses, and maps upstream failures to clean HTTP errors: a 429 becomes your own 429 so clients know to slow down, and any other bad status becomes a 502. TTLs differ by tool, because standings move after matches while Elo ratings move once a day.

The overview route calls the two cached tools, indexes ratings by team_id, and builds rows with points per game and rank_gap. A positive gap means the club sits lower in the table than its rating rank. Treat it as a descriptive number, not a forecast.

`app/main.py`

import os
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI, HTTPException, Query, Response

from .cache import TTLCache

BASE = os.environ.get("STRIKER_BASE_URL", "https://mcp.strikerapi.com/v1")
API_KEY = os.environ["STRIKER_API_KEY"]  # stays on the server, never sent to clients

LEAGUES = {"soccer", "mls", "laliga", "seriea", "bundesliga", "ligue1"}
# Seconds to keep each tool's answer. Standings change after matches, Elo daily.
TTL = {"get_standings": 300, "get_ratings": 3600, "list_games": 120}

cache = TTLCache()
client: httpx.AsyncClient


@asynccontextmanager
async def lifespan(_: FastAPI):
    global client
    client = httpx.AsyncClient(timeout=20, headers={"x-api-key": API_KEY})
    yield
    await client.aclose()


app = FastAPI(title="Soccer analytics backend", lifespan=lifespan)


async def call(tool: str, body: dict, response: Response) -> dict:
    async def load() -> dict:
        r = await client.post(f"{BASE}/{tool}", json=body)
        if r.status_code == 429:
            raise HTTPException(429, "Upstream rate limit, retry shortly")
        r.raise_for_status()
        return r.json()["data"]

    try:
        data, state = await cache.get_or_load(cache.key(tool, body), TTL[tool], load)
    except httpx.HTTPStatusError as e:
        raise HTTPException(502, f"Upstream returned {e.response.status_code}")
    response.headers["X-Cache"] = state
    return data


def check_league(league: str) -> str:
    if league not in LEAGUES:
        raise HTTPException(422, f"league must be one of {sorted(LEAGUES)}")
    return league


@app.get("/health")
async def health():
    return {"ok": True, "cache": {"hits": cache.hits, "misses": cache.misses, "stale": cache.stale}}


@app.get("/leagues/{league}/standings")
async def standings(league: str, response: Response, season: int | None = None):
    body = {"league": check_league(league)}
    if season:
        body["season"] = season
    return await call("get_standings", body, response)


@app.get("/leagues/{league}/ratings")
async def ratings(league: str, response: Response, limit: int = Query(20, le=50)):
    return await call("get_ratings", {"league": check_league(league), "limit": limit}, response)


@app.get("/leagues/{league}/overview")
async def overview(league: str, response: Response):
    """Table position next to Elo rank, plus points per game."""
    check_league(league)
    table = await call("get_standings", {"league": league}, response)
    elo = await call("get_ratings", {"league": league, "limit": 50}, response)
    elo_by_id = {r["team_id"]: r for r in elo["ratings"]}
    rows = []
    for t in table["standings"]:
        e = elo_by_id.get(t["team_id"])
        rows.append({
            "team": t["display_name"],
            "table_rank": t["rank"],
            "points": t["points"],
            "points_per_game": round(t["points"] / t["played"], 2) if t["played"] else None,
            "elo": e["elo"] if e else None,
            "elo_rank": e["rank"] if e else None,
            "rank_gap": (t["rank"] - e["rank"]) if e else None,  # positive: table sits below Elo
        })
    return {"league": league, "as_of": elo["as_of"], "rows": rows}

How to run it

python3.12 -m venv .venv
.venv/bin/pip install -r requirements.txt
export STRIKER_API_KEY=your-key
.venv/bin/uvicorn app.main:app --port 8000

Then, from a second terminal:

curl -s -D - -o /dev/null http://127.0.0.1:8000/leagues/soccer/overview | grep -i x-cache   # MISS
curl -s -D - -o /dev/null http://127.0.0.1:8000/leagues/soccer/overview | grep -i x-cache   # HIT
curl -s http://127.0.0.1:8000/leagues/soccer/overview | head -c 400
curl -s http://127.0.0.1:8000/health
curl -s -w ' %{http_code}\n' http://127.0.0.1:8000/leagues/nba/standings   # 422, not in the allowed set

The first call is slower because it makes two upstream requests. The second is served from memory. FastAPI also serves interactive docs at /docs, which lets you try each route in a browser.

How to extend it

  • More tools. Add list_games for fixtures and results, using the TTL entry already in the file. Pass status and a date range through as validated query parameters, and keep an allow-list so clients cannot request arbitrary upstream calls.
  • Shared cache. Replace TTLCache with Redis using SET key value EX ttl. Keep the lock logic with a short Redis lock so several workers share one upstream call per window.
  • Derived metrics. Add per-club goal difference per game, home versus away points per game from the home and away strings, or a rolling form score from the form string.
  • Auth and quotas. Add an API key dependency to your own routes and a per-key request counter, so you can hand the service to a team without handing out the upstream key.

Limits and when not to use this

The cache lives in process memory. It is lost on restart, it is not shared between workers, and it grows with the number of distinct request bodies. The code only allows a few parameter shapes, which bounds growth, but add a size limit before you open more parameters.

The service has no authentication. Run it on localhost, behind a private network or behind your own gateway. If you put it on the public internet as is, anyone can read data through your key and spend your credits, and a public pass-through is also not allowed by the data terms. You may store data, train models and show your users what you derive, but you may not redistribute the data or run it as a raw feed of its own.

The upstream API is the source of truth for freshness. The TTLs here are starting points. A five minute standings cache is right for a dashboard and wrong for anything that must show a final score within seconds of the whistle.

Do not use this stack if your traffic is a handful of requests a day. Call the API directly. Do not use it either if you need a durable history of changes, because a cache keeps only the latest answer. Write responses to a database on a schedule instead.

Ratings are ours, based on results, and are not a league ranking. Standings are computed from final matches and carry point deductions where they apply.

FAQ

Why cache in front of a paid API instead of calling it per request? Standings change after matches, not after page views. A five minute cache turns hundreds of identical requests into one upstream call, which keeps credit use flat and your response times low. Single-flight loading also stops a burst of cold requests from all hitting the API at once.

Will this cache work with several uvicorn workers? Each worker keeps its own in-memory cache, so a 4 worker deployment makes up to 4 upstream calls per cache window. That is fine for a starter. For shared caching, swap the TTLCache class for Redis and keep the same get_or_load interface.

Which leagues does the service expose? Six in the starter: soccer (the Premier League default), mls, laliga, seriea, bundesliga and ligue1. StrikerAPI covers 17 leagues, so you can add the rest by extending the LEAGUES set, after checking each tool's league list in the docs.

Live from the API

Free to embed on your own site, with no key needed. Get the embed code.

Get a free key Or download whole seasons as Parquet

Checked against the live API on 2026-12-06. Questions: hello@sportsdatahq.com.