Skip to main content

An asynchronous Python wrapper for the un-official NHL APIs.

Project description

NHL API Python Wrapper

An asynchronous Python wrapper for the official (but undocumented) NHL APIs: api-web.nhle.com and api.nhle.com/stats/rest.

Note: This library interacts with APIs that are not officially documented or supported by the NHL. Use at your own risk. API changes may break this library without notice.

Features

  • Async Python wrapper for both the NHL Web API (api-web.nhle.com) and Stats API (api.nhle.com/stats/rest).
  • Two main clients:
    • NHLWebClient: For web endpoints (players, teams, schedule, games, playoffs, drafts, misc, other web).
    • NHLStatsClient: For stats endpoints (players, teams, draft, season, game, misc).
  • Easy-to-use endpoint categories as attributes (e.g., client.players, client.teams).
  • Custom exception handling for API errors.

Installation

pip install git+https://github.com/brrainey13/nhl-api.git # Or clone and pip install .

Or for development:

git clone https://github.com/brrainey13/nhl-api.git
cd nhl-api
pip install -e .

Basic Usage (api-web.nhle.com)

import asyncio
from nhl_api import NHLWebClient
from nhl_api.exceptions import NHLAPIError

async def main():
    async with NHLWebClient() as client:
        try:
            # Get player landing info (Auston Matthews)
            player_info = await client.players.get_landing(player_id=8477934)
            print(f"Player: {player_info['firstName']['default']} {player_info['lastName']['default']}")
            print(f"Team: {player_info['currentTeamAbbrev']}")
            print(f"Position: {player_info['position']}")

            # Get today's standings
            standings = await client.teams.get_standings_now()
            print(f"\nStandings Date: {standings['standingsDate']}")

            # Get game log for Connor McDavid, 2023-2024 Regular Season
            game_log = await client.players.get_game_log(
                player_id=8478402,
                season=20232024,
                game_type=2 # 2=Regular Season, 3=Playoffs
            )
            print(f"\nMcDavid Game Log (First 5 Games):")
            for game in game_log['gameLog'][:5]:
                print(f"  Date: {game['gameDate']}, Opp: {game['opponentAbbrev']}, G: {game['goals']}, A: {game['assists']}")

            # Get schedule for a specific date
            schedule = await client.schedule.get_schedule_by_date(date="2023-11-10")
            print(f"\nSchedule for 2023-11-10:")
            for date_info in schedule['gameWeek']:
                if date_info['date'] == "2023-11-10":
                    for game in date_info['games']:
                        print(f"  {game['awayTeam']['abbrev']} @ {game['homeTeam']['abbrev']} ({game['gameTypeDescription']}) - State: {game['gameState']}")
        except NHLAPIError as e:
            print(f"API Error: Status={e.status_code}, Message={e.message}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(main())

## Basic Usage (api.nhle.com/stats/rest)

```python
import asyncio
from nhl_api import NHLStatsClient

async def main():
    async with NHLStatsClient() as stats_client:
        # Get skater points leaders
        leaders = await stats_client.players.get_skater_leaders("points")
        print("Top points leader:", leaders['data'][0]['player']['fullName'])

        # Get team stats
        team_stats = await stats_client.teams.get_team_stats(team_id=10)
        print("Team stats:", team_stats)

if __name__ == "__main__":
    asyncio.run(main())

## Endpoint Categories

**NHLWebClient**
- `players`: Player info, stats, game logs, bios, etc.
- `teams`: Team info, rosters, standings.
- `schedule`: Schedules, calendar.
- `game`: Game scores, events, boxscores.
- `playoff`: Playoff info.
- `draft`: Draft info.
- `misc`: Miscellaneous endpoints.
- `other_web`: Other endpoints (season, where to watch, odds, etc.)

**NHLStatsClient**
- `players`: Stats leaders, skater/goalie stats, bios.
- `teams`: Team stats, franchise info.
- `draft`: Draft picks, history.
- `season`: Season info.
- `game`: Game stats, summaries.
- `misc`: Miscellaneous endpoints.

## Error Handling

All API errors raise `NHLAPIError` or a subclass. Example:

```python
from nhl_api.exceptions import NHLAPIError
try:
    ... # API call
except NHLAPIError as e:
    print(f"API Error: Status={e.status_code}, Message={e.message}")

Requirements

  • Python 3.8+
  • httpx (see requirements-dev.txt for dev dependencies)

Further Documentation

  • See nhl_api.md for detailed endpoint and usage documentation.
  • The code is documented with docstrings.

Contributing

Pull requests and issues are welcome! Please open an issue for bugs or feature requests.


Disclaimer: This project is not affiliated with or endorsed by the NHL. The APIs are undocumented and may change or break without notice.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nhlapi_tools-0.1.1.tar.gz (15.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nhlapi_tools-0.1.1-py3-none-any.whl (19.7 kB view details)

Uploaded Python 3

File details

Details for the file nhlapi_tools-0.1.1.tar.gz.

File metadata

  • Download URL: nhlapi_tools-0.1.1.tar.gz
  • Upload date:
  • Size: 15.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for nhlapi_tools-0.1.1.tar.gz
Algorithm Hash digest
SHA256 aafa4ffeb82d805a5e0e32f1b653de885599346a9f4166e2076eb955a795217f
MD5 48d89d8710bf79009fc1fdf360d57839
BLAKE2b-256 0c87aa014f8e7947140d681291e078892f7bd2b449544620bfc1681bf3b77e55

See more details on using hashes here.

File details

Details for the file nhlapi_tools-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: nhlapi_tools-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for nhlapi_tools-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4ff3790550e885e8fadd102af5f1a5f2071991cf1345f7fbfb52b08bc52f1404
MD5 edd24069e207a0dc6e9d836f16498167
BLAKE2b-256 02ae8dd7ad582f66fd5ed2643c4c251487297b87adad56614aa17c6ff9213da7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page