Skip to content

Python Code Examples

Setup & Configuration

python
import requests
import json
from datetime import datetime

# API Configuration
API_BASE_URL = "https://sofasport.p.rapidapi.com"
API_KEY = "YOUR_RAPIDAPI_KEY"  # Replace with your RapidAPI key

# Headers for all requests
HEADERS = {
    "X-RapidAPI-Key": API_KEY,
    "X-RapidAPI-Host": "sofasport.p.rapidapi.com"
}

def make_request(endpoint, params=None):
    """Make API request with error handling"""
    url = f"{API_BASE_URL}{endpoint}"
    response = requests.get(url, headers=HEADERS, params=params)

    if response.status_code == 200:
        return response.json()
    elif response.status_code == 401:
        raise Exception("Invalid API key")
    elif response.status_code == 403:
        raise Exception("Access forbidden - check subscription")
    elif response.status_code == 429:
        raise Exception("Rate limit exceeded")
    else:
        raise Exception(f"API Error: {response.status_code}")

Workflow 1: Get All Sports

python
def get_all_sports():
    """Get list of all available sports"""
    data = make_request("/v1/sports")
    return data.get('data', [])

# Usage
sports = get_all_sports()
print("Available Sports:")
for sport in sports:
    print(f"  {sport['id']}: {sport['name']}")

# Output:
# Available Sports:
#   1: Football
#   2: Basketball
#   4: Ice Hockey
#   5: Tennis
#   ...

Workflow 2: Get Categories by Sport

python
def get_categories(sport_id):
    """Get categories (countries/leagues) for a sport"""
    data = make_request("/v1/categories", {"sport_id": sport_id})
    return data.get('data', [])

# Usage - Get football categories
categories = get_categories(1)  # 1 = Football
print("\nFootball Categories:")
for cat in categories[:10]:
    print(f"  {cat['id']}: {cat['name']} ({cat.get('alpha2', 'N/A')})")

# Output:
# Football Categories:
#   1: England (EN)
#   2: Spain (ES)
#   3: Italy (IT)
#   ...

Workflow 3: Get Today's Matches

python
def get_today_matches(sport_id=1, timezone_offset=0):
    """
    Get all matches for today

    Args:
        sport_id: Sport ID (default: 1 for Football)
        timezone_offset: Timezone offset (-11 to 13)
    """
    today = datetime.now().strftime('%Y-%m-%d')

    # Step 1: Get categories with events today
    data = make_request("/v1/calendar/categories", {
        "sport_id": sport_id,
        "date": today,
        "timezone": timezone_offset
    })

    categories = data.get('data', [])
    all_matches = []

    # Step 2: Get events for each category
    for cat in categories:
        category_id = cat['category']['id']
        events_data = make_request("/v1/events/schedule/category", {
            "category_id": category_id,
            "date": today
        })

        events = events_data.get('data', [])
        all_matches.extend(events)

    return all_matches

# Usage
matches = get_today_matches()
print(f"\nFound {len(matches)} matches today")

for match in matches[:5]:
    home = match['homeTeam']['name']
    away = match['awayTeam']['name']
    home_score = match.get('homeScore', {}).get('current', '-')
    away_score = match.get('awayScore', {}).get('current', '-')
    status = match['status']['description']
    tournament = match.get('tournament', {}).get('name', '')

    print(f"  {home} {home_score} - {away_score} {away} [{status}] ({tournament})")

Workflow 4: Get Live Matches

python
def get_live_matches(sport_id=1):
    """Get all live matches for a sport"""
    data = make_request("/v1/events/schedule/live", {"sport_id": sport_id})
    return data.get('data', [])

# Usage
live_matches = get_live_matches(1)
print(f"\nLive Matches: {len(live_matches)}")

for match in live_matches[:10]:
    home = match['homeTeam']['name']
    away = match['awayTeam']['name']
    home_score = match.get('homeScore', {}).get('current', 0)
    away_score = match.get('awayScore', {}).get('current', 0)
    status = match['status']['description']
    tournament = match.get('tournament', {}).get('name', '')

    print(f"  {home} {home_score} - {away_score} {away} [{status}] ({tournament})")

Workflow 5: Get Match Details

python
def get_event_data(event_id):
    """Get detailed event/match data"""
    data = make_request("/v1/events/data", {"event_id": event_id})
    return data.get('data', {})

