nhl-api-py

repository·main·Indexed 41 days ago

https://github.com/coreyjs/nhl-api-py

A Python wrapper for the NHL API (updated for 2025/2026) and EDGE Stats. It provides access to team information, schedules, standings, and player statistics via the NHLClient. The library includes a pythonic QueryBuilder for complex skater stats filtering and a dedicated edge module for advanced tracking data such as shot speed, skating speed, and zone time for players, goalies, and teams.

Tokens
24.1K
Snippets
79
Records
86
Agent score
100%

What's inside nhl-api-py

  1. Overview of API Modules

    main

    The library is organized into functional modules that map to NHL API endpoints:

    • teams: Team information, rosters, and franchise IDs.
    • schedule: Game schedules (daily, weekly, team-specific, playoffs).
    • stats: Player and team statistics (basic, summary, and advanced via Query Builder).
    • edge: EDGE-related data (shot speed, skate speed, etc.).
    • standings: Current and historical league standings.
    • game_center: Box scores, play-by-play, and game summaries.
    • players: Players by team and prospects.
    • misc: Glossary, configuration, and country info.
    • helpers: Experimental utilities for complex tasks (e.g., getting game IDs by season). Note: Helpers may perform many requests and include built-in sleeping to avoid rate limits; you can override this with sleep=False.
  2. Access the NHL EDGE Tracking module

    main

    The edge module provides access to NHL EDGE puck and player tracking data, including shot speed, skating speed, distance skated, zone time, and shot location analytics for skaters, goalies, and teams.

    Note: EDGE data is only available from the 2021-2022 season onward. Access the module via client.edge on an NHLClient instance.

    from nhlpy import NHLClient
    
    client = NHLClient()
    # Access the edge module
    edge_module = client.edge
  3. Game ID Format Reference

    main

    NHL Game IDs follow a specific structured format: YYYYTTNNNN.

    • YYYY: The season start year.
    • TT: The game type code:
      • 01: Preseason
      • 02: Regular Season
      • 03: Playoffs
    • NNNN: The sequential game number.

    Example: 2023020280 represents the 280th regular season game of the 2023 season.

  4. How the Helpers API Module works

    main

    The helpers module provides convenience methods that aggregate data from multiple NHL API calls into single results. You can access it via client.helpers on an NHLClient instance.

    Performance Warning: Every method in this module makes multiple API calls internally (typically 32, one per NHL team) with built-in sleep delays between requests to avoid rate limiting. These methods are significantly slower than individual API calls. Expect execution times of 30 seconds to several minutes depending on the method and sleep rate.

  5. Validate QueryContext and handle errors

    main

    When building a query, the QueryContext object tracks whether the provided filters are valid. If a filter is invalid (due to bad data or wrong options), it will be excluded from the final query, but the rest of the valid filters will still be processed.

    You can check for errors using:

    • query_context.is_valid(): Returns False if any filters failed validation.
    • query_context.errors: Contains the error details encountered during the build process.
    ... 
    query_context: QueryContext = query_builder.build(filters=filters)
    if not query_context.is_valid():
        print(f"Errors encountered: {query_context.errors}")
  6. Access the Misc API Module

    main

    The misc module provides utility and reference data endpoints for the NHL API. You can access it via the client.misc attribute on an NHLClient instance. It is used for retrieving glossary definitions, stats configuration, country lists, historical season rules, and draft information.

    from nhlpy import NHLClient
    
    client = NHLClient()
    # Access the misc module
    misc_module = client.misc
  7. Access the Stats API via NHLClient

    main

    The Stats module provides access to player statistics, team statistics, goalie statistics, and advanced query-based stat lookups. You can access this module through the .stats attribute on an instance of NHLClient.

    from nhlpy import NHLClient
    
    client = NHLClient()
    # Access stats via client.stats
    stats_module = client.stats
  8. Quick Start with NHLClient

    main

    To use the library, instantiate the NHLClient and access its sub-modules (like teams, standings, or schedule) to retrieve NHL data.

    from nhlpy import NHLClient
    
    # Basic usage
    client = NHLClient()
    
    # Get all teams
    teams = client.teams.teams()
    
    # Get current standings
    standings = client.standings.league_standings()
    
    # Get today's games
    games = client.schedule.daily_schedule()
  9. Use the QueryBuilder for skater stats

    main

    The QueryBuilder allows you to programmatically construct complex skater statistics queries using a list of filter objects. This abstraction simplifies interacting with the NHL API's skater stats endpoint.

    To use it, you create a list of filter instances (like GameTypeQuery, DraftQuery, etc.), pass them to QueryBuilder.build(), and then use the resulting QueryContext with the client.stats.skater_stats_with_query_context method.

    from nhlpy.api.query.builder import QueryBuilder, QueryContext
    from nhlpy.nhl_client import NHLClient
    from nhlpy.api.query.filters.draft import DraftQuery
    from nhlpy.api.query.filters.season import SeasonQuery
    from nhlpy.api.query.filters.game_type import GameTypeQuery
    from nhlpy.api.query.filters.position import PositionQuery, PositionTypes
    
    client = NHLClient(debug=True)
    
    filters = [
        GameTypeQuery(game_type="2"),
        DraftQuery(year="2020", draft_round="2"),
        SeasonQuery(season_start="20202021", season_end="20232024"),
        PositionQuery(position=PositionTypes.ALL_FORWARDS)
    ]
    
    query_builder = QueryBuilder()
    query_context: QueryContext = query_builder.build(filters=filters)
    
    data = client.stats.skater_stats_with_query_context(
        report_type='summary',
        query_context=query_context,
        aggregate=True
    )
  10. Configure NHLClient settings

    main

    When initializing NHLClient, you can pass several configuration options to control behavior such as logging, timeouts, and SSL verification.

    from nhlpy import NHLClient
    
    # All available configurations
    client = NHLClient(
        debug=True,           # Enable debug logging
        timeout=30,           # Request timeout in seconds
        ssl_verify=True,      # SSL certificate verification
        follow_redirects=True # Follow HTTP redirects
    )
  11. Apply granular filtering with fact_query

    main

    In addition to high-level filters, you can apply granular numeric constraints using the fact_query attribute on the QueryContext object. This maps to the factCayenneExp parameter in the API.

    Constraints can be combined using and and support operators >, <, >=, <=.

    Supported fields for fact_query: gamesPlayed, points, goals, pointsPerGame, penaltyMinutes, plusMinus, ppGoals, evGoals, evPoints, ppPoints, gameWinningGoals, otGoals, shPoints, shGoals, shootingPct, timeOnIcePerGame, faceoffWinPct, shots.

    query_builder = QueryBuilder()
    query_context: QueryContext = query_builder.build(filters=filters)
    
    # Example: filter for players with at least 1 game played and 10 goals
    query_context.fact_query = "gamesPlayed>=1 and goals>=10"
    
    data = client.stats.skater_stats_with_query_context(
        report_type='summary',
        query_context=query_context,
        aggregate=True
    )