
Matchday: A Serverless Football Results Tool on AWS Lambda, API Gateway and DynamoDB
In this post, we'll look at Matchday, a small tool that answers those questions from one place. It started as a command line scraper and grew into a serverless web app on AWS: a Streamlit front end, API Gateway, Lambda functions, and a DynamoDB cache that keeps the whole thing fast and polite to the upstream APIs.
DataEngineer
Football fans juggle a lot of questions in a single evening. Who plays today? Who starts for my team, and who is the manager? Where is my team in the table? What club does this player play for now, and where did he play before? The answers are all public, but they are spread across several sites and APIs, each with its own format.
The Challenge
A tool like this runs into a handful of practical problems:
- Scattered Sources: Results, lineups, standings and player data come from different endpoints, plus Wikipedia and OpenStreetMap for the details ESPN doesn't provide
- Repeated Calls: Many people ask for the same Premier League table within the same hour
- Idle Infrastructure: Traffic is spiky (match days, weekends) and close to zero the rest of the time
- Two Ways to Use It: A terminal user wants a CLI, a casual user wants a web page, and nobody wants to maintain two code bases
- Environments: A change should be testable in staging before it reaches production
Why Serverless on AWS?
An always-on server for a tool that is idle most of the day is the wrong shape. The serverless building blocks match the workload:
- Lambda: Runs only when a request arrives, no servers to patch
- API Gateway: A managed HTTP entry point in front of the functions
- DynamoDB (on-demand): A key-value cache with no capacity planning, plus a built-in TTL that deletes expired items for free
- One code base: The same Python module powers the CLI and the Lambda, so there is a single place to fix a bug
Solution Architecture
The solution has five parts:
- Clients: The CLI (
espn_results.py) and the Streamlit web UI (app.py)
- API Gateway: Receives
GET /?action=<action>&...from the web UI
- Lambda: Two functions,
clt-espn-results-productionandclt-espn-results-staging, running the samelambda_handler.pyandespn_results.py
- DynamoDB: A table named
espn_cachethat stores every upstream response, keyed by URL, with a 1-hour TTL
- External APIs: ESPN (HTML and JSON), Wikipedia and OpenStreetMap Nominatim, none of which need credentials
The request flow is simple:
- The Streamlit page calls API Gateway with an
actionand its parameters
- API Gateway invokes the Lambda
- The Lambda checks DynamoDB for the URL it needs
- Cache hit: it returns the stored response
- Cache miss: it calls the external API, stores the response in DynamoDB, and returns it
- The CLI skips API Gateway and Lambda: it talks to DynamoDB and the external APIs directly from your machine
Implementation Deep Dive
1. The Cache Table
The cache is the part that makes everything else cheap and fast. One setup script creates a DynamoDB table with on-demand billing and turns on TTL:
TABLE_NAME = "espn_cache"TTL_ATTR = "expires_at"
def create_table(ddb, region): table = ddb.create_table( TableName=TABLE_NAME, KeySchema=[{"AttributeName": "cache_key", "KeyType": "HASH"}], AttributeDefinitions=[{"AttributeName": "cache_key", "AttributeType": "S"}], BillingMode="PAY_PER_REQUEST", ) table.wait_until_exists()
# enable TTL (idempotent) client = boto3.client("dynamodb", region_name=region) client.update_time_to_live( TableName=TABLE_NAME, TimeToLiveSpecification={"AttributeName": TTL_ATTR, "Enabled": True}, )The partition key is the URL being fetched, and
expires_at holds the expiry time. Every cached response lives for one hour ( CACHE_TTL_SECONDS = 3600 in the code), after which DynamoDB removes it without any cleanup job.
The access pattern is the classic cache-aside, sketched here in simplified form:
def fetch_json(url): cached = table.get_item(Key={"cache_key": url}).get("Item") if cached: return json.loads(cached["body"]) # cache hit
body = http_get(url) # cache miss: call upstream table.put_item(Item={ "cache_key": url, "body": json.dumps(body), "expires_at": int(time.time()) + CACHE_TTL_SECONDS, }) return bodyThe script can also attach an inline IAM policy that gives a user only
dynamodb:GetItem and dynamodb:PutItem on this one table, so the CLI never needs broader access:policy_doc = json.dumps({ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["dynamodb:GetItem", "dynamodb:PutItem"], "Resource": table_arn, }],})iam.put_user_policy(UserName=iam_user, PolicyName="ESPNResultsDynamoDB", PolicyDocument=policy_doc)2. The Lambda Handler
The handler is a thin router. It reads the
action query parameter and calls the same functions the CLI uses. The trick that lets one code base serve both worlds is that those functions print() their output, so the handler captures standard output and returns it as JSON:def _capture(fn, *args): buf = io.StringIO() with contextlib.redirect_stdout(buf): try: fn(*args) except Exception as e: return None, str(e) return buf.getvalue(), None
def lambda_handler(event, context): qs = event.get("queryStringParameters") or {} action = qs.get("action", "results")
if action == "lineup": team = qs.get("team") if not team: return _err("'team' parameter required") date = espn.normalize_date(qs.get("date")) out, err = _capture(espn.find_lineup, team, date) return _ok(out) if not err else _err(err)
if action == "standings": league = qs.get("league") slug = espn.LEAGUE_SLUGS.get(league.lower(), league) out, err = _capture(espn.fetch_standings, slug) return _ok(out) if not err else _err(err) # ... results, player, teamFive actions are exposed:
results , lineup , standings , player and team . A sixth, scrape_stadiums , is an admin action that loads stadium data into DynamoDB.3. The Web UI
The Streamlit app is a plain HTTP client. It has no AWS SDK and no credentials, only the API URL:
API = "https://<api-id>.execute-api.us-east-1.amazonaws.com/"
def call(params): try: r = requests.get(API, params=params, timeout=30) data = r.json() return data.get("result") or data.get("error", "No response") except Exception as e: return f"Error: {e}"
Each tab builds its parameters (
action=lineup&team=... ), calls call() , and renders the text that comes back as cards, headers and tables. A dictionary of 51 leagues and cups, mapped to ESPN slugs such as eng.1 or uefa.champions , fills the dropdowns.4. Deploying to Staging and Production
Both Lambda functions run the same two files, so one script packages them once and updates both:
FUNCTIONS=("clt-espn-results-production" "clt-espn-results-staging")REGION="us-east-1"
zip -q deploy.zip lambda_handler.py espn_results.py
for FN in "${FUNCTIONS[@]}"; do aws lambda update-function-code \ --function-name "$FN" \ --zip-file "fileb://deploy.zip" \ --region "$REGION"doneThe only dependencies are
boto3 (already in the Lambda runtime) and the Python standard library, so the package is two files, with no layers to build.Real-World Use Case: A Match Day Companion
Let's walk through what Matchday does, one tab at a time. The screenshots below come from the deployed web app.
Results
Leave the date blank for today, or type
YYYYMMDD or YYYY-MM-DD , and optionally filter by league. Each game shows kickoff time (in the Europe/Madrid timezone), score, status, venue, city and country. Without a league filter, the output ends with the list of leagues found that day, so you can pick one.