def get_event_statistics(event_id):
    """Get match statistics"""
    data = make_request("/v1/events/statistics", {"event_id": event_id})
    return data.get('data', {})

def get_event_lineups(event_id):
    """Get team lineups"""
    data = make_request("/v1/events/lineups", {"event_id": event_id})
    return data.get('data', {})

def get_event_incidents(event_id):
    """Get match incidents (goals, cards, substitutions)"""
    data = make_request("/v1/events/incidents", {"event_id": event_id})
    return data.get('data', {})

# Usage
event_id = 13981507  # Example event ID

# Get event details
event = get_event_data(event_id)
print(f"\nMatch: {event['homeTeam']['name']} vs {event['awayTeam']['name']}")
print(f"Tournament: {event['tournament']['name']}")
print(f"Status: {event['status']['description']}")
print(f"Score: {event.get('homeScore', {}).get('current', 0)} - {event.get('awayScore', {}).get('current', 0)}")

# Get incidents
incidents = get_event_incidents(event_id)
if incidents:
    print("\nIncidents:")
    for incident in incidents:
        inc_type = incident.get('incidentType', 'Unknown')
        time = incident.get('time', 0)
        print(f"  {time}' - {inc_type}")

Workflow 6: Get League Standings

python
def get_unique_tournaments(category_id):
    """Get tournaments for a category"""
    data = make_request("/v1/unique-tournaments", {"category_id": category_id})
    return data.get('data', [])

def get_tournament_seasons(unique_tournament_id):
    """Get seasons for a tournament"""
    data = make_request("/v1/unique-tournaments/seasons", {
        "unique_tournament_id": unique_tournament_id
    })
    return data.get('data', [])

def get_standings(unique_tournament_id, season_id, standing_type="total"):
    """Get league standings"""
    data = make_request("/v1/seasons/standings", {
        "unique_tournament_id": unique_tournament_id,
        "seasons_id": season_id,
        "standing_type": standing_type
    })
    return data.get('data', {})

# Usage - Get Premier League standings
def display_premier_league_table():
    tournament_id = 17  # Premier League

    # Get current season
    seasons = get_tournament_seasons(tournament_id)
    if seasons:
        current_season = seasons[0]
        season_id = current_season['id']
        print(f"Season: {current_season['name']}\n")

        # Get standings
        standings_data = get_standings(tournament_id, season_id)

        if standings_data:
            table = standings_data['standings'][0]['rows']

            print(f"{'Pos':<4} {'Team':<25} {'P':<4} {'W':<4} {'D':<4} {'L':<4} {'GD':<5} {'Pts':<4}")
            print("-" * 60)

            for team in table:
                pos = team['position']
                name = team['team']['name'][:24]
                played = team['matches']
                won = team['wins']
                drawn = team['draws']
                lost = team['losses']
                gd = int(team['scoreDiffFormatted'])
                points = team['points']

                print(f"{pos:<4} {name:<25} {played:<4} {won:<4} {drawn:<4} {lost:<4} {gd:<+5} {points:<4}")

display_premier_league_table()

Workflow 7: Get Team Information

python
def get_team_data(team_id):
    """Get team information"""
    data = make_request("/v1/teams/data", {"team_id": team_id})
    return data.get('data', {})

def get_team_players(team_id):
    """Get team roster"""
    data = make_request("/v1/teams/players", {"team_id": team_id})
    return data.get('data', [])

def get_team_events(team_id, page=0):
    """Get team match history"""
    data = make_request("/v1/teams/events", {
        "team_id": team_id,
        "page": page,
        "course_events": "last"
    })
    return data.get('data', [])

# Usage - Get Chelsea FC info
team_id = 38  # Chelsea FC

team = get_team_data(team_id)
print(f"\nTeam: {team['name']}")
print(f"Country: {team.get('country', {}).get('name', 'N/A')}")
print(f"Founded: {datetime.fromtimestamp(team.get('foundationDateTimestamp', 0)).year if team.get('foundationDateTimestamp') else 'N/A'}")

# Get players
players = get_team_players(team_id)
print(f"\nPlayers ({len(players['players'])}):")
for player in players['players'][:10]:
    name = player['player']['name']
    position = player['player'].get('position', 'N/A')
    print(f"  {name} ({position})")

Workflow 8: Get Player Statistics

