Skip to content

Nfl

griddy / nfl**


Module Contents

Classes

BaseSDK

BaseSDK(
    sdk_config: SDKConfiguration,
    parent_ref: Optional[object] = None,
)
Source code in griddy/nfl/basesdk.py
def __init__(
    self,
    sdk_config: SDKConfiguration,
    parent_ref: Optional[object] = None,
) -> None:
    self.sdk_configuration = sdk_config
    self.parent_ref = parent_ref

Attributes

parent_ref class-attribute instance-attribute
parent_ref: Optional[object] = parent_ref

Reference to the root SDK instance, if any. This will prevent it from being garbage collected while there are active streams.

GriddyNFL

GriddyNFL(
    nfl_auth: Optional[Dict[str, Any]] = None,
    login_email: Optional[str] = None,
    login_password: Optional[str] = None,
    headless_login: Optional[bool] = False,
    server_idx: Optional[int] = None,
    server_url: Optional[str] = None,
    url_params: Optional[Dict[str, str]] = None,
    client: Optional[HttpClient] = None,
    async_client: Optional[AsyncHttpClient] = None,
    retry_config: OptionalNullable[RetryConfig] = UNSET,
    timeout_ms: Optional[int] = None,
    debug_logger: Optional[Logger] = None,
)

Bases: BaseSDK


              flowchart TD
              griddy.nfl.GriddyNFL[GriddyNFL]
              griddy.nfl.basesdk.BaseSDK[BaseSDK]

                              griddy.nfl.basesdk.BaseSDK --> griddy.nfl.GriddyNFL
                


              click griddy.nfl.GriddyNFL href "" "griddy.nfl.GriddyNFL"
              click griddy.nfl.basesdk.BaseSDK href "" "griddy.nfl.basesdk.BaseSDK"
            

Main client for accessing NFL data from multiple API endpoints.

GriddyNFL provides unified access to NFL data through three API categories:

  • Regular API: Public NFL.com endpoints for games, rosters, standings
  • Pro API: Advanced statistics, betting odds, player projections
  • Next Gen Stats: Player tracking data and advanced analytics

Sub-SDKs are loaded lazily on first access to minimize startup time.

ATTRIBUTE DESCRIPTION
authentication

Token generation and refresh operations.

TYPE: Authentication

combine

NFL Combine workout data and results.

TYPE: Combine

draft

NFL Draft picks and information.

TYPE: Draft

games

Game schedules, scores, and details.

TYPE: Games

rosters

Team rosters and player assignments.

TYPE: Rosters

standings

Division and conference standings.

TYPE: Standings

football_teams

Team information and details.

TYPE: Teams

venues

Stadium information.

TYPE: Venues

weeks

Season week information.

TYPE: Weeks

stats

Aggregated player/team statistics (passing, rushing, etc.).

TYPE: StatsSDK

betting

Betting odds and lines.

TYPE: Betting

content

Game previews and film cards.

TYPE: Content

players

Player information and projections.

TYPE: Players

pro_games

Advanced game data.

TYPE: ProGames

schedules

Matchup rankings and injury reports.

TYPE: Schedules

transactions

Player transactions.

TYPE: Transactions

teams

Pro team information.

TYPE: Teams

ngs

Next Gen Stats (tracking data, leaderboards, charts).

TYPE: NextGenStats

Example

from griddy.nfl import GriddyNFL

Initialize with auth token

nfl = GriddyNFL(nfl_auth={"accessToken": "your_token"})

Get games

games = nfl.games.get_games(season=2024, week=1)

Get Next Gen Stats

passing = nfl.ngs.stats.get_passing_stats(season=2024)

Use as context manager

with GriddyNFL(nfl_auth=auth) as nfl: ... games = nfl.games.get_games(season=2024)

Initialize the GriddyNFL client.

You must provide authentication either via a pre-obtained auth token (nfl_auth) or via email/password for browser-based authentication.

PARAMETER DESCRIPTION
nfl_auth

Dictionary containing authentication information, must include 'accessToken' key. Example:

TYPE: Optional[Dict[str, Any]] DEFAULT: None

login_email

Email address for NFL.com account. Used with login_password for browser-based authentication.

TYPE: Optional[str] DEFAULT: None

login_password

Password for NFL.com account.

TYPE: Optional[str] DEFAULT: None

headless_login

If True, run browser in headless mode during authentication. Defaults to False.

TYPE: Optional[bool] DEFAULT: False

server_idx

Index of the server to use from the server list.

TYPE: Optional[int] DEFAULT: None

server_url

Override the default server URL.

TYPE: Optional[str] DEFAULT: None

url_params

Parameters to template into the server URL.