The same data is available from the terminal:
python3 espn_results.py 2026-10-27 -l "champions"

Lineup
Pick a league and a team, and the tool finds that team's match for the day. For a live game, the header shows the score and status, and
↓ / ↑ mark substitutions. Each team block includes the league position, the next fixture, the manager and their nationality, the average age of the starting XI, and every player's age and nationality. If the team has no match in its default league that day, it searches cups and second divisions (Carabao Cup, FA Cup, Copa del Rey and others).

Pick a league and a team, and the tool finds that team's match for the day. For a live game, the header shows the score and status, and
↓ / ↑ mark substitutions. Each team block includes the league position, the next fixture, the manager and their nationality, the average age of the starting XI, and every player's age and nationality. If the team has no match in its default league that day, it searches cups and second divisions (Carabao Cup, FA Cup, Copa del Rey and others).
Sample output from the CLI:
Bologna 3 - 2 AC Milan [Second Half]
AC Milan [4-2-3-1]-------------------League position: 3rd (18 pts, 8 played)Next match: AC Milan vs Inter — Sat 01 Nov 2026, 20:45 (Italian Serie A)Manager: Sergio Conceição (Portuguese)Avg age (XI): 27.1Starting XI: 1 G Mike Maignan 31y France 5 CD-L Strahinja Pavlovic 25y Serbia ...Bench: 11 SUB Christian Pulisic ↑ USA 10 SUB Luka Modric ↑ 34y CroatiaThe manager's nationality comes from Wikipedia, which is why the cache matters: that lookup is the slowest part of the request.
Standings

Choose a league and fetch the table. Columns are played, wins, draws, losses, goals for, goals against, difference and points, with the qualification and relegation zones shown inline:
Premiership de Inglaterra 2026/2------------------------------------------------------------ # Team J P DIF PTS GC GF E G------------------------------------------------------------ 1 Manchester City 8 1 +11 21 9 20 0 7 [Champions League] 2 Arsenal 8 1 +8 21 5 13 0 7 [Champions League] ... 18 Nottingham Forest 8 4 -4 6 10 6 3 1 [Relegation] 19 Coventry City 8 6 -9 6 15 6 0 2 [Relegation] 20 Sunderland 8 5 -8 5 14 6 2 1 [Relegation]Player tab