python
def get_player_data(player_id):
    """Get player information"""
    data = make_request("/v1/players/data", {"player_id": player_id})
    return data.get('data', {})

def get_player_statistics_seasons(player_id):
    """Get available seasons for player statistics"""
    data = make_request("/v1/players/statistics/seasons", {"player_id": player_id})
    return data.get('data', [])

def get_player_statistics(player_id, unique_tournament_id, season_id):
    """Get player statistics for a season"""
    data = make_request("/v1/players/statistics/result", {
        "player_id": player_id,
        "unique_tournament_id": unique_tournament_id,
        "seasons_id": season_id,
        "player_stat_type": "overall"
    })
    return data.get('data', {})

# Usage
player_id = 12994  # Example player ID

player = get_player_data(player_id)
print(f"\nPlayer: {player['name']}")
print(f"Position: {player.get('position', 'N/A')}")
print(f"Country: {player.get('country', {}).get('name', 'N/A')}")

# Get statistics
seasons = get_player_statistics_seasons(player_id)
if seasons:
    recent_season = seasons['uniqueTournamentSeasons'][9]
    season_id = recent_season['seasons'][0]['id']
    tournament_id = recent_season['uniqueTournament']['id']

    stats = get_player_statistics(player_id, tournament_id, season_id)

    if stats and 'statistics' in stats:
        stat = stats['statistics']
        print(f"\nStatistics ({recent_season['seasons'][0]['name']}):")
        print(f"  Matches: {stat.get('matchesStarted', 0)}")
        print(f"  Goals: {stat.get('goals', 0)}")
        print(f"  Assists: {stat.get('assists', 0)}")
        print(f"  Minutes: {stat.get('minutesPlayed', 0)}")
        
"""
Player: Lionel Messi
Position: F
Country: Argentina

Statistics (UEFA Champions League 22/23):
  Matches: 7
  Goals: 4
  Assists: 4
  Minutes: 615
"""

Workflow 9: Live Score Monitor

python
import time
from collections import deque

class LiveScoreMonitor:
    def __init__(self, sport_id=1, refresh_interval=60):
        self.sport_id = sport_id
        self.refresh_interval = refresh_interval
        self.tracked_matches = {}

    def get_live_matches(self):
        """Get current live matches"""
        data = make_request("/v1/events/schedule/live", {"sport_id": self.sport_id})
        return data.get('data', [])

    def check_score_changes(self, matches):
        """Check for score changes"""
        changes = []

        for match in matches:
            match_id = match['id']
            home_score = match.get('homeScore', {}).get('current', 0)
            away_score = match.get('awayScore', {}).get('current', 0)
            current_score = (home_score, away_score)

            if match_id in self.tracked_matches:
                previous_score = self.tracked_matches[match_id]

                if current_score != previous_score:
                    changes.append({
                        'match': match,
                        'previous': previous_score,
                        'current': current_score
                    })

            self.tracked_matches[match_id] = current_score

        return changes

    def monitor(self, duration_minutes=5):
        """Monitor live matches for changes"""
        print(f"Starting live score monitor for {duration_minutes} minutes...")
        print(f"Refresh interval: {self.refresh_interval} seconds\n")

        end_time = time.time() + (duration_minutes * 60)

        while time.time() < end_time:
            timestamp = datetime.now().strftime('%H:%M:%S')
            print(f"[{timestamp}] Checking for updates...")

            try:
                matches = self.get_live_matches()
                print(f"Live matches: {len(matches)}")

                changes = self.check_score_changes(matches)

                if changes:
                    print("\n*** SCORE CHANGES DETECTED! ***")
                    for change in changes:
                        match = change['match']
                        home = match['homeTeam']['name']
                        away = match['awayTeam']['name']
                        prev = change['previous']
                        curr = change['current']

                        print(f"  {home} {prev[0]} -> {curr[0]} - {curr[1]} <- {prev[1]} {away}")
                else:
                    for match in matches[:5]:
                        home = match['homeTeam']['name']
                        away = match['awayTeam']['name']
                        h_score = match.get('homeScore', {}).get('current', 0)
                        a_score = match.get('awayScore', {}).get('current', 0)
                        status = match['status']['description']
                        print(f"  {home} {h_score} - {a_score} {away} [{status}]")

            except Exception as e:
                print(f"Error: {e}")

            time.sleep(self.refresh_interval)

        print("\nMonitoring ended.")

