How to Get Head-to-Head (H2H) Football Stats via API
Build head-to-head (H2H) football stats for any two teams: wins, draws, losses, goals, BTTS, over 2.5 and home/away splits. Python and JavaScript examples using real team IDs.
Head-to-head (H2H) stats summarise every previous meeting between two teams: who won, how many goals were scored, and how the fixture tends to play out. Every match preview, betting site and score app shows them, and Soccerbase built a reputation on its long UK head-to-head records.
This guide shows how to build H2H stats for any two teams in any covered league from raw match results, using Kaizer Chiefs vs Mamelodi Sundowns in the South African Premiership as the worked example. The same code works for Arsenal vs Tottenham, Boca vs River or any other fixture.
What Goes Into H2H Stats
A useful head-to-head panel usually shows:
| Stat | How it is calculated |
|---|---|
| Wins / draws / losses | Count of meetings won by team A, drawn, and won by team B |
| Goals for and against | Sum of each side's goals across all meetings |
| Average goals per meeting | Total goals divided by meetings |
| BTTS % | Share of meetings where both teams scored |
| Over 2.5 % | Share of meetings with 3 or more goals |
| Home / away split | The same numbers split by which team was at home |
| Last 5 meetings | Most recent results, newest first |
| Biggest win | Largest winning margin for each side |
All of these come from one input: the list of finished matches between the two teams. There is no need for a special H2H endpoint once you have that list.
Step 1: Find the Two Team IDs
Search teams by name. The search parameter is case-insensitive and puts the best match first.
curl "https://api.thestatsapi.com/api/football/teams?search=Kaizer%20Chiefs" \
-H "Authorization: Bearer YOUR_API_KEY"
For this example:
- Kaizer Chiefs:
tm_577242 - Mamelodi Sundowns:
tm_455781
Both play in the South African Premier Division (Betway Premiership), comp_8597.
Step 2: Fetch Every Meeting (Python)
GET /football/matches filters by one team_id, so fetch team A's finished matches and keep the ones where team B is the opponent. Leave out competition_id to include cup ties as well as league games.
import requests
API_KEY = "your_api_key_here"
BASE = "https://api.thestatsapi.com/api"
headers = {"Authorization": f"Bearer {API_KEY}"}
def meetings(team_a, team_b, date_from="2016-01-01", competition_id=None):
"""All finished matches between team_a and team_b, newest first."""
params = {
"team_id": team_a,
"status": "finished",
"date_from": date_from,
"per_page": 100,
"page": 1,
}
if competition_id:
params["competition_id"] = competition_id
found = []
while True:
r = requests.get(f"{BASE}/football/matches", headers=headers, params=params)
r.raise_for_status()
body = r.json()
for m in body["data"]:
ids = {m["home_team"]["id"], m["away_team"]["id"]}
if team_b in ids:
found.append(m)
if params["page"] >= body["meta"]["total_pages"]:
return found
params["page"] += 1
games = meetings("tm_577242", "tm_455781") # Chiefs vs Sundowns
print(f"{len(games)} meetings found")
Step 3: Turn Meetings Into H2H Stats
Use the 90-minute score (score.regulation) for the betting-style numbers, because over/under and BTTS markets settle on 90 minutes. Use score.winner for the result so that extra time and penalties in cup ties count the way you expect.
def h2h(games, team_a):
s = {"played": 0, "a_wins": 0, "draws": 0, "b_wins": 0,
"a_goals": 0, "b_goals": 0, "btts": 0, "over_25": 0}
for m in games:
reg = m["score"].get("regulation") or m["score"]
a_home = m["home_team"]["id"] == team_a
a_goals = reg["home"] if a_home else reg["away"]
b_goals = reg["away"] if a_home else reg["home"]
s["played"] += 1
s["a_goals"] += a_goals
s["b_goals"] += b_goals
s["btts"] += a_goals > 0 and b_goals > 0
s["over_25"] += a_goals + b_goals > 2.5
winner = m["score"]["winner"] # "home", "away" or "draw"
if winner == "draw":
s["draws"] += 1
elif (winner == "home") == a_home:
s["a_wins"] += 1
else:
s["b_wins"] += 1
return s
stats = h2h(games, "tm_577242")
n = stats["played"] or 1
print(f"Chiefs {stats['a_wins']}W {stats['draws']}D {stats['b_wins']}L vs Sundowns")
print(f"Goals: {stats['a_goals']}-{stats['b_goals']} | "
f"avg {(stats['a_goals'] + stats['b_goals']) / n:.2f} per game")
print(f"BTTS {stats['btts'] / n:.0%} | Over 2.5 {stats['over_25'] / n:.0%}")
print("\nLast 5 meetings:")
for m in games[:5]:
reg = m["score"].get("regulation") or m["score"]
print(f"{m['utc_date'][:10]} {m['home_team']['name']} {reg['home']}-{reg['away']} {m['away_team']['name']}")
For a home/away split, run h2h() twice: once on the meetings where team A was at home and once on the rest. If a meeting was at a neutral venue (is_neutral: true, common in cup finals), you may want to leave it out of both.
The Same Thing in JavaScript
const BASE = "https://api.thestatsapi.com/api";
const headers = { Authorization: `Bearer ${process.env.THESTATSAPI_KEY}` };
async function meetings(teamA, teamB, dateFrom = "2016-01-01") {
const found = [];
for (let page = 1; ; page++) {
const url = new URL(`${BASE}/football/matches`);
url.search = new URLSearchParams({
team_id: teamA, status: "finished", date_from: dateFrom,
per_page: "100", page: String(page),
});
const res = await fetch(url, { headers });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { data, meta } = await res.json();
for (const m of data) {
if (m.home_team.id === teamB || m.away_team.id === teamB) found.push(m);
}
if (page >= meta.total_pages) return found;
}
}
const games = await meetings("tm_577242", "tm_455781");
console.log(`${games.length} meetings`);
Keep the API key server-side (an API route, server component or backend job). Do not ship it to the browser.
Making It Fast
Fetching every match one team has played over ten years can take several pages. A few habits keep H2H pages quick and cheap on requests:
- Cache finished meetings forever. A finished result never changes. Store meetings by the pair of team IDs and only fetch matches newer than your latest stored one.
- Narrow the window. Most previews only show the last 10 meetings or the last five seasons. Set
date_fromto match. - Filter by competition when it makes sense. League-only H2H (
competition_id=comp_8597) is smaller and often what bettors want, because cup ties play out differently. - Pre-compute for upcoming fixtures. Pull the week's fixtures with
status=scheduled, build H2H for each pair in a background job, and serve it from your database.
Beyond Results: Richer H2H
Once you have the list of meetings, every match ID opens more data:
- xG per meeting from
GET /football/matches/{match_id}/stats, to see whether results matched chance quality. See the xG API guide. - Who scored from
GET /football/matches/{match_id}/timeline. - Lineups from
GET /football/matches/{match_id}/lineups, to see which players featured in previous meetings. - Odds from
GET /football/matches/{match_id}/odds, to compare H2H trends with what the market priced.
To turn H2H goal averages into over/under probabilities, see Under 2.5 Goals: Meaning, Odds and How to Calculate the Probability.
FAQ
What does H2H mean in football?
H2H means head-to-head: the record of previous matches between the same two teams. It usually shows wins, draws and losses for each side, goals scored, and recent results, and it is a standard part of match previews and betting research.
Are head-to-head stats useful for predictions?
They help, but less than people think. Squads and managers change, so a meeting from five years ago says little about today. Recent form, xG and team strength usually predict better. H2H works best as context, especially in derbies and for spotting patterns such as low-scoring fixtures.
Is there a head-to-head endpoint?
You do not need one. Fetch one team's finished matches with GET /football/matches?team_id=...&status=finished and keep the matches against the other team. The full code is above, in Python and JavaScript.
How far back do H2H records go?
As far back as the match history for that league. TheStatsAPI has up to 10 years of history depending on the competition, so most H2H records cover the last several seasons in full. The coverage page lists seasons per league.
Should cup matches count in head-to-head stats?
Most sites include every competitive meeting. For betting models, league-only H2H is often cleaner, because cup ties can go to extra time and teams often rotate their squads. Use competition_id to choose either way, and score.regulation to count only the 90 minutes.
Where can I see Kaizer Chiefs vs Mamelodi Sundowns head-to-head?
The full record, with every result, goals, BTTS and over 2.5 rates, is on the Kaizer Chiefs vs Mamelodi Sundowns head to head page. To build it yourself, run the code above with tm_577242 (Kaizer Chiefs) and tm_455781 (Mamelodi Sundowns). The current league table is on the South African Premier Division standings page.
Ready to Power Your Sports App?
Start your 7-day free trial. All endpoints included on every plan.