TYPE: Optional[Dict[str, str]] DEFAULT: None

client

Custom synchronous HTTP client (must implement HttpClient).

TYPE: Optional[HttpClient] DEFAULT: None

async_client

Custom async HTTP client (must implement AsyncHttpClient).

TYPE: Optional[AsyncHttpClient] DEFAULT: None

retry_config

Configuration for automatic request retries.

TYPE: OptionalNullable[RetryConfig] DEFAULT: UNSET

timeout_ms

Request timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

debug_logger

Custom logger for debug output.

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION
ValueError

If neither nfl_auth nor email/password is provided, or if both are provided.

Example

With pre-obtained token

nfl = GriddyNFL(nfl_auth={"accessToken": "your_token"})

With email/password

nfl = GriddyNFL( ... login_email="user@example.com", ... login_password="password", ... headless_login=True, ... )

Source code in griddy/nfl/sdk.py
def __init__(
    self,
    nfl_auth: Optional[Dict[str, Any]] = None,
    login_email: Optional[str] = None,
    login_password: Optional[str] = None,
    headless_login: Optional[bool] = False,
    server_idx: Optional[int] = None,
    server_url: Optional[str] = None,
    url_params: Optional[Dict[str, str]] = None,
    client: Optional[HttpClient] = None,
    async_client: Optional[AsyncHttpClient] = None,
    retry_config: OptionalNullable[RetryConfig] = UNSET,
    timeout_ms: Optional[int] = None,
    debug_logger: Optional[Logger] = None,
) -> None:
    """Initialize the GriddyNFL client.

    You must provide authentication either via a pre-obtained auth token
    (nfl_auth) or via email/password for browser-based authentication.

    Args:
        nfl_auth: Dictionary containing authentication information,
            must include 'accessToken' key. Example:
            {"accessToken": "your_nfl_access_token"}
        login_email: Email address for NFL.com account. Used with
            login_password for browser-based authentication.
        login_password: Password for NFL.com account.
        headless_login: If True, run browser in headless mode during
            authentication. Defaults to False.
        server_idx: Index of the server to use from the server list.
        server_url: Override the default server URL.
        url_params: Parameters to template into the server URL.
        client: Custom synchronous HTTP client (must implement HttpClient).
        async_client: Custom async HTTP client (must implement AsyncHttpClient).
        retry_config: Configuration for automatic request retries.
        timeout_ms: Request timeout in milliseconds.
        debug_logger: Custom logger for debug output.

    Raises:
        ValueError: If neither nfl_auth nor email/password is provided,
            or if both are provided.

    Example:
        >>> # With pre-obtained token
        >>> nfl = GriddyNFL(nfl_auth={"accessToken": "your_token"})
        >>> # With email/password
        >>> nfl = GriddyNFL(
        ...     login_email="user@example.com",
        ...     login_password="password",
        ...     headless_login=True,
        ... )
    """
    client_supplied = True
    if client is None:
        client = httpx.Client(follow_redirects=True)
        client_supplied = False

    assert issubclass(
        type(client), HttpClient
    ), "The provided client must implement the HttpClient protocol."

    async_client_supplied = True
    if async_client is None:
        async_client = httpx.AsyncClient(follow_redirects=True)
        async_client_supplied = False

    if debug_logger is None:
        debug_logger = get_default_logger()

    assert issubclass(
        type(async_client), AsyncHttpClient
    ), "The provided async_client must implement the AsyncHttpClient protocol."

    auth_params_error = (
        "You must provide either nfl_auth, OR email/password combination."
    )
    if all([nfl_auth, login_email, login_password]):
        raise ValueError(auth_params_error)
    elif not any([nfl_auth, login_email, login_password]):
        raise ValueError(auth_params_error)

    if not nfl_auth:
        nfl_auth = do_browser_auth(
            email=login_email, password=login_password, headless=headless_login
        )

        print("Writing auth creds to file")
        with open("creds.json", "w") as outfile:
            json.dump(nfl_auth, outfile, indent=4)

    security = models.Security(nfl_auth=nfl_auth["accessToken"])

    if server_url is not None:
        if url_params is not None:
            server_url = utils.template_url(server_url, url_params)

    BaseSDK.__init__(
        self,
        SDKConfiguration(
            client=client,
            client_supplied=client_supplied,
            async_client=async_client,
            async_client_supplied=async_client_supplied,
            security=security,
            server_url=server_url,
            server_idx=server_idx,
            retry_config=retry_config,
            timeout_ms=timeout_ms,
            debug_logger=debug_logger,
            custom_auth_info=nfl_auth,
        ),
        parent_ref=self,
    )

    hooks = SDKHooks()

    # pylint: disable=protected-access
    self.sdk_configuration.__dict__["_hooks"] = hooks

    self.sdk_configuration = hooks.sdk_init(self.sdk_configuration)

    weakref.finalize(
        self,
        close_clients,
        cast(ClientOwner, self.sdk_configuration),
        self.sdk_configuration.client,
        self.sdk_configuration.client_supplied,
        self.sdk_configuration.async_client,
        self.sdk_configuration.async_client_supplied,
    )

