### Install understatapi from source Source: https://collinb9.github.io/understatAPI/index Installs the understatapi package from its source repository. This is useful for development or for using the latest unreleased changes. ```shell git clone git@github.com:collinb9/understatAPI understatAPI cd understatAPI python -m pip install . ``` -------------------------------- ### Install understatapi using pip Source: https://collinb9.github.io/understatAPI/index Installs the understatapi package using pip. This is the standard method for installing Python packages. ```shell pip install understatapi ``` -------------------------------- ### Get Match Data for a League (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.league Fetches data for all fixtures played in a specific league and season. The output is a list of dictionaries, where each dictionary represents a match and its associated details. ```python match_data = LeagueEndpoint("La_Liga", session=requests.Session()).get_match_data(season="2023") # Access individual match details: match_data[0] ``` -------------------------------- ### Error Handling with Context Manager Source: https://collinb9.github.io/understatAPI/understatapi.api Illustrates how the context manager in UnderstatClient provides more verbose error handling. This example shows an AttributeError when trying to access a non-existent method. ```python team="" with UnderstatClient() as understat: understat.team(team).get_bad_data() ``` -------------------------------- ### Python: Fetch team match data and rosters Source: https://collinb9.github.io/understatAPI/index Shows how to retrieve match data for a specific team and season. It then demonstrates how to get the match ID from the first match and subsequently retrieve the roster data for that match. ```python from understatapi import UnderstatClient understat = UnderstatClient() # get data for every league match involving Manchester United in 2019/20 team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") # get the id for the first match of the season match_id = team_match_data[0]["id"] # get the rosters for the both teams in that match roster_data = understat.match(match=match_id).get_roster_data() ``` -------------------------------- ### Run understatapi tests locally Source: https://collinb9.github.io/understatAPI/index Installs necessary requirements and runs the project's test suite using a shell script. This is a crucial step for contributors to ensure their changes meet the project's quality standards before submitting a pull request. ```shell pip install -r requirements.txt pip install -r test_requirments.txt pip install -r docs_requirments.txt chmod +x ci/run_tests.sh ci/run_tests.sh ``` -------------------------------- ### League Endpoint Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Endpoint for league data. Use this function to get data from a url of the form `https://understat.com/league//` ```APIDOC ## League Endpoint ### Description Endpoint for league data. Use this function to get data from a url of the form `https://understat.com/league//` ### Method `league(league: PrimaryAttribute)` ### Endpoint Accessed via `understat.league(league)` ### Parameters #### Path Parameters - **league** (PrimaryAttribute) - Required - Name of the league(s) to get data for, one of {EPL, La_Liga, Bundesliga, Serie_A, Ligue_1, RFPL} ### Request Example ```python from understatapi import UnderstatClient leagues = ["EPL", "Bundesliga"] with UnderstatClient() as understat: for league in understat.league(leagues): print(league.league) ``` ### Response Returns a `LeagueEndpoint` object. #### Success Response (200) N/A (Method returns an endpoint object, actual data retrieval is handled by subsequent method calls on the endpoint) #### Response Example N/A ``` -------------------------------- ### Handling HTTP Requests with understatapi Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.base Shows the implementation of the _request_url method, which utilizes the requests module to send HTTP GET requests and verifies their success. It accepts arbitrary arguments and keyword arguments to pass directly to requests.get(). ```python def _request_url(self, *args, **kwargs): """ Use the requests module to send a HTTP request to a url, and check that this request worked. Parameters: args (Any): Arguments to pass to `requests.get()` kwargs (Any): Keyword arguments to pass to `requests.get()` Return type: Response """ pass ``` -------------------------------- ### Player Endpoint Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Endpoint for player data. Use this function to get data from a url of the form `https://understat.com/player//` ```APIDOC ## Player Endpoint ### Description Endpoint for player data. Use this function to get data from a url of the form `https://understat.com/player//` ### Method `player(player: PrimaryAttribute)` ### Endpoint Accessed via `understat.player(player)` ### Parameters #### Path Parameters - **player** (PrimaryAttribute) - Required - Id of the player(s) to get data for ### Request Example ```python from understatapi import UnderstatClient player_ids = ["000", "111"] with UnderstatClient() as understat: for player in understat.player(player_ids): print(player.player) ``` ### Response Returns a `PlayerEndpoint` object. #### Success Response (200) N/A (Method returns an endpoint object, actual data retrieval is handled by subsequent method calls on the endpoint) #### Response Example N/A ``` -------------------------------- ### Get Match Data by Match ID (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Retrieves match data from Understat.com using a given match ID or a list of IDs. This function is part of the UnderstatClient and returns a MatchEndpoint object, which can then be iterated to get individual match details. Ensure the UnderstatClient is properly initialized and closed. ```python from understatapi import UnderstatClient match_ids = ["123", "456"] with UnderstatClient() as understat: for match in understat.match(match_ids): print(match.match) ``` -------------------------------- ### Get Raw Match Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.match This function fetches raw data for a match. It can accept keyword arguments for customization, which are then passed to the AJAX request handler. ```python raw_data = MatchEndpoint.get_data(**kwargs) ``` -------------------------------- ### Get General Match Information Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.match This function retrieves general information pertaining to a match. It accepts keyword arguments that are forwarded to the base endpoint's request method. ```python match_info = MatchEndpoint.get_match_info(**kwargs) ``` -------------------------------- ### Player Endpoint Access (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Provides access to the PlayerEndpoint for fetching player-specific data. It accepts a player ID or a list of player IDs and returns a PlayerEndpoint object initialized with these IDs and the client's session. The example shows how to process multiple player IDs. ```python [docs] def player(self, player: PrimaryAttribute) -> PlayerEndpoint: """ Endpoint for player data. Use this function to get data from a url of the form ``https://understat.com/player//`` :param player: Id of the player(s) to get data for :rtype: :py:class:`~understatapi.endpoints.player.PlayerEndpoint` :Example: .. testsetup:: from understatapi import UnderstatClient .. doctest:: >>> player_ids = ["000", "111"] >>> with UnderstatClient() as understat: ... for player in understat.player(player_ids): ... print(player.player) 000 111 """ return PlayerEndpoint(player=player, session=self.session) ``` -------------------------------- ### Get Match Roster Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.match This function retrieves roster data for a given match. It takes arbitrary keyword arguments that are passed to the underlying request method. ```python roster_data = MatchEndpoint.get_roster_data(**kwargs) ``` -------------------------------- ### Get League-wide Data (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.league Fetches general league data for a specified season using the get_data method. This method retrieves aggregated data for teams, players, and matches within the league. ```python league_data = LeagueEndpoint("EPL", session=requests.Session()).get_data(season="2023") # Access data like: league_data['teams'], league_data['players'], league_data['dates'] ``` -------------------------------- ### League Endpoint Access (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Provides access to the LeagueEndpoint for fetching league-specific data. It expects a league name or a list of league names and returns a LeagueEndpoint object configured with the provided league(s) and the client's session. The example demonstrates iterating through multiple leagues. ```python [docs] def league(self, league: PrimaryAttribute) -> LeagueEndpoint: """ Endpoint for league data. Use this function to get data from a url of the form ``https://understat.com/league//`` :param league: Name of the league(s) to get data for, one of {EPL, La_Liga, Bundesliga, Serie_A, Ligue_1, RFPL} :rtype: :py:class:`~understatapi.endpoints.league.LeagueEndpoint` :Example: .. testsetup:: from understatapi import UnderstatClient .. doctest:: >>> leagues = ["EPL", "Bundesliga"] >>> with UnderstatClient() as understat: ... for league in understat.league(leagues): ... print(league.league) EPL Bundesliga """ return LeagueEndpoint(league=league, session=self.session) ``` -------------------------------- ### Get Class from Module Name (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/utils Dynamically retrieves a class object given its module name and class name. It utilizes `sys.modules` to access loaded modules and `getattr` to fetch the specified class. ```python [docs]def str_to_class(modulename: str, classname: str) -> type: """ Get a class by using its name """ return getattr(sys.modules[modulename], classname) ``` -------------------------------- ### Get Player Data for a League (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.league Retrieves statistics for all players participating in a given league and season. The result is a list of dictionaries, with each dictionary containing a player's performance data. ```python player_data = LeagueEndpoint("Serie_A", session=requests.Session()).get_player_data(season="2023") # Access specific player data: player_data[0]['player_name'] ``` -------------------------------- ### Get Team Data for a League (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.league Retrieves data for all teams within a given league and season. The returned data is a dictionary where keys represent teams and values contain their respective statistics. ```python team_data = LeagueEndpoint("Bundesliga", session=requests.Session()).get_team_data(season="2023") # Access specific team data: team_data['Bayern Munich'] ``` -------------------------------- ### Get Team Context Data (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.team Obtains context-based data for a team in a specified season via the understatapi.endpoints.team.TeamEndpoint.get_context_data method. This method requires a season string and can accept arbitrary keyword arguments for the request. ```python team_endpoint.get_context_data(season='2023') # Returns: Dict[str, Any] ``` -------------------------------- ### Get Team Overall Data (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.team Retrieves general data for a team on a per-season basis using the understatapi.endpoints.team.TeamEndpoint.get_data method. This method is essential for fetching team statistics and requires a season string, with support for additional keyword arguments. ```python team_endpoint.get_data(season='2023') # Returns: Dict[str, Any] ``` -------------------------------- ### Team Endpoint Access (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Provides access to the TeamEndpoint for fetching team-specific data. It accepts a team name or a list of team names and returns a TeamEndpoint object configured with these teams and the client's session. The example demonstrates fetching data for multiple teams. ```python [docs] def team(self, team: PrimaryAttribute) -> TeamEndpoint: """ Endpoint for team data. Use this function to get data from a url of the form ``https://understat.com/team//`` :param team: Name of the team(s) to get data for :rtype: :py:class:`~understatapi.endpoints.team.TeamEndpoint` :Example: .. testsetup:: from understatapi import UnderstatClient .. doctest:: >>> team_names = ["Manchester_United", "Liverpool"] >>> with UnderstatClient() as understat: ... for team in understat.team(team_names): ... print(team.team) Manchester_United Liverpool """ return TeamEndpoint(team=team, session=self.session) ``` -------------------------------- ### Get All Class Methods (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/utils Retrieves all function-based methods of a given class. It excludes methods decorated with decorators like @property or @classmethod. This is useful for understanding the full programmatic interface of a class. ```python """Helper functions for formatting data""" import sys from typing import List import inspect import re [docs]def get_all_methods(cls: type) -> List[str]: """ Get the names of all methods in a class, excluding methods decorated with ``@property``, ``@classmethod``, etc :param cls: The class to get the methods for :return: A list of the names of the methods """ return [meth[0] for meth in inspect.getmembers(cls, inspect.isfunction)] ``` -------------------------------- ### Get Team Match Data (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.team Retrieves match-level data for a specific team in a given season using the understatapi.endpoints.team.TeamEndpoint.get_match_data method. It requires a season string and optionally accepts keyword arguments for the underlying request. ```python team_endpoint.get_match_data(season='2023') # Returns: List[Dict[str, Any]] ``` -------------------------------- ### Get Public Class Methods (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/utils Extracts the names of all public methods from a class. Public methods are identified as those that do not start with an underscore. This function aids in identifying the intended API of a class. ```python [docs]def get_public_methods(cls: type) -> List[str]: """ Get the names of all public methods in a class :param cls: The class to get all public methods for :return: A list of the names of the public methods """ methods = get_all_methods(cls) methods = [meth for meth in methods if not meth.startswith("_")] return methods ``` -------------------------------- ### Initialize and Use UnderstatClient Source: https://collinb9.github.io/understatAPI/understatapi.api Demonstrates the basic usage of the UnderstatClient, including fetching league, player, team, and match data. It highlights the use of the context manager for session management. ```python from understatapi import UnderstatClient with UnderstatClient() as understat: league_player_data = understat.league(league="EPL").get_player_data(season="2019") player_shot_data = understat.player(player="2371").get_shot_data() team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") roster_data = understat.match(match="14711").get_roster_data() ``` -------------------------------- ### Base Endpoint Initialization and Attributes Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.base Demonstrates the initialization of the BaseEndpoint class and its key attributes like base_url and available leagues. The base_url is a constant string, while leagues is a list of supported league identifiers. ```python class BaseEndpoint: base_url = 'https://understat.com/' leagues = ['EPL', 'La_Liga', 'Bundesliga', 'Serie_A', 'Ligue_1', 'RFPL'] parser = BaseParser() def __init__(self, _primary_attr_, _session_): pass ``` -------------------------------- ### UnderstatClient Usage Source: https://collinb9.github.io/understatAPI/understatapi.api Demonstrates the basic usage of the UnderstatClient for fetching various types of data. ```APIDOC ## UnderstatClient ### Description API client for understat. The main interface for interacting with understatAPI. Exposes each of the entrypoints, maintains a consistent session and handles errors. ### Method Instantiate the client using a context manager. ### Endpoint N/A ### Parameters None ### Request Example ```python from understatapi import UnderstatClient with UnderstatClient() as understat: league_player_data = understat.league(league="EPL").get_player_data(season="2019") player_shot_data = understat.player(player="2371").get_shot_data() team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") roster_data = understat.match(match="14711").get_roster_data() ``` ### Response N/A ### Error Handling Example ```python >>> team="" >>> with UnderstatClient() as understat: ... understat.team(team).get_bad_data() Traceback (most recent call last): File "", line 2, in File "understatapi/api.py", line 59, in __exit__ raise AttributeError( AttributeError: 'TeamEndpoint' object has no attribute 'get_bad_data' Its public methods are ['get_context_data', 'get_match_data', 'get_player_data'] ``` ``` -------------------------------- ### UnderstatClient Initialization and Context Management Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Initializes the UnderstatClient with a requests session and implements context management protocols (__enter__ and __exit__) for session handling and error reporting. The __exit__ method specifically enhances AttributeError messages to include available public methods of the endpoint causing the error. ```python """understatAPI client""" from types import TracebackType import requests from .utils import get_public_methods, str_to_class, find_endpoints from .endpoints import ( LeagueEndpoint, PlayerEndpoint, TeamEndpoint, MatchEndpoint, ) from .exceptions import PrimaryAttribute [docs] class UnderstatClient: """#pylint: disable=line-too-long API client for understat The main interface for interacting with understatAPI. Exposes each of the entrypoints, maintains a consistent session and handles errors :Example: .. code-block:: from understatapi import UnderstatClient with UnderstatClient() as understat: league_player_data = understat.league(league="EPL").get_player_data(season="2019") player_shot_data = understat.player(player="2371").get_shot_data() team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") roster_data = understat.match(match="14711").get_roster_data() Using the context manager gives some more verbose error handling .. testsetup:: from understatapi import UnderstatClient .. doctest:: >>> team="" >>> with UnderstatClient() as understat: ... understat.team(team).get_bad_data() # doctest: +SKIP Traceback (most recent call last) File "", line 2, in File "understatapi/api.py", line 59, in __exit__ raise AttributeError( AttributeError: 'TeamEndpoint' object has no attribute 'get_bad_data' Its public methods are ['get_context_data', 'get_match_data', 'get_player_data'] """ def __init__(self) -> None: self.session = requests.Session() def __enter__(self) -> "UnderstatClient": return self def __exit__( self, exception_type: type, exception_value: BaseException, traceback: TracebackType, ) -> None: if exception_type is AttributeError: endpoint = find_endpoints(str(exception_value)) endpoint_obj = str_to_class(__name__, endpoint[0]) public_methods = get_public_methods(endpoint_obj) raise AttributeError( str(exception_value) + f"\nIts public methods are {public_methods}" ) self.session.close() ``` -------------------------------- ### Instantiate and Iterate LeagueEndpoint (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.league Demonstrates how to create a LeagueEndpoint object for one or more leagues and iterate through them to access league information. Requires the 'requests' library for session management. ```python import requests from understatapi.endpoints.league import LeagueEndpoint session = requests.Session() leagues = ["EPL", "Bundesliga"] for league in LeagueEndpoint(leagues, session=session): print(league.league) ``` -------------------------------- ### Team Endpoint Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Endpoint for team data. Use this function to get data from a url of the form `https://understat.com/team//` ```APIDOC ## Team Endpoint ### Description Endpoint for team data. Use this function to get data from a url of the form `https://understat.com/team//` ### Method `team(team: PrimaryAttribute)` ### Endpoint Accessed via `understat.team(team)` ### Parameters #### Path Parameters - **team** (PrimaryAttribute) - Required - Name of the team(s) to get data for ### Request Example ```python from understatapi import UnderstatClient team_names = ["Manchester_United", "Liverpool"] with UnderstatClient() as understat: for team in understat.team(team_names): print(team.team) ``` ### Response Returns a `TeamEndpoint` object. #### Success Response (200) N/A (Method returns an endpoint object, actual data retrieval is handled by subsequent method calls on the endpoint) #### Response Example N/A ``` -------------------------------- ### UnderstatClient Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api The main interface for interacting with understatAPI. Exposes each of the entrypoints, maintains a consistent session and handles errors. ```APIDOC ## UnderstatClient ### Description API client for understat. Exposes each of the entrypoints, maintains a consistent session and handles errors. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters None ### Request Example ```python from understatapi import UnderstatClient with UnderstatClient() as understat: league_player_data = understat.league(league="EPL").get_player_data(season="2019") player_shot_data = understat.player(player="2371").get_shot_data() team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") roster_data = understat.match(match="14711").get_roster_data() ``` ### Response N/A (Class definition) ### Error Handling Using the context manager provides verbose error handling. If an `AttributeError` occurs, it will detail the available public methods for the endpoint object. ``` -------------------------------- ### Python: Fetch Premier League player data Source: https://collinb9.github.io/understatAPI/index Demonstrates how to use the UnderstatClient to fetch player data for a specific league and season. It then shows how to extract a player's ID and name to fetch their shot data. ```python from understatapi import UnderstatClient understat = UnderstatClient() # get data for every player playing in the Premier League in 2019/20 league_player_data = understat.league(league="EPL").get_player_data(season="2019") # Get the name and id of one of the player player_id, player_name = league_player_data[0]["id"], league_player_data[0]["player_name"] # Get data for every shot this player has taken in a league match (for all seasons) player_shot_data = understat.player(player=player_id).get_shot_data() ``` -------------------------------- ### Get Match Shot Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.match This function retrieves shot-level data for a specific match. It accepts keyword arguments that are passed to the underlying request function. ```python shot_data = MatchEndpoint.get_shot_data(**kwargs) ``` -------------------------------- ### Instantiate and Iterate TeamEndpoint with requests Session (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.team Demonstrates how to instantiate the TeamEndpoint class with a list of team names and a requests session, and then iterate through the results to print team names. This is useful for fetching data for multiple teams concurrently. ```python import requests from understatapi.endpoints.team import TeamEndpoint session = requests.Session() team_names = ["Manchester_United", "Liverpool"] for team in TeamEndpoint(team_names, session=session): print(team.team) ``` -------------------------------- ### Python: Use UnderstatClient as a context manager Source: https://collinb9.github.io/understatAPI/index Illustrates using the UnderstatClient as a context manager. This approach automatically handles session closure and provides improved error handling, making it the recommended way to interact with the API. ```python from understatapi import UnderstatClient with UnderstatClient() as understat: team_match_data = understat.team(team="Manchester_United").get_match_data(season="2019") ``` -------------------------------- ### Get Player Match Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.player Fetches match-level data for a specific player. This method sends a request to an AJAX endpoint and returns a list of dictionaries, each representing a match. ```python player_endpoint.get_match_data() ``` -------------------------------- ### Get Player Shot Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.player Retrieves shot-level data for a player. This function queries an AJAX endpoint and returns a list of dictionaries, where each dictionary details a shot taken by the player. ```python player_endpoint.get_shot_data() ``` -------------------------------- ### Get Player General Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.player Retrieves general data for a player via an AJAX endpoint. The returned value is a dictionary containing keys such as 'player', 'matches', 'shots', and 'groups'. ```python player_endpoint.get_data() ``` -------------------------------- ### Match Endpoint Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Endpoint for match data. ```APIDOC ## Match Endpoint ### Description Endpoint for match data. ### Method `match(match: PrimaryAttribute)` ### Endpoint Accessed via `understat.match(match)` ### Parameters #### Path Parameters - **match** (PrimaryAttribute) - Required - Identifier for the match. ### Request Example ```python from understatapi import UnderstatClient with UnderstatClient() as understat: roster_data = understat.match(match="14711").get_roster_data() ``` ### Response Returns a `MatchEndpoint` object. #### Success Response (200) N/A (Method returns an endpoint object, actual data retrieval is handled by subsequent method calls on the endpoint) #### Response Example N/A ``` -------------------------------- ### Get Player Season Data Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.player Obtains season-level statistics for a player. The method calls an AJAX endpoint and returns a list of dictionaries, summarizing the player's performance over different seasons. ```python player_endpoint.get_season_data() ``` -------------------------------- ### Making AJAX Requests with understatapi Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.base Illustrates how to make an AJAX request to Understat's internal API using the _request_ajax method. This method handles necessary headers and returns parsed JSON data for dynamic content loading. ```python def _request_ajax(self, endpoint, **kwargs): """ Make an AJAX request to Understat’s internal API endpoints. Understat loads data dynamically via AJAX calls. This method handles the required headers and returns parsed JSON data. Parameters: endpoint (str): The AJAX endpoint path (e.g., ‘getLeagueData/EPL/2024’) kwargs (Any): Additional keyword arguments to pass to `requests.get()` Return type: Dict[str, Any] Returns: Parsed JSON response as a dictionary """ pass ``` -------------------------------- ### Retrieve Match Data using MatchEndpoint Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.match This snippet demonstrates how to use the MatchEndpoint class to fetch data for one or more matches. It requires a list of match IDs and a requests session. The endpoint iterates through the provided match IDs and prints the match ID for each. ```python import requests from understatapi.endpoints.match import MatchEndpoint session = requests.Session() match_ids = ["123", "456"] for match in MatchEndpoint(match_ids, session=session): print(match.match) ``` -------------------------------- ### League Endpoint Source: https://collinb9.github.io/understatAPI/understatapi.api Provides access to league data, typically from URLs like `https://understat.com/league//`. ```APIDOC ## GET /league ### Description Endpoint for league data. Use this function to get data from a url of the form `https://understat.com/league//`. ### Method GET ### Endpoint `/league` ### Parameters #### Query Parameters - **league** (Union[List[str], str]) - Required - Name of the league(s) to get data for, one of {EPL, La_Liga, Bundesliga, Serie_A, Ligue_1, RFPL} - **season** (str) - Required - The season for which to retrieve data (e.g., "2019"). ### Request Example ```python leagues = ["EPL", "Bundesliga"] with UnderstatClient() as understat: for league_data in understat.league(leagues).get_data(season="2020"): print(league_data['league']) ``` ### Response #### Success Response (200) - **league_data** (list) - A list of dictionaries, where each dictionary contains data for a specific league in the specified season. #### Response Example ```json [ { "league": "EPL", "season": "2020", "data": [...] }, { "league": "Bundesliga", "season": "2020", "data": [...] } ] ``` ``` -------------------------------- ### Match Endpoint Source: https://collinb9.github.io/understatAPI/understatapi.api Provides access to match data, typically from URLs like `https://understat.com/match/`. ```APIDOC ## GET /match ### Description Endpoint for match data. Use this function to get data from a url of the form `https://understat.com/match/`. ### Method GET ### Endpoint `/match` ### Parameters #### Query Parameters - **match** (Union[List[str], str]) - Required - Id of match(es) to get data for. ### Request Example ```python match_ids = ["123", "456"] with UnderstatClient() as understat: for match_data in understat.match(match_ids).get_data(): print(match_data['match']) ``` ### Response #### Success Response (200) - **match_data** (list) - A list of dictionaries, where each dictionary contains data for a specific match. #### Response Example ```json [ { "match": "123", "teams": {"home": "TeamA", "away": "TeamB"}, "score": "2-1", "stats": {...} }, { "match": "456", "teams": {"home": "TeamC", "away": "TeamD"}, "score": "0-0", "stats": {...} } ] ``` ``` -------------------------------- ### Base Endpoint Information Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.base Provides information about the BaseEndpoint class, including its attributes and available leagues. ```APIDOC ## Base Endpoint Class ### Description Represents the base endpoint for the Understat API, handling core request logic. ### Class `understatapi.endpoints.base.BaseEndpoint` ### Attributes - **base_url** (str) - The base URL for Understat API requests: `https://understat.com/` - **leagues** (List[str]) - A list of available leagues supported by the API: `EPL`, `La_Liga`, `Bundesliga`, `Serie_A`, `Ligue_1`, `RFPL` ### Methods - **__init__(_primary_attr_, _session_)** - Initializes the BaseEndpoint with a `requests.Session` object. - **_check_args(_league=None_, _season=None_)** - Handles validation of provided arguments. - **_request_url(*args, **kwargs)** - Sends an HTTP GET request to a specified URL and returns the response. - **_request_ajax(endpoint, **kwargs)** - Makes an AJAX request to Understat's internal API endpoints, handling necessary headers and returning parsed JSON data. - **endpoint** (str) - The AJAX endpoint path (e.g., 'getLeagueData/EPL/2024'). - **kwargs** (Any) - Additional keyword arguments for `requests.get()`. ### Response - **_request_ajax** returns `Dict[str, Any]` - Parsed JSON response as a dictionary. ``` -------------------------------- ### Retrieve Player Data using PlayerEndpoint Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.player Demonstrates how to use the PlayerEndpoint class to iterate through multiple player IDs and retrieve player information. Requires the 'requests' library and player IDs. ```python import requests from understatapi.endpoints.player import PlayerEndpoint session = requests.Session() player_ids = ["000", "111"] for player in PlayerEndpoint(player_ids, session=session): print(player.player) ``` -------------------------------- ### Player Endpoint Source: https://collinb9.github.io/understatAPI/understatapi.api Provides access to player data, typically from URLs like `https://understat.com/player//`. ```APIDOC ## GET /player ### Description Endpoint for player data. Use this function to get data from a url of the form `https://understat.com/player//`. ### Method GET ### Endpoint `/player` ### Parameters #### Query Parameters - **player** (Union[List[str], str]) - Required - Id of the player(s) to get data for. ### Request Example ```python player_ids = ["000", "111"] with UnderstatClient() as understat: for player_data in understat.player(player_ids).get_data(): print(player_data['player']) ``` ### Response #### Success Response (200) - **player_data** (list) - A list of dictionaries, where each dictionary contains data for a specific player. #### Response Example ```json [ { "player": "000", "stats": {...} }, { "player": "111", "stats": {...} } ] ``` ``` -------------------------------- ### Get Team Player Data (Python) Source: https://collinb9.github.io/understatAPI/understatapi.endpoints.team Fetches data for all players belonging to a specific team within a given season using the understatapi.endpoints.team.TeamEndpoint.get_player_data method. It takes a season string and supports additional keyword arguments for the request. ```python team_endpoint.get_player_data(season='2023') # Returns: List[Dict[str, Any]] ``` -------------------------------- ### Fetch Match Data Source: https://collinb9.github.io/understatAPI/understatapi.api Shows how to fetch data for one or more matches using their IDs. The match endpoint accepts a single match ID or a list of match IDs. ```python match_ids = ["123", "456"] with UnderstatClient() as understat: for match in understat.match(match_ids): print(match.match) ``` -------------------------------- ### UnderstatAPI Custom Exceptions Source: https://collinb9.github.io/understatAPI/understatapi.exceptions This section details the custom exceptions raised by the UnderstatAPI for various invalid input scenarios. ```APIDOC ## Custom Exceptions ### Description Defines custom exception classes to handle specific error conditions within the UnderstatAPI. ### Exceptions #### InvalidSeason - **Description**: Raised when an invalid season format or value is provided. - **Inherits from**: `Exception` #### InvalidPlayer - **Description**: Raised when an invalid player identifier or name is provided. - **Inherits from**: `Exception` #### InvalidLeague - **Description**: Raised when an invalid league identifier or name is provided. - **Inherits from**: `Exception` #### InvalidTeam - **Description**: Raised when an invalid team identifier or name is provided. - **Inherits from**: `Exception` #### InvalidMatch - **Description**: Raised when an invalid match identifier is provided. - **Inherits from**: `Exception` ``` -------------------------------- ### Player Endpoint API Source: https://collinb9.github.io/understatAPI/_modules/understatapi/endpoints/player This section details the functionalities of the Player Endpoint, including how to initialize it and retrieve various types of player data such as matches, shots, and season statistics. ```APIDOC ## Player Endpoint ### Description This endpoint provides access to player-specific data from the Understat website. It allows retrieval of match-level, shot-level, and season-level statistics for a given player. ### Class `PlayerEndpoint` ### Initialization To use this endpoint, you need to instantiate the `PlayerEndpoint` class with a player ID and a requests session. ```python from understatapi.endpoints import PlayerEndpoint import requests session = requests.Session() player_id = "" # Replace with the actual player ID player_endpoint = PlayerEndpoint(player_id, session=session) ``` ### Methods #### `_get_data(**kwargs)` ##### Description Retrieves raw data for a player from the Understat AJAX endpoint. This is an internal method used by other public methods. ##### Parameters - `**kwargs` (Any): Additional keyword arguments to pass to the `_request_ajax` method. ##### Returns - `Dict[str, Any]`: A dictionary containing player data, including keys like 'player', 'matches', 'shots', and 'groups'. ##### Raises - `TypeError`: If the 'player' attribute is not a string. - `InvalidPlayer`: If the provided player ID is invalid. #### `get_match_data(**kwargs)` ##### Description Fetches match-level data for the player. ##### Parameters - `**kwargs` (Any): Additional keyword arguments to pass to the `_request_ajax` method. ##### Returns - `List[Dict[str, Any]]`: A list of dictionaries, where each dictionary represents data for a single match the player participated in. #### `get_shot_data(**kwargs)` ##### Description Fetches shot-level data for the player. ##### Parameters - `**kwargs` (Any): Additional keyword arguments to pass to the `_request_ajax` method. ##### Returns - `List[Dict[str, Any]]`: A list of dictionaries, where each dictionary represents a shot taken by the player. #### `get_season_data(**kwargs)` ##### Description Fetches season-level data for the player. ##### Parameters - `**kwargs` (Any): Additional keyword arguments to pass to the `_request_ajax` method. ##### Returns - `List[Dict[str, Any]]`: A list of dictionaries, where each dictionary represents aggregated statistics for a season. ### Example Usage ```python import requests from understatapi.endpoints import PlayerEndpoint session = requests.Session() player_ids = ["604", "1112"] for player_id in player_ids: try: player_endpoint = PlayerEndpoint(player_id, session=session) # Get basic player info print(f"Player ID: {player_endpoint.player}") # Get match data matches = player_endpoint.get_match_data() print(f"Number of matches found: {len(matches)}") if matches: print(f"First match data: {matches[0]}") # Get shot data shots = player_endpoint.get_shot_data() print(f"Number of shots found: {len(shots)}") if shots: print(f"First shot data: {shots[0]}") # Get season data seasons = player_endpoint.get_season_data() print(f"Number of seasons found: {len(seasons)}") if seasons: print(f"First season data: {seasons[0]}") except Exception as e: print(f"Error processing player {player_id}: {e}") session.close() ``` ### Error Handling - `InvalidPlayer`: Raised when a provided player ID does not correspond to a valid player on Understat. - `TypeError`: Raised if the `player` parameter is not of the expected type (string). ``` -------------------------------- ### Fetch Player Data Source: https://collinb9.github.io/understatAPI/understatapi.api Demonstrates fetching data for one or more players using their IDs. The player endpoint accepts a single player ID or a list of player IDs. ```python player_ids = ["000", "111"] with UnderstatClient() as understat: for player in understat.player(player_ids): print(player.player) ``` -------------------------------- ### Python MatchEndpoint Class for UnderstatAPI Source: https://collinb9.github.io/understatAPI/_modules/understatapi/endpoints/match Defines the MatchEndpoint class for retrieving match data from Understat.com. It handles requests to the match data endpoint, parses the response, and provides methods to access specific data like shots, rosters, and match info. Requires `requests` library and custom `MatchParser`, `BaseEndpoint`, `PrimaryAttribute`, `InvalidMatch` classes. ```python """Match endpoint""" from typing import Dict, Any import requests from requests.exceptions import HTTPError from .base import BaseEndpoint from ..parsers import MatchParser from ..exceptions import InvalidMatch, PrimaryAttribute class MatchEndpoint(BaseEndpoint): """ Use this class to get data from a url of the form ``https://understat.com/match/`` :Example: .. testsetup:: import requests from understatapi.endpoints import MatchEndpoint .. testcleanup:: session.close() .. doctest:: >>> session = requests.Session() >>> match_ids = ["123", "456"] >>> for match in MatchEndpoint(match_ids, session=session): ... print(match.match) 123 456 """ parser = MatchParser() def __init__(self, match: PrimaryAttribute, session: requests.Session): """ :param match: Id of match(es) to get data for :param session: The current session """ self._primary_attr = match super().__init__(primary_attr=self._primary_attr, session=session) @property def match(self) -> PrimaryAttribute: """match id""" return self._primary_attr def _get_data(self, **kwargs: Any) -> Dict[str, Any]: """ Get data on a per-match basis via AJAX endpoint. :param kwargs: Keyword argument to pass to :meth:`understatapi.endpoints.base.BaseEndpoint._request_ajax` :return: Dictionary with keys: rosters, shots, tmpl """ if not isinstance(self.match, str): raise TypeError("``match`` must be a string") self._check_args() endpoint = f"getMatchData/{self.match}" try: return self._request_ajax(endpoint, **kwargs) except HTTPError as err: raise InvalidMatch( f"{self.match} is not a valid match", match=self.match ) from err def get_shot_data(self, **kwargs: Any) -> Dict[str, Any]: """ Get shot level data for a match :param kwargs: Keyword argument to pass to :meth:`understatapi.endpoints.base.BaseEndpoint._request_ajax` """ data = self._get_data(**kwargs) return data.get("shots", {}) def get_roster_data(self, **kwargs: Any) -> Dict[str, Any]: """ Get data about the roster for each team :param kwargs: Keyword argument to pass to :meth:`understatapi.endpoints.base.BaseEndpoint._request_ajax` """ data = self._get_data(**kwargs) return data.get("rosters", {}) def get_match_info(self, **kwargs: Any) -> Dict[str, Any]: """ Get information about the match :param kwargs: Keyword argument to pass to :meth:`understatapi.endpoints.base.BaseEndpoint._request_ajax` """ data = self._get_data(**kwargs) return data.get("tmpl", {}) ``` -------------------------------- ### Match Endpoint Access (Python) Source: https://collinb9.github.io/understatAPI/_modules/understatapi/api Provides access to the MatchEndpoint for fetching match-specific data. It expects a match ID or a list of match IDs and returns a MatchEndpoint object. This endpoint is used to retrieve data associated with specific football matches. ```python [docs] def match(self, match: PrimaryAttribute) -> MatchEndpoint: """ ```