# Usage
monitor = LiveScoreMonitor(sport_id=1, refresh_interval=30)
monitor.monitor(duration_minutes=10)

Workflow 10: Get Match Odds

python
def get_match_odds(event_id, provider_id=1):
    """
    Get betting odds for a match

    Args:
        event_id: Event ID
        provider_id: Odds provider (1 = Bet365)
    """
    data = make_request("/v1/events/odds/all", {
        "event_id": event_id,
        "provider_id": provider_id,
        "odds_format": "decimal"
    })
    return data.get('data', {})

# Usage
event_id = 14442358

# Get event info first
event = get_event_data(event_id)
print(f"\n{event['homeTeam']['name']} vs {event['awayTeam']['name']}")
print("=" * 40)

# Get odds
odds_data = get_match_odds(event_id)

if odds_data:
    for market in odds_data:
        market_name = market.get('marketName', 'Unknown')
        print(f"\n{market_name}:")

        for choice in market.get('choices', []):
            name = choice.get('name', '')
            odds = choice.get('fractionalValue', 0)
            print(f"  {name}: {odds}")
else:
    print("No odds available for this match")

Complete Example: Football Dashboard

python
#!/usr/bin/env python3
"""
Football Dashboard - Complete Example
Displays live scores, standings, and upcoming matches
"""

import requests
from datetime import datetime

class FootballDashboard:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://sofasport.p.rapidapi.com"
        self.headers = {
            "X-RapidAPI-Key": api_key,
            "X-RapidAPI-Host": "sofasport.p.rapidapi.com"
        }

    def request(self, endpoint, params=None):
        url = f"{self.base_url}{endpoint}"
        response = requests.get(url, headers=self.headers, params=params)
        return response.json() if response.status_code == 200 else None

    def get_live_matches(self):
        data = self.request("/v1/events/schedule/live", {"sport_id": 1})
        return data.get('data', []) if data else []

    def get_standings(self, tournament_id=17):
        # Get current season
        seasons_data = self.request("/v1/unique-tournaments/seasons", {
            "unique_tournament_id": tournament_id
        })

        if not seasons_data or not seasons_data.get('data'):
            return None

        season_id = seasons_data['data'][0]['id']

        # Get standings
        standings_data = self.request("/v1/seasons/standings", {
            "unique_tournament_id": tournament_id,
            "seasons_id": season_id,
            "standing_type": "total"
        })

        return standings_data.get('data') if standings_data else None

    def display_dashboard(self):
        print("\n" + "=" * 60)
        print(f"  FOOTBALL DASHBOARD - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
        print("=" * 60)

        # Live Matches
        print("\n  LIVE MATCHES")
        print("  " + "-" * 56)

        live_matches = self.get_live_matches()

        if live_matches:
            for match in live_matches[:8]:
                home = match['homeTeam']['name'][:12]
                away = match['awayTeam']['name'][:12]
                h_score = match.get('homeScore', {}).get('current', 0)
                a_score = match.get('awayScore', {}).get('current', 0)
                status = match['status']['description']
                tournament = match.get('tournament', {}).get('name', '')[:15]

                print(f"  {home:<12} {h_score} - {a_score} {away:<12} [{status:<8}] {tournament}")
        else:
            print("  No live matches at the moment")

        # Standings (Top 5)
        print("\n  PREMIER LEAGUE STANDINGS (Top 5)")
        print("  " + "-" * 56)

        standings = self.get_standings(17)  # Premier League

        if standings:
            table = standings[0]['rows'][:5]

            print(f"  {'#':<3} {'Team':<20} {'P':<3} {'GD':<4} {'Pts':<3}")
            print("  " + "-" * 36)

            for team in table:
                pos = team['position']
                name = team['team']['name'][:18]
                played = team['matches']
                gd = int(team['scoreDiffFormatted'])
                points = team['points']

                print(f"  {pos:<3} {name:<20} {played:<3} {gd:<+4} {points:<3}")

        print("\n" + "=" * 60)

# Usage
if __name__ == "__main__":
    API_KEY = "YOUR_RAPIDAPI_KEY"
    dashboard = FootballDashboard(API_KEY)
    dashboard.display_dashboard()

We’re dedicated to providing the best API products.