Attributes

authentication instance-attribute
authentication: Authentication

Token generation and refresh operations for NFL API access.

combine instance-attribute
combine: Combine

NFL Combine workout data and results.

draft instance-attribute
draft: Draft

NFL Draft picks and information.

games instance-attribute
games: Games

Game schedules, scores, and details from the regular API.

rosters instance-attribute
rosters: Rosters

Team rosters and player assignments.

standings instance-attribute
standings: Standings

Division and conference standings.

football_teams instance-attribute
football_teams: Teams

Team information and details.

venues instance-attribute
venues: Venues

Stadium and venue information.

weeks instance-attribute
weeks: Weeks

Season week information.

stats instance-attribute
stats: StatsSDK

Aggregated player and team statistics (stats.passing, stats.rushing, etc.).

betting instance-attribute
betting: Betting

Betting odds and lines.

content instance-attribute
content: Content

Game previews, film cards, and insights.

players instance-attribute
players: Players

Player information, statistics, and projections.

pro_games instance-attribute
pro_games: ProGames

Advanced game data and statistics.

schedules instance-attribute
schedules: Schedules

Matchup rankings and injury reports.

transactions instance-attribute
transactions: Transactions

Player transactions and roster moves.

fantasy_statistics instance-attribute
fantasy_statistics: FantasyStatistics

Fantasy football statistics and scoring metrics.

teams instance-attribute
teams: Teams

Pro team information, rosters, and schedules.

ngs instance-attribute

Next Gen Stats data (tracking statistics, leaderboards, charts, highlights).

Functions

Functions

dynamic_import

dynamic_import(
    modname: str,
    package: str | None = None,
    retries: int = 3,
)

Dynamically import a module with retry logic for handling race conditions.

This function handles edge cases where parallel imports can cause KeyError due to half-initialized modules in sys.modules.

:param modname: The name of the module to import (absolute or relative) :param package: The package name for relative imports (e.g., package) :param retries: Number of retry attempts (default: 3) :returns: The imported module :raises KeyError: If import fails after all retries

Source code in griddy/nfl/_import.py
def dynamic_import(modname: str, package: str | None = None, retries: int = 3):
    """Dynamically import a module with retry logic for handling race conditions.

    This function handles edge cases where parallel imports can cause KeyError
    due to half-initialized modules in sys.modules.

    :param modname: The name of the module to import (absolute or relative)
    :param package: The package name for relative imports (e.g., __package__)
    :param retries: Number of retry attempts (default: 3)
    :returns: The imported module
    :raises KeyError: If import fails after all retries
    """
    for attempt in range(retries):
        try:
            return import_module(modname, package)
        except KeyError:
            # Clear any half-initialized module and retry
            sys.modules.pop(modname, None)
            if attempt == retries - 1:
                break
    raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")

close_clients

close_clients(
    owner: ClientOwner,
    sync_client: Union[HttpClient, None],
    sync_client_supplied: bool,
    async_client: Union[AsyncHttpClient, None],
    async_client_supplied: bool,
) -> None

A finalizer function that is meant to be used with weakref.finalize to close httpx clients used by an SDK so that underlying resources can be garbage collected.

Source code in griddy/nfl/httpclient.py
def close_clients(
    owner: ClientOwner,
    sync_client: Union[HttpClient, None],
    sync_client_supplied: bool,
    async_client: Union[AsyncHttpClient, None],
    async_client_supplied: bool,
) -> None:
    """
    A finalizer function that is meant to be used with weakref.finalize to close
    httpx clients used by an SDK so that underlying resources can be garbage
    collected.
    """

    # Unset the client/async_client properties so there are no more references
    # to them from the owning SDK instance and they can be reaped.
    owner.client = None
    owner.async_client = None
    if sync_client is not None and not sync_client_supplied:
        try:
            sync_client.close()
        except Exception:
            pass

    if async_client is not None and not async_client_supplied:
        try:
            loop = asyncio.get_running_loop()
            asyncio.run_coroutine_threadsafe(async_client.aclose(), loop)
        except RuntimeError:
            try:
                asyncio.run(async_client.aclose())
            except RuntimeError:
                # best effort
                pass