### Python API Request Setup Source: https://sofasport.rapi.one/Complete_Tutorial This Python code sets up the necessary configurations for making API requests, including base URL, API key, and headers. It also includes a utility function for making GET requests with basic error handling. ```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 Today's Football Matches Source: https://sofasport.rapi.one/Complete_Tutorial Sequence of API calls to retrieve today's football matches, starting with getting the sport ID. ```http 1. GET /v1/sports → Get sport_id for Football (1) 2. GET /v1/calendar/categories?sport_id=1&date=2024-03-15&timezone=0 → Get categories with events 3. GET /v1/events/schedule/category?category_id=1&date=2024-03-15 → Get events for each category ``` -------------------------------- ### Get League Standings Source: https://sofasport.rapi.one/Complete_Tutorial Fetches and displays league standings for a specified tournament and season. Requires functions to get unique tournaments, tournament seasons, and standings. The example shows how to retrieve and format the Premier League table. ```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() ``` -------------------------------- ### Sport List Response Example Source: https://sofasport.rapi.one/Complete_Tutorial Example JSON response for a request to list available sports. ```json { "data": [ {"name": "Football", "slug": "football", "id": 1}, {"name": "Basketball", "slug": "basketball", "id": 2}, {"name": "Ice Hockey", "slug": "ice-hockey", "id": 4}, {"name": "Tennis", "slug": "tennis", "id": 5}, {"name": "Handball", "slug": "handball", "id": 6}, {"name": "Volleyball", "slug": "volleyball", "id": 23}, {"name": "Cricket", "slug": "cricket", "id": 62}, {"name": "American Football", "slug": "american-football", "id": 63}, {"name": "Baseball", "slug": "baseball", "id": 64}, {"name": "eSports", "slug": "esports", "id": 72} ] } ``` -------------------------------- ### Get Team Information Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves and displays general team data, roster, and match history. Requires functions to get team data, players, and events. The example demonstrates fetching information for Chelsea FC. ```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 3: Get League Standings Source: https://sofasport.rapi.one/Complete_Tutorial Sequence of API calls to retrieve league standings, starting from getting categories and progressing through tournaments, seasons, and finally standings. ```http 1. GET /v1/categories?sport_id=1 → Get categories 2. GET /v1/unique-tournaments?category_id=1 → Get tournaments for category 3. GET /v1/unique-tournaments/seasons?unique_tournament_id=17 → Get seasons 4. GET /v1/seasons/standings?unique_tournament_id=17&seasons_id=37036&standing_type=total → Get standings ``` -------------------------------- ### Get Player Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Fetches player statistics for a specific season and tournament. Requires functions to get player data, available seasons, and statistics results. The example shows how to retrieve basic information and position for a given player ID. ```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')}") ``` -------------------------------- ### Workflow 5: Get Live Events Source: https://sofasport.rapi.one/Complete_Tutorial Sequence of API calls to retrieve information about live events, first getting the count per sport and then fetching details for a specific sport. ```http 1. GET /v1/sports/number-live → Get number of live events per sport 2. GET /v1/events/schedule/live?sport_id=1 → Get all live football matches ``` -------------------------------- ### Player Attribute Overviews Source: https://sofasport.rapi.one/Complete_Tutorial Get player attribute overviews. ```APIDOC ## GET Player Attribute Overviews ### Description Get player attribute overviews. ### Method GET ### Endpoint /v1/players/attribute-overviews ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### GET Sport List Response Example Source: https://sofasport.rapi.one/Complete_Tutorial This JSON structure represents the response when requesting a list of all available sports from the API. It includes the sport's name, slug, and a unique ID. ```json { "data": [ {"name": "Football", "slug": "football", "id": 1}, {"name": "Basketball", "slug": "basketball", "id": 2}, {"name": "Ice Hockey", "slug": "ice-hockey", "id": 4}, {"name": "Tennis", "slug": "tennis", "id": 5} // ... more sports ] } ``` -------------------------------- ### Player Data Source: https://sofasport.rapi.one/Complete_Tutorial Get player information. ```APIDOC ## GET Player Data ### Description Get player information. ### Method GET ### Endpoint /v1/players/data ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Get Today's Matches Source: https://sofasport.rapi.one/Complete_Tutorial Fetches all matches scheduled for today for a given sport and timezone. This involves two API calls: first to get categories with events, then to get events per category. Requires `datetime` and `make_request`. ```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 Player Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Sequence of API calls to retrieve player statistics, starting with getting team players and then drilling down into seasons and specific results. ```http 1. GET /v1/teams/players?team_id=44 → Get team players 2. GET /v1/players/statistics/seasons?player_id=12994 → Get available seasons 3. GET /v1/players/statistics/result?player_id=12994&unique_tournament_id=34&seasons_id=37167&player_stat_type=overall → Get stats ``` -------------------------------- ### Player Characteristics Source: https://sofasport.rapi.one/Complete_Tutorial Get player characteristics. ```APIDOC ## GET Player Characteristics ### Description Get player characteristics. ### Method GET ### Endpoint /v1/players/characteristics ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Player Photo Source: https://sofasport.rapi.one/Complete_Tutorial Get player photo. ```APIDOC ## GET Player Photo ### Description Get player photo. ### Method GET ### Endpoint /v1/players/photo ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### GET Stage Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves detailed data for a specific stage. ```APIDOC ## GET Stage Data ### Description Get stage data. ### Method GET ### Endpoint `/v1/stages/data` ### Parameters #### Query Parameters - **stage_id** (integer) - Required - Stage ID ``` -------------------------------- ### Player Events Source: https://sofasport.rapi.one/Complete_Tutorial Get player's match history. ```APIDOC ## GET Player Events ### Description Get player's match history. ### Method GET ### Endpoint /v1/players/events ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID - **page** (integer) - Required - Page number (0-indexed) - **course_events** (string) - Required - Event course type ``` -------------------------------- ### Player Statistics Result Source: https://sofasport.rapi.one/Complete_Tutorial Get player statistics. ```APIDOC ## GET Player Statistics Result ### Description Get player statistics. ### Method GET ### Endpoint /v1/players/statistics/result ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID - **unique_tournament_id** (integer) - Required - Unique Tournament ID - **seasons_id** (integer) - Required - Season ID - **player_stat_type** (string) - Required - Statistics type ### Note Use `regularSeason` for hockey statistics. ``` -------------------------------- ### GET Event Point by Point Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves point-by-point data for a tennis event. ```APIDOC ## GET Event Point by Point ### Description Get point-by-point data (tennis). ### Method GET ### Endpoint `/v1/events/point-by-point` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ### Request Example ```json { "event_id": 10290654 } ``` ``` -------------------------------- ### Get Manager Photo Source: https://sofasport.rapi.one/Complete_Tutorial Fetches the profile photo for a given manager. ```APIDOC ## GET Manager Photo ### Description Get manager photo. ### Method GET ### Endpoint `/v1/managers/photo` ### Parameters #### Query Parameters - **manager_id** (integer) - Required - Manager ID ``` -------------------------------- ### Get Manager Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves general information about a specific manager. ```APIDOC ## GET Manager Data ### Description Get manager information. ### Method GET ### Endpoint `/v1/managers/data` ### Parameters #### Query Parameters - **manager_id** (integer) - Required - Manager ID ``` -------------------------------- ### GET Live Schedule Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves all currently live events for a given sport. ```APIDOC ## GET Live Schedule ### Description Get all live events by sport. ### Method GET ### Endpoint `/v1/events/schedule/live` ### Parameters #### Query Parameters - **sport_id** (integer) - Required - Sport ID ``` -------------------------------- ### GET Esports Lineups Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves esports lineups for a specific event. ```APIDOC ## GET Esports Lineups ### Description Get esports lineups. ### Method GET ### Endpoint `/v1/events/esports-lineups` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ### Request Example ```json { "event_id": 10289011 } ``` ``` -------------------------------- ### GET Stage Substages Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves substages for a given stage. ```APIDOC ## GET Stage Substages ### Description Get substages of a stage. ### Method GET ### Endpoint `/v1/stages/substages` ### Parameters #### Query Parameters - **stage_id** (integer) - Required - Stage ID ``` -------------------------------- ### GET Event Media Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves media content such as videos and highlights for an event. ```APIDOC ## GET Event Media ### Description Get media content (videos, highlights). ### Method GET ### Endpoint `/v1/events/media` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### Team Logo Source: https://sofasport.rapi.one/Complete_Tutorial Get a team's logo. ```APIDOC ## GET Team Logo ### Description Get team logo. ### Method GET ### Endpoint /v1/teams/logo ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID - **sport_id** (integer) - Optional - Sport ID ``` -------------------------------- ### Team Rankings Source: https://sofasport.rapi.one/Complete_Tutorial Get a team's rankings. ```APIDOC ## GET Team Rankings ### Description Get team rankings. ### Method GET ### Endpoint /v1/teams/rankings ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ``` -------------------------------- ### GET Team Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves information for a specific team. ```APIDOC ## GET Team Data ### Description Get team information. ### Method GET ### Endpoint `/v1/teams/data` ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ### Request Example ```json { "team_id": 44 } ``` ``` -------------------------------- ### GET Event Form Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the pre-game team form data for an event. ```APIDOC ## GET Event Form ### Description Get pregame team form. ### Method GET ### Endpoint `/v1/events/form` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### GET Team Players Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the roster of players for a specific team. ```APIDOC ## GET Team Players ### Description Get team roster. ### Method GET ### Endpoint `/v1/teams/players` ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ### Request Example ```json { "team_id": 44 } ``` ``` -------------------------------- ### GET Event Lineups Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the team lineups for a specific event. ```APIDOC ## GET Event Lineups ### Description Get team lineups. ### Method GET ### Endpoint `/v1/events/lineups` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### GET Event Odds All Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves all betting odds for a specific event. ```APIDOC ## GET Event Odds All ### Description Get all betting odds. ### Method GET ### Endpoint `/v1/events/odds/all` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID - **odds_format** (string) - Required - Odds format - **provider_id** (integer) - Optional - Provider ID (1 = Bet365) ### Request Example ```json { "event_id": 11930405, "odds_format": "decimal", "provider_id": 1 } ``` ``` -------------------------------- ### Get Referee Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves general information about a specific referee. ```APIDOC ## GET Referee Data ### Description Get referee information. ### Method GET ### Endpoint `/v1/referees/data` ### Parameters #### Query Parameters - **referee_id** (integer) - Required - Referee ID ``` -------------------------------- ### Get Referee Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Fetches statistical data for a given referee. ```APIDOC ## GET Referee Statistics ### Description Get referee statistics. ### Method GET ### Endpoint `/v1/referees/statistics` ### Parameters #### Query Parameters - **referee_id** (integer) - Required - Referee ID ``` -------------------------------- ### GET Team Career History Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the career history for a specific team. ```APIDOC ## GET Team Career History (Motorsport) ### Description Get team career history. ### Method GET ### Endpoint `/v1/teams/career-history` ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ``` -------------------------------- ### Player Statistics Seasons Source: https://sofasport.rapi.one/Complete_Tutorial Get available seasons for player statistics. ```APIDOC ## GET Player Statistics Seasons ### Description Get available seasons for player statistics. ### Method GET ### Endpoint /v1/players/statistics/seasons ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Team Player Statistics Result Source: https://sofasport.rapi.one/Complete_Tutorial Get player statistics by team. ```APIDOC ## GET Team Player Statistics Result ### Description Get player statistics by team. ### Method GET ### Endpoint /v1/teams/player-statistics/result ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID - **unique_tournament_id** (integer) - Required - Unique Tournament ID - **season_id** (integer) - Required - Season ID - **player_stat_type** (string) - Optional - Statistics type ``` -------------------------------- ### GET Stage Data Source: https://sofasport.rapi.one/Complete_Tutorial Fetches detailed data for a specific stage. Requires stage_id. ```http GET /v1/stages/data?stage_id=190582 ``` -------------------------------- ### GET Newly Added Events Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves a list of newly added events. ```APIDOC ## GET Newly Added Events ### Description Get newly added events. ### Method GET ### Endpoint `/v1/events/newly-added-events` ### Parameters **Parameters:** None ``` -------------------------------- ### Get Manager Career History Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the career history of a specific manager. ```APIDOC ## GET Manager Career History ### Description Get manager's career history. ### Method GET ### Endpoint `/v1/managers/career-history` ### Parameters #### Query Parameters - **manager_id** (integer) - Required - Manager ID ``` -------------------------------- ### GET Esports Games Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves esports games for a specific event. ```APIDOC ## GET Esports Games ### Description Get esports games. ### Method GET ### Endpoint `/v1/events/esports-games` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ### Request Example ```json { "event_id": 10289011 } ``` ``` -------------------------------- ### GET Team Events Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the match history for a specific team. ```APIDOC ## GET Team Events ### Description Get team's match history. ### Method GET ### Endpoint `/v1/teams/events` ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID - **page** (integer) - Required - Page number (0-indexed) - **course_events** (string) - Required - Event course type ### Request Example ```json { "team_id": 2817, "page": 0, "course_events": "last" } ``` ``` -------------------------------- ### Get Season Details Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves a summary of season statistics, such as goals and wins. ```APIDOC ## GET Season Details ### Description Get season statistics summary (goals, wins, etc.). ### Method GET ### Endpoint `/v1/seasons/details` ### Parameters #### Query Parameters - **unique_tournament_id** (integer) - Required - Unique Tournament ID - **seasons_id** (integer) - Required - Season ID ``` -------------------------------- ### GET Event Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves complete data for a specific event or match. ```APIDOC ## GET Event Data ### Description Get complete event/match data. ### Method GET ### Endpoint `/v1/events/data` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### Complete Football Dashboard Example Source: https://sofasport.rapi.one/Complete_Tutorial A full Python script to display live football match scores, league standings, and upcoming matches. Requires a RapidAPI key and the 'requests' library. ```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() ``` -------------------------------- ### GET Popular Events Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves a list of popular events for the current day. ```APIDOC ## GET Popular Events ### Description Get today's popular events. ### Method GET ### Endpoint `/v1/events/schedule/popular` ### Parameters #### Query Parameters - **locale** (string) - Required - Locale code ``` -------------------------------- ### Match Timing Information Source: https://sofasport.rapi.one/Complete_Tutorial This JSON snippet illustrates how timing information for a match is provided, including initial duration, maximum duration, extra time, and the start timestamp for the current period. ```json "time": { "initial": 2700, "max": 5400, "extra": 540, "currentPeriodStartTimestamp": 1701068460 } ``` -------------------------------- ### Get Tournament Data Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves detailed data for a given tournament ID. ```APIDOC ## GET Tournament Data ### Description Get tournament data by tournament ID. ### Method GET ### Endpoint `/v1/tournaments/data` ### Parameters #### Query Parameters - **tournament_id** (integer) - Required - Tournament ID ``` -------------------------------- ### GET Event Heatmap Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the team's heatmap data during a match. ```APIDOC ## GET Event Heatmap ### Description Get team heatmap during the match. ### Method GET ### Endpoint `/v1/events/heatmap` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID - **team_id** (integer) - Required - Team ID ``` -------------------------------- ### GET Event Streaks Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves team streak information for an event. ```APIDOC ## GET Event Streaks ### Description Get team streaks. ### Method GET ### Endpoint `/v1/events/streaks` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### GET Schedule by Category Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the event schedule filtered by category and a specific date. ```APIDOC ## GET Schedule by Category ### Description Get event schedule by category and date. ### Method GET ### Endpoint `/v1/events/schedule/category` ### Parameters #### Query Parameters - **category_id** (integer) - Required - Category ID - **date** (string) - Required - Date (YYYY-MM-DD) ``` -------------------------------- ### GET Event Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves detailed statistics for a specific match. ```APIDOC ## GET Event Statistics ### Description Get match statistics. ### Method GET ### Endpoint `/v1/events/statistics` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### Get Player Transfer History Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the transfer history for a specific player. ```APIDOC ## GET Player Transfer History ### Description Get player's transfer history. ### Method GET ### Endpoint `/v1/players/transfer-history` ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Get Unique Tournament Logo Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the logo for a specific unique tournament. ```APIDOC ## GET Unique Tournament Logo ### Description Get tournament logo. ### Method GET ### Endpoint `/v1/unique-tournaments/logo` ### Parameters #### Query Parameters - **unique_tournament_id** (integer) - Required - Unique Tournament ID - **sport_id** (integer) - Optional - Sport ID ``` -------------------------------- ### GET Event Player Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves detailed statistics for an individual player in a match. ```APIDOC ## GET Event Player Statistics ### Description Get individual player statistics. ### Method GET ### Endpoint `/v1/events/player-statistics` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Team Recent Unique Tournaments Source: https://sofasport.rapi.one/Complete_Tutorial Get recent unique tournaments for a team. ```APIDOC ## GET Team Recent Unique Tournaments ### Description Get recent unique tournaments. ### Method GET ### Endpoint /v1/teams/recent-unique-tournaments ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ``` -------------------------------- ### Get Match Details, Statistics, Lineups, and Incidents Source: https://sofasport.rapi.one/Complete_Tutorial Provides functions to fetch detailed data for a specific match, including general information, statistics, team lineups, and match incidents (goals, cards). Requires `event_id` and the `make_request` function. ```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}") ``` -------------------------------- ### GET Event Incidents Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves match incidents such as goals, cards, and substitutions. ```APIDOC ## GET Event Incidents ### Description Get match incidents (goals, cards, substitutions). ### Method GET ### Endpoint `/v1/events/incidents` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID ``` -------------------------------- ### Get Live Matches from SofaScore API Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves all currently live matches for a specified sport. Requires a `sport_id`. The `make_request` function must be defined. ```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})") ``` -------------------------------- ### Fetch and Display Match Odds Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves odds data for a given event ID and prints market names, choices, and their fractional odds. Handles cases where no odds are available. ```python 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") ``` -------------------------------- ### GET Team Current Tournaments Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the current tournaments a specific team is participating in. ```APIDOC ## GET Team Current Tournaments ### Description Get team's current tournaments. ### Method GET ### Endpoint `/v1/teams/current-tournaments` ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ### Request Example ```json { "team_id": 2817 } ``` ``` -------------------------------- ### Workflow 2: Get Match Details Source: https://sofasport.rapi.one/Complete_Tutorial Sequence of API calls to retrieve comprehensive details for a specific match, including basic info, statistics, lineups, and incidents. ```http 1. GET /v1/events/data?event_id=11930405 → Get basic match info 2. GET /v1/events/statistics?event_id=11930405 → Get match statistics 3. GET /v1/events/lineups?event_id=11930405 → Get lineups 4. GET /v1/events/incidents?event_id=11930405 → Get incidents (goals, cards) ``` -------------------------------- ### Get Player National Team Statistics Source: https://sofasport.rapi.one/Complete_Tutorial Fetches the national team statistics for a given player. ```APIDOC ## GET Player National Team Statistics ### Description Get player's national team statistics. ### Method GET ### Endpoint `/v1/players/national-team-statistics` ### Parameters #### Query Parameters - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Live Score Monitor Source: https://sofasport.rapi.one/Complete_Tutorial Monitors live sports matches for score changes at a specified interval. Initializes with a sport ID and refresh rate, then runs for a set duration. ```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) ``` -------------------------------- ### Team Statistics Result Source: https://sofasport.rapi.one/Complete_Tutorial Get team statistics. ```APIDOC ## GET Team Statistics Result ### Description Get team statistics. ### Method GET ### Endpoint /v1/teams/statistics/result ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID - **unique_tournament_id** (integer) - Required - Unique Tournament ID - **season_id** (integer) - Required - Season ID - **team_stat_type** (string) - Optional - Statistics type ``` -------------------------------- ### Team Transfers Source: https://sofasport.rapi.one/Complete_Tutorial Get a team's transfers. ```APIDOC ## GET Team Transfers ### Description Get team transfers. ### Method GET ### Endpoint /v1/teams/transfers ### Parameters #### Query Parameters - **team_id** (integer) - Required - Team ID ``` -------------------------------- ### GET Event Player Heatmap Source: https://sofasport.rapi.one/Complete_Tutorial Retrieves the individual player's heatmap data during a match. ```APIDOC ## GET Event Player Heatmap ### Description Get individual player heatmap. ### Method GET ### Endpoint `/v1/events/player-heatmap` ### Parameters #### Query Parameters - **event_id** (integer) - Required - Event ID - **player_id** (integer) - Required - Player ID ``` -------------------------------- ### Categories Response Example Source: https://sofasport.rapi.one/Complete_Tutorial This JSON response shows a list of sports categories, including details like category name, sport, total events, and associated tournament IDs. ```json { "data": [ { "category": { "name": "England", "slug": "england", "sport": {"name": "Football", "id": 1}, "id": 1, "flag": "england", "alpha2": "EN" }, "totalEvents": 7, "totalVideos": 5, "uniqueTournamentIds": [1044, 17, 18, 25] } ] } ``` -------------------------------- ### Event Data Response Example Source: https://sofasport.rapi.one/Complete_Tutorial This JSON structure represents the detailed data for a specific sports event, including tournament, season, teams, scores, and venue information. ```json { "data": { "tournament": { "name": "Premier League", "category": {"name": "England", "alpha2": "EN"}, "uniqueTournament": {"id": 17, "name": "Premier League"} }, "season": {"name": "Premier League 25/26", "year": "25/26", "id": 76986}, "roundInfo": {"round": 26}, "status": {"code": 100, "description": "Ended", "type": "finished"}, "winnerCode": 3, "homeTeam": {"name": "Chelsea", "id": 38, "nameCode": "CHE"}, "awayTeam": {"name": "Leeds United", "id": 34, "nameCode": "LEE"}, "homeScore": {"current": 2, "period1": 1, "period2": 1}, "awayScore": {"current": 2, "period1": 0, "period2": 2}, "venue": {"name": "Stamford Bridge", "city": {"name": "London"}}, "referee": {"name": "Robert Jones"}, "startTimestamp": 1770751800 } } ``` -------------------------------- ### SofaSport API Authentication Headers Source: https://sofasport.rapi.one/Rapid_Quickstart These headers are mandatory for authenticating your requests to the SofaSport API. Replace 'YOUR_API_KEY' with your actual RapidAPI key. ```text X-RapidAPI-Key: YOUR_API_KEY X-RapidAPI-Host: sofasport.p.rapidapi.com ``` -------------------------------- ### Status Time Information Source: https://sofasport.rapi.one/Complete_Tutorial This JSON snippet shows an alternative way to represent match timing, including a prefix, initial and maximum durations, a timestamp, and extra time. ```json "statusTime": { "prefix": "", "initial": 2700, "max": 5400, "timestamp": 1701068460, "extra": 540 } ```