Type a name (
Harry Kane , Messi ) and the tool returns the current club, league, position, nationality, and the clubs of the career with appearances:Harry Kane Current club : Bayern Munich League : German Bundesliga Position : Atacante Nationality : Inglaterra
Career (clubs):---------------------------------------- Bayern Munich (4 apps) Tottenham Hotspur (13 apps) ...Team

The Team tab answers "which tier does this club play in, and where is its stadium?":
Leicester City → Championship (2nd tier) Stadium : King Power Stadium Location : Leicester, United Kingdom Coords : 52.6203970, -1.1423352 Maps : https://www.openstreetmap.org/?mlat=52.6203970&mlon=-1.1423352&zoom=15 GMaps : https://www.google.com/maps?q=52.6203970,-1.1423352Coordinates come from OpenStreetMap Nominatim, which needs no API key.
Note on the evidence: the screenshots show the five tabs of the deployed app and their inputs. The outputs above are sample runs of the same functions from the CLI, as documented in the project README.
Why This Design Works
Performance Advantages
- Cache-First: Repeated requests inside the hour are served from DynamoDB, not from ESPN or Wikipedia
- Shared Cache: The CLI, the staging Lambda and the production Lambda all read and write the same table
- No Cold Infrastructure to Warm: Lambda scales from zero to the number of concurrent requests without any capacity planning
- Small Package: Two Python files and no third-party layers keep deploys and cold starts light
Cost Efficiency
Nothing in this stack runs when nobody is using it:
- Lambda: billed per request and per millisecond of execution
- API Gateway: billed per request
- DynamoDB on-demand: billed per read and write, plus the storage of cached items, which TTL deletes after an hour
- No servers, no NAT gateway, no always-on instances
For a personal project with spiky traffic, this keeps the bill close to zero when idle. I haven't measured the monthly cost, so check the AWS pricing pages for your own request volume.
Advanced Features
Teams and Stadiums
Locating a stadium needs a place name turned into coordinates. The tool keeps a table of stadium aliases (
STADIUM_ALIASES ) for the geocoding step, and an admin action ( scrape_stadiums ) can load stadium data into DynamoDB, which the team lookup can read back ( _get_stadium_from_ddb ) before it falls back to OpenStreetMap.Falling Back Across Competitions
A team can play in a league, a domestic cup and a continental competition. The lineup search tries the default league first, then falls back to cups and second divisions, so asking for "Brentford" on a cup night still finds the match.
Best Practices and Considerations
Key Best Practices
- Cache by URL, expire by TTL: Let DynamoDB delete old items instead of writing cleanup code
- Least Privilege: Give the CLI user
GetItemandPutItemon one table, nothing else
- One Code Base, Two Entry Points: Keep business logic in a module that the CLI and the Lambda both import
- Separate Staging from Production: Deploy to staging first, then production, from the same artifact
- Keep Secrets Out of the UI: The Streamlit app holds only a URL, never AWS credentials
Considerations
- Unofficial Sources: The HTML scrape reads state embedded in the ESPN page, and the JSON endpoints are not documented for public use. They can change without notice
- Text Coupling: Returning printed text keeps the code simple, but the UI has to parse that text with regular expressions. A JSON response would be more robust
- Open API: The endpoint has no authentication and allows any origin. Before sharing it widely, add an API key or usage plan, throttling, and a narrower CORS setting
- Upstream Etiquette: Nominatim publishes a usage policy that asks for low request rates, so the cache is part of being a good citizen
- Cold Starts: The first request after an idle period is slower, and the web client waits at most 30 seconds
Getting Started
Ready to run it yourself? Here's the short path:
- Create the cache:
python3 setup_aws.py --region us-east-1 --iam-user YOUR_IAM_USERNAME
- Try the CLI :
python3 espn_results.py --lineup "liverpool"
- Create the Lambda functions and API Gateway (production and staging), pointing at
lambda_handler.lambda_handler
- Deploy the code:
./infrastructure/deploy.sh
- Run the UI: set
APIinapp.pyto your API Gateway URL, thenstreamlit run app.py
The complete code and the CLI reference are in the
matchday project folder next to this post.Conclusion
Matchday started as a script and became a small serverless application without a rewrite: the same Python module serves the terminal and the web, API Gateway and Lambda handle the traffic, and a TTL-based DynamoDB cache keeps responses fast and the upstream APIs calm.
The pattern isn't specific to football. Any tool that wraps slow or rate-limited public data, such as weather, transit or prices, can use the same shape: thin handler, shared module, cache with a TTL.
What would you add next? A JSON API, authentication, or alerts for your team's kickoff? Share your ideas in the comments below!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article