├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ └── python-app.yml
├── .gitignore
├── .python-version
├── CONTRIBUTING.md
├── README.md
├── license.md
├── nhl_api_2_3_0.json
├── nhlpy
├── __init__.py
├── api
│ ├── __init__.py
│ ├── game_center.py
│ ├── helpers.py
│ ├── misc.py
│ ├── playoffs.py
│ ├── query
│ │ ├── __init__.py
│ │ ├── builder.py
│ │ ├── filters
│ │ │ ├── __init__.py
│ │ │ ├── decision.py
│ │ │ ├── draft.py
│ │ │ ├── experience.py
│ │ │ ├── franchise.py
│ │ │ ├── game_type.py
│ │ │ ├── home_road.py
│ │ │ ├── nationality.py
│ │ │ ├── opponent.py
│ │ │ ├── position.py
│ │ │ ├── season.py
│ │ │ ├── shoot_catch.py
│ │ │ └── status.py
│ │ └── sorting
│ │ │ ├── __init__.py
│ │ │ └── sorting_options.py
│ ├── schedule.py
│ ├── standings.py
│ ├── stats.py
│ └── teams.py
├── config.py
├── data
│ ├── seasonal_information_manifest.json
│ ├── team_stat_ids.json
│ └── teams_20232024.json
├── http_client.py
└── nhl_client.py
├── poetry.lock
├── pyproject.toml
└── tests
├── __init__.py
├── conftest.py
├── query
├── __init__.py
├── filters
│ ├── test_decision.py
│ ├── test_draft.py
│ ├── test_experience.py
│ ├── test_franchise.py
│ ├── test_game_type.py
│ ├── test_home_road.py
│ ├── test_nationality.py
│ ├── test_position.py
│ ├── test_season.py
│ ├── test_shoot_catch.py
│ └── test_status.py
└── test_builder.py
├── test_game_center.py
├── test_nhl_client.py
├── test_playoffs.py
├── test_schedule.py
├── test_standings.py
├── test_stats.py
└── test_teams.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: coreyjs
14 | thanks_dev: # Replace with a single thanks.dev username
15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
16 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/python-app.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
3 |
4 | name: NHL-API-PY
5 |
6 | on:
7 | push:
8 | branches: [ "main" ]
9 | pull_request:
10 | branches: [ "main" ]
11 |
12 | permissions:
13 | contents: read
14 |
15 | jobs:
16 | test-ruff-black:
17 | runs-on: ubuntu-latest
18 | steps:
19 | - uses: actions/checkout@v4
20 |
21 | # If you wanted to use multiple Python versions, you'd have specify a matrix in the job and
22 | # reference the matrixe python version here.
23 | - uses: actions/setup-python@v5
24 | with:
25 | python-version: 3.9.18
26 |
27 | # Cache the installation of Poetry itself, e.g. the next step. This prevents the workflow
28 | # from installing Poetry every time, which can be slow. Note the use of the Poetry version
29 | # number in the cache key, and the "-0" suffix: this allows you to invalidate the cache
30 | # manually if/when you want to upgrade Poetry, or if something goes wrong. This could be
31 | # mildly cleaner by using an environment variable, but I don't really care.
32 | - name: cache poetry install
33 | uses: actions/cache@v4
34 | with:
35 | path: ~/.local
36 | key: poetry-1.5.1-0
37 |
38 | # Install Poetry. You could do this manually, or there are several actions that do this.
39 | # `snok/install-poetry` seems to be minimal yet complete, and really just calls out to
40 | # Poetry's default install script, which feels correct. I pin the Poetry version here
41 | # because Poetry does occasionally change APIs between versions and I don't want my
42 | # actions to break if it does.
43 | #
44 | # The key configuration value here is `virtualenvs-in-project: true`: this creates the
45 | # venv as a `.venv` in your testing directory, which allows the next step to easily
46 | # cache it.
47 | - uses: snok/install-poetry@v1
48 | with:
49 | version: 1.5.1
50 | virtualenvs-create: true
51 | virtualenvs-in-project: true
52 |
53 | # Cache your dependencies (i.e. all the stuff in your `pyproject.toml`). Note the cache
54 | # key: if you're using multiple Python versions, or multiple OSes, you'd need to include
55 | # them in the cache key. I'm not, so it can be simple and just depend on the poetry.lock.
56 | - name: cache deps
57 | id: cache-deps
58 | uses: actions/cache@v3
59 | with:
60 | path: .venv
61 | key: pydeps-${{ hashFiles('**/poetry.lock') }}
62 |
63 | # Install dependencies. `--no-root` means "install all dependencies but not the project
64 | # itself", which is what you want to avoid caching _your_ code. The `if` statement
65 | # ensures this only runs on a cache miss.
66 | - run: poetry install --no-interaction --no-root
67 | if: steps.cache-deps.outputs.cache-hit != 'true'
68 |
69 | # Now install _your_ project. This isn't necessary for many types of projects -- particularly
70 | # things like Django apps don't need this. But it's a good idea since it fully-exercises the
71 | # pyproject.toml and makes that if you add things like console-scripts at some point that
72 | # they'll be installed and working.
73 | - run: poetry install --no-interaction
74 |
75 | # And finally run tests. I'm using pytest and all my pytest config is in my `pyproject.toml`
76 | # so this line is super-simple. But it could be as complex as you need.
77 | - run: poetry run pytest
78 |
79 | # run a check for black
80 | - name: poetry run black . --check
81 | run: poetry run black . --check
82 |
83 | # run a lint check with ruff
84 | - name: poetry run ruff check
85 | run: poetry run ruff check .
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .ipynb_checkpoints
3 | .mypy_cache
4 | .vscode
5 | __pycache__
6 | .pytest_cache
7 | htmlcov
8 | dist
9 | site
10 | .coverage
11 | coverage.xml
12 | .netlify
13 | test.db
14 | log.txt
15 | Pipfile.lock
16 | env3.*
17 | env
18 | docs_build
19 | venv
20 | docs.zip
21 | archive.zip
22 |
23 | # vim temporary files
24 | *~
25 | .*.sw?
26 |
27 | */.DS_Store
--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------
1 | 3.9.18
2 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to nhl-api-py
2 |
3 | Thank you for considering contributing to nhl-api-py! We appreciate your time and effort in helping us improve the package. The following guidelines will help you understand how to contribute effectively.
4 |
5 | ## How to Contribute
6 |
7 | 1. Fork the repository and create a new branch for your contributions.
8 | 2. Make your changes, enhancements, or bug fixes in the new branch.
9 | 3. Test your changes locally to ensure they are functioning as expected.
10 | 4. Commit your changes with clear and descriptive messages.
11 | 5. Push your changes to your forked repository.
12 | 6. Create a pull request (PR) from your branch to the main repository.
13 |
14 | ## Guidelines for Contributions
15 |
16 | - Before starting any significant work, please open an issue or join an existing discussion to ensure that your contribution aligns with the project's goals and avoids duplication of effort.
17 | - Follow the Python style guide (PEP 8) when writing or modifying code. Maintain consistent code formatting and ensure your changes pass the linting checks.
18 | - Include unit tests to validate the changes you've made. Ensure that all existing tests pass successfully.
19 | - Document any new features, modifications, or bug fixes using the appropriate format in the code and/or in the project's documentation.
20 | - Be responsive to any feedback or comments on your pull request and make necessary updates as requested.
21 | - Respect the code of conduct. Be considerate, inclusive, and respectful in all interactions and communications.
22 |
23 | ## Issue Reporting
24 |
25 | If you encounter any issues, bugs, or have suggestions for improvements, please open a GitHub issue. When reporting an issue, provide as much relevant information as possible, including the steps to reproduce the problem.
26 |
27 | ## Feature Requests
28 |
29 | If you have ideas for new features or enhancements, we encourage you to open an issue on GitHub. Explain your feature request in detail, including its purpose and potential benefits.
30 |
31 | ## Code of Conduct
32 |
33 | By participating in this project, you are expected to adhere to the project's [Code of Conduct](CODE_OF_CONDUCT.md). Please familiarize yourself with it and ensure that all interactions are respectful and inclusive.
34 |
35 | ## Licensing
36 |
37 | Contributions to nhl-api-py are subject to the same license as the main repository. By contributing code, you agree to license your contributions under the project's existing license.
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://badge.fury.io/py/nhl-api-py)
2 | 
3 |
4 | # NHL API & NHL Edge Stats
5 |
6 |
7 | ## About
8 |
9 | NHL-api-py is a Python package that provides a simple wrapper around the
10 | NHL API, allowing you to easily access and retrieve NHL data in your Python
11 | applications.
12 |
13 |
14 | Note: I created this to help me with some machine learning
15 | projects around the NHL and the NHL data sets. Special thanks to https://github.com/erunion/sport-api-specifications/tree/master/nhl,
16 | https://gitlab.com/dword4/nhlapi/-/blob/master/stats-api.md and https://github.com/Zmalski/NHL-API-Reference.
17 |
18 |
19 | ### Developer Note: This is being updated with the new, also undocumented, NHL API.
20 |
21 | As of 10/5/24 I seem to have a majority of the endpoints added from what I can tell, but every once and awhile I come across one that needs to be added/changed. These will most likely be a minor ver bump.
22 |
23 | If you find any, open a ticket or post in the discussions tab. I would love to hear more.
24 |
25 |
26 | ---
27 | # Contact
28 |
29 | Im available on [Bluesky](https://bsky.app/profile/coreyjs.dev) for any questions or just general chats about enhancements.
30 |
31 | ---
32 |
33 | # Wiki
34 |
35 | More in depth examples can be found in the wiki, feel free to add more: [Examples](https://github.com/coreyjs/nhl-api-py/wiki/Example-Use-Cases)
36 |
37 | ---
38 |
39 | # Usage
40 |
41 | ```bash
42 | pip install nhl-api-py
43 | ```
44 |
45 | ```python
46 | from nhlpy import NHLClient
47 |
48 | client = NHLClient()
49 | # Fore more verbose logging
50 | client = NHLClient(verbose=True)
51 | # OR Other available configurations:
52 | client = NHLClient(verbose={bool}, timeout={int}, ssl_verify={bool}, follow_redirects={bool})
53 | ```
54 | ---
55 | ## Stats with QueryBuilder
56 |
57 | The skater stats endpoint can be accessed using the new query builder. It should make
58 | creating and understanding the queries a bit easier. Filters are being added as I go, and will match up
59 | to what the NHL API will allow.
60 |
61 | The idea is to easily, and programatically, build up more complex queries using the query filters. A quick example below:
62 | ```python
63 | filters = [
64 | GameTypeQuery(game_type="2"),
65 | DraftQuery(year="2020", draft_round="2"),
66 | SeasonQuery(season_start="20202021", season_end="20232024"),
67 | PositionQuery(position=PositionTypes.ALL_FORWARDS)
68 | ]
69 | ```
70 |
71 |
72 |
73 | ### Sorting
74 | The sorting is a list of dictionaries similar to below. You can supply your own, otherwise it will
75 | default to the default sort properties that the stat dashboard uses. All sorting defaults are found
76 | in the `nhl-api-py/nhlpy/api/query/sorting/sorting_options.py` file.
77 |
78 |
79 | Default Sorting
80 |
81 | ```python
82 | skater_summary_default_sorting = [
83 | {"property": "points", "direction": "DESC"},
84 | {"property": "gamesPlayed", "direction": "ASC"},
85 | {"property": "playerId", "direction": "ASC"},
86 | ]
87 | ```
88 |
89 |
90 | ---
91 |
92 | ### Report Types
93 | The following report types are available. These are used to build the request url. So `/summary`, `/bios`, etc.
94 |
95 | ```bash
96 | summary
97 | bios
98 | faceoffpercentages
99 | faceoffwins
100 | goalsForAgainst
101 | realtime
102 | penalties
103 | penaltykill
104 | penaltyShots
105 | powerplay
106 | puckPossessions
107 | summaryshooting
108 | percentages
109 | scoringRates
110 | scoringpergame
111 | shootout
112 | shottype
113 | timeonice
114 | ```
115 |
116 | ### Available Filters
117 |
118 | ```python
119 | from nhlpy.api.query.filters.franchise import FranchiseQuery
120 | from nhlpy.api.query.filters.shoot_catch import ShootCatchesQuery
121 | from nhlpy.api.query.filters.draft import DraftQuery
122 | from nhlpy.api.query.filters.season import SeasonQuery
123 | from nhlpy.api.query.filters.game_type import GameTypeQuery
124 | from nhlpy.api.query.filters.position import PositionQuery, PositionTypes
125 | from nhlpy.api.query.filters.status import StatusQuery
126 | from nhlpy.api.query.filters.opponent import OpponentQuery
127 | from nhlpy.api.query.filters.home_road import HomeRoadQuery
128 | from nhlpy.api.query.filters.experience import ExperienceQuery
129 | from nhlpy.api.query.filters.decision import DecisionQuery
130 |
131 | filters = [
132 | GameTypeQuery(game_type="2"),
133 | DraftQuery(year="2020", draft_round="2"),
134 | SeasonQuery(season_start="20202021", season_end="20232024"),
135 | PositionQuery(position=PositionTypes.ALL_FORWARDS),
136 | ShootCatchesQuery(shoot_catch="L"),
137 | HomeRoadQuery(home_road="H"),
138 | FranchiseQuery(franchise_id="1"),
139 | StatusQuery(is_active=True),#for active players OR for HOF players StatusQuery(is_hall_of_fame=True),
140 | OpponentQuery(opponent_franchise_id="2"),
141 | ExperienceQuery(is_rookie=True), # for rookies || ExperienceQuery(is_rookie=False) #for veteran
142 | DecisionQuery(decision="W") # OR DecisionQuery(decision="L") OR DecisionQuery(decision="O")
143 | ]
144 | ```
145 |
146 |
147 | ### Example
148 | ```python
149 | from nhlpy.api.query.builder import QueryBuilder, QueryContext
150 | from nhlpy.nhl_client import NHLClient
151 | from nhlpy.api.query.filters.draft import DraftQuery
152 | from nhlpy.api.query.filters.season import SeasonQuery
153 | from nhlpy.api.query.filters.game_type import GameTypeQuery
154 | from nhlpy.api.query.filters.position import PositionQuery, PositionTypes
155 |
156 | client = NHLClient(verbose=True)
157 |
158 | filters = [
159 | GameTypeQuery(game_type="2"),
160 | DraftQuery(year="2020", draft_round="2"),
161 | SeasonQuery(season_start="20202021", season_end="20232024"),
162 | PositionQuery(position=PositionTypes.ALL_FORWARDS)
163 | ]
164 |
165 | query_builder = QueryBuilder()
166 | query_context: QueryContext = query_builder.build(filters=filters)
167 |
168 | data = client.stats.skater_stats_with_query_context(
169 | report_type='summary',
170 | query_context=query_context,
171 | aggregate=True
172 | )
173 | ```
174 |
175 | ### Granular Filtering
176 | Each API request uses an additional query parameter called `factCayenneExp`. This defaults to `gamesPlayed>=1`
177 | but can be overridden by setting the `fact_query` parameter in the `QueryContextObject` object. These can
178 | be combined together with `and` to create a more complex query. It supports `>`, `<`, `>=`, `<=`. For example: `shootingPct>=0.01 and timeOnIcePerGame>=60 and faceoffWinPct>=0.01 and shots>=1`
179 |
180 |
181 | This should support the following filters:
182 |
183 | - `gamesPlayed`
184 | - `points`
185 | - `goals`
186 | - `pointsPerGame`
187 | - `penaltyMinutes`
188 | - `plusMinus`
189 | - `ppGoals` # power play goals
190 | - `evGoals` # even strength goals
191 | - `pointsPerGame`
192 | - `penaltyMinutes`
193 | - `evPoints` # even strength points
194 | - `ppPoints` # power play points
195 | - `gameWinningGoals`
196 | - `otGoals`
197 | - `shPoints` # short handed points
198 | - `shGoals` # short handed goals
199 | - `shootingPct`
200 | - `timeOnIcePerGame`
201 | - `faceoffWinPct`
202 | - `shots`
203 |
204 | ```python
205 | .....
206 | query_builder = QueryBuilder()
207 | query_context: QueryContext = query_builder.build(filters=filters)
208 |
209 | query_context.fact_query = "gamesPlayed>=1 and goals>=10" # defaults to gamesPlayed>=1
210 |
211 | data = client.stats.skater_stats_with_query_context(
212 | report_type='summary',
213 | query_context=query_context,
214 | aggregate=True
215 | )
216 | ```
217 |
218 |
219 | ### Invalid Query / Errors
220 |
221 | The `QueryContext` object will hold the result of the built query with the supplied queries.
222 | In the event of an invalid query (bad data, wrong option, etc), the `QueryContext` object will
223 | hold all the errors that were encountered during the build process. This should help in debugging.
224 |
225 | You can quickly check the `QueryContext` object for errors by calling `query_context.is_valid()`. Any "invalid" filters
226 | will be removed from the output query, but anything that is still valid will be included.
227 |
228 | ```python
229 | ...
230 | query_context: QueryContext = query_builder.build(filters=filters)
231 | query_context.is_valid() # False if any of the filters fails its validation check
232 | query_context.errors
233 | ```
234 |
235 | ---
236 |
237 | ## Additional Stats Endpoints (In development)
238 |
239 | ```python
240 |
241 | client.stats.gametypes_per_season_directory_by_team(team_abbr="BUF") # kinda weird endpoint.
242 |
243 | client.stats.player_career_stats(player_id="8478402")
244 |
245 | client.stats.player_game_log(player_id="8478402", season_id="20242025", game_type="2")
246 |
247 | # Team Summary Stats.
248 | # These have lots of available parameters. You can also tap into the apache cayenne expressions to build custom
249 | # queries, if you have that knowledge.
250 | client.stats.team_summary(start_season="20202021", end_season="20212022", game_type_id=2)
251 | client.stats.team_summary(start_season="20202021", end_season="20212022")
252 |
253 |
254 | # Skater Summary Stats.
255 | # Queries for skaters for year ranges, filterable down by franchise.
256 | client.stats.skater_stats_summary_simple(start_season="20232024", end_season="20232024")
257 | client.stats.skater_stats_summary_simple(franchise_id=10, start_season="20232024", end_season="20232024")
258 |
259 | # For the following query context endpoints, see the above section
260 | client.stats.skater_stats_with_query_context(...)
261 |
262 | # Goalies
263 | client.stats.goalie_stats_summary_simple(start_season="20242025", stats_type="summary")
264 |
265 | ```
266 | ---
267 |
268 |
269 | ## Schedule Endpoints
270 |
271 | ```python
272 |
273 | # Returns the games for the given date.
274 | client.schedule.get_schedule(date="2021-01-13")
275 |
276 | # Return games for the week of (date)
277 | client.schedule.get_weekly_schedule(date="2021-01-13")
278 |
279 | client.schedule.get_schedule_by_team_by_month(team_abbr="BUF")
280 | client.schedule.get_schedule_by_team_by_month(team_abbr="BUF", month="2021-01")
281 |
282 | client.schedule.get_schedule_by_team_by_week(team_abbr="BUF")
283 | client.schedule.get_schedule_by_team_by_week(team_abbr="BUF", date="2024-01-01")
284 |
285 | client.schedule.get_season_schedule(team_abbr="BUF", season="20212022")
286 |
287 | client.schedule.schedule_calendar(date="2023-11-23")
288 | ```
289 |
290 | ---
291 |
292 | ## Standings Endpoints
293 |
294 | ```python
295 | client.standings.get_standings()
296 | client.standings.get_standings(date="2021-01-13")
297 | client.standings.get_standings(season="20222023")
298 |
299 | # standings manifest. This returns a ton of information for every season ever it seems like
300 | # This calls the API for this info, I also cache this in /data/seasonal_information_manifest.json
301 | # for less API calls since this only changes yearly.
302 | client.standings.season_standing_manifest()
303 | ```
304 | ---
305 |
306 | ## Teams Endpoints
307 |
308 | ```python
309 | client.teams.teams_info() # returns id + abbrevation + name of all teams
310 | ```
311 |
312 | ---
313 |
314 | ## Game Center
315 | ```python
316 | client.game_center.boxscore(game_id="2023020280")
317 |
318 | client.game_center.play_by_play(game_id="2023020280")
319 |
320 | client.game_center.landing(game_id="2023020280")
321 |
322 | client.game_center.score_now()
323 |
324 | # this is used via the website to provide additional related game information
325 | client.game_center.right_rail(game_id="2023020280")
326 | ```
327 |
328 |
329 | ---
330 |
331 | ## Helpers
332 |
333 | These are expieremental and often times make many requests, can return DFs or do calculations. Stuff I find myself doing over and over I tend to move into helpers for convience.
334 |
335 | ```python
336 | # Game types 1=preseason, 2=regular season, 3 playoffs
337 | client.helpers.get_gameids_by_season("20242025", game_types=[2])
338 | ```
339 |
340 |
341 | ---
342 |
343 | ## Misc Endpoints
344 | ```python
345 | client.misc.glossary()
346 |
347 | client.misc.config()
348 |
349 | client.misc.countries()
350 |
351 | client.misc.season_specific_rules_and_info()
352 |
353 | client.misc.draft_year_and_rounds()
354 | ```
355 |
356 | ---
357 | ## Insomnia Rest Client Export
358 |
359 | [Insomnia Rest Client](https://insomnia.rest) is a great tool for testing
360 |
361 | nhl_api-{ver}.json in the root folder is an export of the endpoints I have
362 | been working through using the Insomnia Rest Client. You can import this directly
363 | into the client and use it to test the endpoints. I will be updating this as I go
364 |
365 |
366 | - - -
367 |
368 |
369 | ## Developers
370 |
371 | 1) Install [Poetry](https://python-poetry.org/docs/#installing-with-the-official-installer)
372 |
373 | `curl -sSL https://install.python-poetry.org | python3 -`
374 |
375 | or using pipx
376 |
377 | `pipx install poetry`
378 |
379 |
380 | 2) `poetry install --with dev`
381 |
382 | 3) `poetry shell`
383 |
384 |
385 | ### Build Pipeline
386 | The build pipeline will run `black`, `ruff`, and `pytest`. Please make sure these are passing before submitting a PR.
387 |
388 | ```python
389 |
390 | $ poetry shell
391 |
392 | # You can then run the following
393 | $ pytest
394 | $ ruff .
395 | $ black .
396 |
397 | ```
398 |
399 |
400 | ### pypi test net
401 | ```
402 | poetry build
403 | poetry publish -r test-pypi
404 | ```
405 |
406 |
407 | #### Poetry version management
408 | ```
409 | # View current version
410 | poetry version
411 |
412 | # Bump version
413 | poetry version patch # 0.1.0 -> 0.1.1
414 | poetry version minor # 0.1.0 -> 0.2.0
415 | poetry version major # 0.1.0 -> 1.0.0
416 |
417 | # Set specific version
418 | poetry version 2.0.0
419 |
420 | # Set pre-release versions
421 | poetry version prepatch # 0.1.0 -> 0.1.1-alpha.0
422 | poetry version preminor # 0.1.0 -> 0.2.0-alpha.0
423 | poetry version premajor # 0.1.0 -> 1.0.0-alpha.0
424 |
425 | # Specify pre-release identifier
426 | poetry version prerelease # 0.1.0 -> 0.1.0-alpha.0
427 | poetry version prerelease beta # 0.1.0-alpha.0 -> 0.1.0-beta.0
428 | ```
429 |
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/nhl_api_2_3_0.json:
--------------------------------------------------------------------------------
1 | {"_type":"export","__export_format":4,"__export_date":"2024-02-15T20:46:14.608Z","__export_source":"insomnia.desktop.app:v8.6.1","resources":[{"_id":"req_0480976539ba499183de1034a85118c9","parentId":"fld_9cc7cf9d180e438887ceedc3387332b5","modified":1707349526885,"created":1707349436961,"url":"https://api.nhle.com/stats/rest/en/draft?","name":"season specifics","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707349436961,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_9cc7cf9d180e438887ceedc3387332b5","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1707349372856,"created":1707349372856,"name":"Misc","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1707349372856,"_type":"request_group"},{"_id":"wrk_99b45ce56b994ef6b63cae0f80b8c840","parentId":null,"modified":1700602776803,"created":1700602776803,"name":"NHL API","description":"","scope":"collection","_type":"workspace"},{"_id":"req_0315e7a6fb7c4790a7381fd98c326194","parentId":"fld_9cc7cf9d180e438887ceedc3387332b5","modified":1708027314441,"created":1707349379690,"url":"https://api.nhle.com/stats/rest/en/country?","name":"countries","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707349379690,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_ec605f61d7f14f69891d7c0bd4513381","parentId":"fld_c881ef4f75c945128f84f418bd70e375","modified":1707862367424,"created":1707861147763,"url":"https://api-web.nhle.com/v1/player/8476453/game-log/20222023/2","name":"player gamelog","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707861147763,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_c881ef4f75c945128f84f418bd70e375","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1707182204260,"created":1707182204260,"name":"Stats","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1707182204260,"_type":"request_group"},{"_id":"req_2b5f840c20e24d5f8efcb9d2cec02a88","parentId":"fld_c881ef4f75c945128f84f418bd70e375","modified":1707350567064,"created":1707349801992,"url":"https://api.nhle.com/stats/rest/en/skater/summary","name":"Skater Stats summary","description":"","method":"GET","body":{},"parameters":[{"name":"isAggregate","value":"false","id":"pair_0cc2bf1a40d84481b99a038ea9adcee8"},{"name":"isGame","value":"false","id":"pair_8d9e01ee3d7c48f09bf73ff23c0afa06"},{"name":"sort","value":"[{\"property\":\"points\",\"direction\":\"DESC\"},{\"property\":\"gamesPlayed\",\"direction\":\"ASC\"},{\"property\":\"playerId\",\"direction\":\"ASC\"}]","id":"pair_24ce5eed3b8746ffbcd669aebf41061f"},{"name":"start","value":"0","id":"pair_c301087c1eae4e47b2a79a1ac89efb5a"},{"name":"limit","value":"10","id":"pair_932bc26db9d44396a1094bf3f8e7c559"},{"name":"factCayenneExp","value":"gamesPlayed>=1","id":"pair_bf115daac2f54baab4742306537f208f"},{"name":"cayenneExp","value":"gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024","id":"pair_bc3c7fed6ba64e78ab5e0508783ca774"}],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707349801992,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_0f6b8b2ed72b4992a0d56716dca607e1","parentId":"fld_c881ef4f75c945128f84f418bd70e375","modified":1707317239017,"created":1707314281816,"url":"https://api.nhle.com/stats/rest/en/team/summary","name":"Team Stats Summary","description":"","method":"GET","body":{},"parameters":[{"name":"isAggregate","value":"false"},{"name":"isGame","value":"false"},{"name":"sort","value":"[{\"property\":\"points\",\"direction\":\"DESC\"},{\"property\":\"wins\",\"direction\":\"DESC\"},{\"property\":\"teamId\",\"direction\":\"ASC\"}]"},{"name":"start","value":"0"},{"name":"limit","value":"50"},{"name":"factCayenneExp","value":"gamesPlayed>=1"},{"name":"cayenneExp","value":"gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024"}],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707314281816,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_02fd6a9157fd4a1a897bd59dbb1b375d","parentId":"fld_c881ef4f75c945128f84f418bd70e375","modified":1707182285031,"created":1707182208364,"url":"https://api-web.nhle.com/v1/club-stats-season/BUF","name":"Club Stats Season","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.5"}],"authentication":{},"metaSortKey":-1707182208364,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_c815e74a3aa140c7bae0427374b8af2a","parentId":"fld_c881ef4f75c945128f84f418bd70e375","modified":1707324381413,"created":1707182296597,"url":"https://api-web.nhle.com/v1/player/8480045/landing","name":"Player Stats","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.5"}],"authentication":{},"metaSortKey":-1704097754543.5,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_119c61ff426849ad94ef4592599de614","parentId":"fld_0a164c32cf894dda9e4e01342d9d6096","modified":1707350408275,"created":1707350357013,"url":"https://api.nhle.com/stats/rest/en/franchise","name":"franchise","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1707350357013,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_0a164c32cf894dda9e4e01342d9d6096","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1700677055390,"created":1700677055390,"name":"Teams","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1700677055390,"_type":"request_group"},{"_id":"req_306d3c7b26aa4f2f8b3c355cfece25a0","parentId":"fld_0a164c32cf894dda9e4e01342d9d6096","modified":1701016559924,"created":1701011877087,"url":"https://api-web.nhle.com/v1/roster/BUF/20232024","name":"roster","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.4"}],"authentication":{},"metaSortKey":-1701011877087,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_6455801ab3ba4148b3d6dc570b179a30","parentId":"fld_0a164c32cf894dda9e4e01342d9d6096","modified":1700677061232,"created":1699714308830,"url":"https://api.nhle.com/stats/rest/en/team/summary?","name":"Team Stats Summary","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.0"}],"authentication":{},"metaSortKey":-1700677061196,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_8704273712d04ba8bd0497391c2dbecc","parentId":"fld_0a164c32cf894dda9e4e01342d9d6096","modified":1700677118186,"created":1700677071513,"url":"https://api-web.nhle.com/v1/roster-season/BUF","name":"Team Roster","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.0"}],"authentication":{},"metaSortKey":-1700646562645,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_44977479c368439db2c6331a329a882e","parentId":"fld_7154c8f2df85461fa685bde21011fb2a","modified":1700961984501,"created":1700615630845,"url":"https://api-web.nhle.com/v1/gamecenter/2023020310/boxscore","name":"GameCenter - BoxScore","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.2"}],"authentication":{},"metaSortKey":-1700616064094,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_7154c8f2df85461fa685bde21011fb2a","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1700616051787,"created":1700616051787,"name":"Game Center","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1700616051787,"_type":"request_group"},{"_id":"req_a207e29ea51847cb853f593fbd178d2b","parentId":"fld_7154c8f2df85461fa685bde21011fb2a","modified":1700616823135,"created":1700616814036,"url":"https://api-web.nhle.com/v1/score/now","name":"GameCenter - Score Now","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.2"}],"authentication":{},"metaSortKey":-1700616052195,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_7a8da7415a8147549b76d3d326425f42","parentId":"fld_7154c8f2df85461fa685bde21011fb2a","modified":1700962024971,"created":1700616095982,"url":"https://api-web.nhle.com/v1/gamecenter/2023020310/play-by-play","name":"GameCenter - PlayByPlay","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.2"}],"authentication":{},"metaSortKey":-1700616040296,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_5c37e19afd9446c29b501d10a2221dc4","parentId":"fld_7154c8f2df85461fa685bde21011fb2a","modified":1700616512883,"created":1700616507407,"url":"https://api-web.nhle.com/v1/gamecenter/2023020285/landing","name":"GameCenter - Landing","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.2"}],"authentication":{},"metaSortKey":-1700616028397,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_ea0ea40c376a4d74b4496a301713df29","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700677761891,"created":1700677744770,"url":"https://api-web.nhle.com/v1/schedule-calendar/2023-11-22","name":"Schedule Calendar","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.4.2"}],"authentication":{},"metaSortKey":-1700677744770,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1700616000421,"created":1700616000421,"name":"Schedule","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1700616000421,"_type":"request_group"},{"_id":"req_1c805c50423d4853a4d7f8586e6f26ae","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700961969246,"created":1699629547871,"url":"https://api-web.nhle.com/v1/schedule/2023-11-25","name":"Schedule By Date","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616016498,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_f4b06b02014643688ce2adba6aa78da8","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700616031808,"created":1698326129771,"url":"https://api-web.nhle.com/v1/schedule/now","name":"Schedule Now","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616016398,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_299f4997b0384de8aa2785bbb3fb06e3","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700616026777,"created":1699634789997,"url":"https://api-web.nhle.com/v1/club-schedule/BUF/month/now","name":"Club Schedule by Month Now","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616016298,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_0c03a29b2c924a769b8561317f9b644d","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700616022893,"created":1699631380607,"url":"https://api-web.nhle.com/v1/club-schedule/BUF/month/2023-11","name":"Club Schedule by Month","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616016198,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_67fddd56d13a4cc29122f95abe65037f","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700616019954,"created":1699632450492,"url":"https://api-web.nhle.com/v1/club-schedule/BUF/week/now","name":"Club Schedule by week","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616016098,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_6dd56acc7608427d8643fe3eca82ff08","parentId":"fld_a1b982f4f15f47f5a8e81ddcfbbbb288","modified":1700616016035,"created":1699631552023,"url":"https://api-web.nhle.com/v1/club-schedule-season/BUF/20232024","name":"Club Schedule by Year","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700616015998,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_c6f2a92e978040748964dba407944c13","parentId":"fld_9185266547564925aed97555b4070a23","modified":1700615988944,"created":1699632326802,"url":"https://api-web.nhle.com/v1/standings/now","name":"Get Standings Now","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700615984150,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"fld_9185266547564925aed97555b4070a23","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1700615973724,"created":1700615973724,"name":"Standings","description":"","environment":{},"environmentPropertyOrder":null,"metaSortKey":-1700615973724,"_type":"request_group"},{"_id":"req_77f077f01ca046b886f4cfb827f13195","parentId":"fld_9185266547564925aed97555b4070a23","modified":1700615984089,"created":1699644667168,"url":"https://api-web.nhle.com/v1/standings-season/","name":"Get Standings Season","description":"","method":"GET","body":{},"parameters":[],"headers":[{"name":"User-Agent","value":"insomnia/8.3.0"}],"authentication":{},"metaSortKey":-1700615984050,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_32a714f5c8194cefbfde6daed74d3dca","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1707351662049,"created":1699645690565,"url":"https://api.nhle.com/stats/rest/en/skater/summary","name":"test","description":"","method":"GET","body":{},"parameters":[{"name":"isAggregate","value":"true","id":"pair_2599316deb3b439496549cd36eeb12d6"},{"name":"isGame","value":"false","id":"pair_55b04aa132bc4c3e916877b1bee2e89d"},{"name":"sort","value":"[{\"property\":\"points\",\"direction\":\"DESC\"},{\"property\":\"gamesPlayed\",\"direction\":\"ASC\"},{\"property\":\"playerId\",\"direction\":\"ASC\"}]","id":"pair_e2ba7d7677c64ba2a5e16754b6b7daaa"},{"name":"start","value":"0","id":"pair_1446d0aa039842d3bb9666fe5d7f9642"},{"name":"limit","value":"100","id":"pair_a49d43a1d009480b8af6b434558cbe08"},{"name":"factCayenneExp","value":"gamesPlayed>=1","id":"pair_e62c86e403d84910974ae4e163ed45e3"},{"name":"cayenneExp","value":"gameTypeId=2 and seasonId<=20232024 and seasonId>=20222023","id":"pair_4c990ef1c4604327baf1f4eed039a953"}],"headers":[{"name":"User-Agent","value":"insomnia/8.4.0"}],"authentication":{},"metaSortKey":-1699645690565,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"req_d62d9fb99dd84bbaa0254e500da82bee","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1708028653267,"created":1707350296487,"url":"https://api.nhle.com/stats/rest/en/skater/summary","name":"test2","description":"","method":"GET","body":{},"parameters":[{"name":"isAggregate","value":"true"},{"name":"isGame","value":"false"},{"name":"start","value":"0"},{"name":"limit","value":"70"},{"name":"factCayenneExp","value":"goals>=10"},{"name":"sort","value":"[{\"property\": \"points\", \"direction\": \"DESC\"}, {\"property\": \"gamesPlayed\", \"direction\": \"ASC\"}, {\"property\": \"playerId\", \"direction\": \"ASC\"}]"},{"name":"cayenneExp","value":"gameTypeId=2 and isRookie='0' and seasonId >= 20232024 and seasonId <= 20232024 and nationalityCode='USA'"}],"headers":[{"name":"User-Agent","value":"insomnia/8.6.1"}],"authentication":{},"metaSortKey":-1699645690465,"isPrivate":false,"pathParameters":[],"settingStoreCookies":true,"settingSendCookies":true,"settingDisableRenderRequestBody":false,"settingEncodeUrl":true,"settingRebuildPath":true,"settingFollowRedirects":"global","_type":"request"},{"_id":"env_03a7e3eb088245d7af86c18a5d983a2d","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1698242404315,"created":1698242404315,"name":"Base Environment","data":{},"dataPropertyOrder":null,"color":null,"isPrivate":false,"metaSortKey":1698242404315,"_type":"environment"},{"_id":"jar_cd68277a39254c7eb5209b24f8beef3f","parentId":"wrk_99b45ce56b994ef6b63cae0f80b8c840","modified":1698242404316,"created":1698242404316,"name":"Default Jar","cookies":[],"_type":"cookie_jar"}]}
--------------------------------------------------------------------------------
/nhlpy/__init__.py:
--------------------------------------------------------------------------------
1 | from .nhl_client import NHLClient # noqa: F401
2 |
--------------------------------------------------------------------------------
/nhlpy/api/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coreyjs/nhl-api-py/d0f71371893a29b3bc067ee12e293391a8d6319f/nhlpy/api/__init__.py
--------------------------------------------------------------------------------
/nhlpy/api/game_center.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, List
2 | from nhlpy.http_client import HttpClient
3 |
4 |
5 | class GameCenter:
6 | def __init__(self, http_client: HttpClient):
7 | self.client = http_client
8 |
9 | def boxscore(self, game_id: str) -> dict:
10 | """Get boxscore data for a specific NHL game. GameIds can be retrieved from the schedule endpoint.
11 |
12 | Args:
13 | game_id (str): The game_id for the game you want the boxscore for
14 |
15 | Example:
16 | API endpoint format: https://api-web.nhle.com/v1/gamecenter/2023020280/boxscore
17 |
18 | Returns:
19 | dict: Game boxscore data
20 | """
21 | return self.client.get(resource=f"gamecenter/{game_id}/boxscore").json()
22 |
23 | def play_by_play(self, game_id: str) -> dict:
24 | """Get play-by-play data for a specific NHL game. GameIds can be retrieved from the schedule endpoint.
25 |
26 | Args:
27 | game_id (str): The game_id for the game you want the play by play for
28 |
29 | Returns:
30 | dict: Play-by-play game data
31 | """
32 | return self.client.get(resource=f"gamecenter/{game_id}/play-by-play").json()
33 |
34 | def landing(self, game_id: str) -> dict:
35 | """Get detailed match up information for a specific NHL game. GameIds can be retrieved
36 | from the schedule endpoint.
37 |
38 | Args:
39 | game_id (str): The game_id for the game you want the landing page for
40 |
41 | Returns:
42 | dict: Detailed game matchup data
43 | """
44 | return self.client.get(resource=f"gamecenter/{game_id}/landing").json()
45 |
46 | def score_now(self, date: Optional[str] = None) -> dict:
47 | """Get current scores for NHL games. GameDay updates at noon est I think.
48 |
49 | Args:
50 | date (str, optional): Date to check scores in YYYY-MM-DD format
51 |
52 | Returns:
53 | dict: Game scores and status information
54 | """
55 | return self.client.get(resource=f"score/{date if date else 'now'}").json()
56 |
57 | def shift_chart_data(self, game_id: str, excludes: List[str] = None) -> dict:
58 | """Gets shift chart data for a specific game.
59 |
60 | Args:
61 | game_id (str): ID of the game to retrieve shift data for. Game IDs can be retrieved
62 | from the schedule endpoint.
63 | excludes (List[str]): List of items to exclude from the response.
64 |
65 | Returns:
66 | Dict containing the shift chart data.
67 | """
68 | if not excludes:
69 | excludes = ["eventDetails"]
70 |
71 | base_url: str = "https://api.nhle.com/stats/rest/en/shiftcharts"
72 | exclude_p: str = ",".join(excludes)
73 | expr_p: str = f"gameId={game_id} and ((duration != '00:00' and typeCode = 517) or typeCode != 517 )"
74 | return self.client.get_by_url(full_resource=f"{base_url}?cayenneExp={expr_p}&exclude={exclude_p}").json()
75 |
76 | def right_rail(self, game_id: str) -> dict:
77 | """Gets game stats and season series information for a specific game.
78 |
79 | Args:
80 | game_id (str): ID of the game to retrieve stats for. Game IDs can be retrieved
81 | from the schedule endpoint.
82 |
83 | Returns:
84 | Dict containing game stats and season series data.
85 | """
86 | return self.client.get(resource=f"gamecenter/{game_id}/right-rail").json()
87 |
88 | def game_story(self, game_id: str) -> dict:
89 | """Gets game story information for a specific game.
90 |
91 | Args:
92 | game_id (str): ID of the game to retrieve story for. Game IDs can be retrieved
93 | from the schedule endpoint.
94 |
95 | Returns:
96 | Dict containing game story data.
97 | """
98 | return self.client.get(resource=f"wsc/game-story/{game_id}").json()
99 |
--------------------------------------------------------------------------------
/nhlpy/api/helpers.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from nhlpy.http_client import HttpClient
4 |
5 |
6 | class Helpers:
7 | def __init__(self, http_client: HttpClient) -> None:
8 | self.client = http_client
9 |
10 | def get_gameids_by_season(self, season: str, game_types: List[int] = None) -> List[str]:
11 | """Gets all game IDs for a specified season.
12 |
13 | Args:
14 | season (str): Season to retrieve game IDs for in YYYYYYYY format (e.g., 20232024).
15 | game_types (List[int]): List of game types to include. Valid types:
16 | 1: Preseason
17 | 2: Regular season
18 | 3: Playoffs
19 |
20 | Returns:
21 | List of game IDs for the specified season and game types.
22 | """
23 | from nhlpy.api.teams import Teams
24 | from nhlpy.api.schedule import Schedule
25 |
26 | teams = Teams(self.client).teams_info()
27 |
28 | gameids = []
29 | schedule_api = Schedule(self.client)
30 | for team in teams:
31 | team_abbr = team.get("abbr", "")
32 | if not team_abbr:
33 | continue
34 |
35 | schedule = schedule_api.get_season_schedule(team_abbr, season)
36 | games = schedule.get("games", [])
37 |
38 | for game in games:
39 | game_type = game.get("gameType")
40 | game_id = game.get("id")
41 |
42 | if game_id and (not game_types or game_type in game_types):
43 | gameids.append(game_id)
44 |
45 | return gameids
46 |
--------------------------------------------------------------------------------
/nhlpy/api/misc.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from nhlpy.http_client import HttpClient
4 |
5 |
6 | class Misc:
7 | def __init__(self, http_client: HttpClient) -> None:
8 | self.client = http_client
9 |
10 | def glossary(self) -> List[dict]:
11 | """Get the glossary for the NHL API.
12 |
13 | Returns:
14 | dict: NHL API glossary data
15 | """
16 | response = self.client.get_by_url(
17 | full_resource="https://api.nhle.com/stats/rest/en/glossary?sort=fullName"
18 | ).json()
19 | return response.get("data", [])
20 |
21 | def config(self) -> dict:
22 | """Get available filter options.
23 |
24 | Returns:
25 | dict: Dictionary of filter options
26 | """
27 | return self.client.get_by_url(full_resource="https://api.nhle.com/stats/rest/en/config").json()
28 |
29 | def countries(self) -> List[dict]:
30 | """Get list of countries from NHL API.
31 |
32 | Returns:
33 | dict: Dictionary of country data
34 | """
35 | response = self.client.get_by_url(full_resource="https://api.nhle.com/stats/rest/en/country").json()
36 | return response.get("data", [])
37 |
38 | def season_specific_rules_and_info(self) -> List[dict]:
39 | """Get NHL season rules and information.
40 |
41 | Returns:
42 | dict: Dictionary containing season-specific rules and information
43 | """
44 | response = self.client.get_by_url(full_resource="https://api.nhle.com/stats/rest/en/season").json()
45 | return response.get("data", [])
46 |
47 | def draft_year_and_rounds(self) -> List[dict]:
48 | """Get NHL draft year and round information.
49 |
50 | Returns:
51 | dict: Draft data containing 'id', 'draftYear', and 'rounds count'
52 | """
53 | response = self.client.get_by_url(full_resource="https://api.nhle.com/stats/rest/en/draft").json()
54 | return response.get("data", [])
55 |
--------------------------------------------------------------------------------
/nhlpy/api/playoffs.py:
--------------------------------------------------------------------------------
1 | from nhlpy.http_client import HttpClient
2 |
3 |
4 | class Playoffs:
5 | def __init__(self, http_client: HttpClient):
6 | self.client = http_client
7 |
8 | def carousel(self, season: str) -> dict:
9 | """Gets list of all series games up to current playoff round.
10 |
11 | Args:
12 | season (str): Season in YYYYYYYY format (e.g., "20232024")
13 |
14 | Returns:
15 | dict: Playoff series data for the specified season.
16 |
17 | Example:
18 | API endpoint: https://api-web.nhle.com/v1/playoff-series/carousel/20232024/
19 | """
20 | return self.client.get(resource=f"playoff-series/carousel/{season}").json()
21 |
22 | def schedule(self, season: str, series: str) -> dict:
23 | """Returns the schedule for a specified playoff series.
24 |
25 | Args:
26 | season (str): Season in YYYYYYYY format (e.g., "20232024")
27 | series (str): Series identifier (a-h) for Round 1
28 |
29 | Returns:
30 | dict: Schedule data for the specified playoff series.
31 |
32 | Example:
33 | API endpoint: https://api-web.nhle.com/v1/schedule/playoff-series/20232024/a/
34 | """
35 |
36 | return self.client.get(resource=f"schedule/playoff-series/{season}/{series}").json()
37 |
38 | def bracket(self, year: str) -> dict:
39 | """Returns the playoff bracket.
40 |
41 | Args:
42 | year (str): Year playoffs take place (e.g., "2024")
43 |
44 | Returns:
45 | dict: Playoff bracket data.
46 |
47 | Example:
48 | API endpoint: https://api-web.nhle.com/v1/playoff-bracket/2024
49 | """
50 |
51 | return self.client.get(resource=f"playoff-bracket/{year}").json()
52 |
--------------------------------------------------------------------------------
/nhlpy/api/query/__init__.py:
--------------------------------------------------------------------------------
1 | class InvalidQueryValueException(Exception):
2 | pass
3 |
--------------------------------------------------------------------------------
/nhlpy/api/query/builder.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 | import logging
3 |
4 | from nhlpy.api.query import InvalidQueryValueException
5 | from nhlpy.api.query.filters import QueryBase
6 |
7 |
8 | class QueryContext:
9 | """A container for query information and validation state.
10 |
11 | This class holds the constructed query string, original filters, any validation
12 | errors, and a base fact query. It provides methods to check query validity.
13 |
14 | Attributes:
15 | query_str (str): The constructed query string from all valid filters
16 | filters (List[QueryBase]): List of original query filter objects
17 | errors (List[str]): List of validation error messages
18 | fact_query (str): Base fact query, defaults to "gamesPlayed>=1"
19 | """
20 |
21 | def __init__(self, query: str, filters: List[QueryBase], fact_query: str = None, errors: List[str] = None):
22 | self.query_str = query
23 | self.filters = filters
24 | self.errors = errors
25 | self.fact_query = fact_query if fact_query else "gamesPlayed>=1"
26 |
27 | def is_valid(self) -> bool:
28 | """Check if the query context is valid.
29 |
30 | Returns:
31 | bool: True if there are no validation errors, False otherwise
32 | """
33 | return len(self.errors) == 0
34 |
35 |
36 | class QueryBuilder:
37 | """Builds and validates query strings from a list of query filters.
38 |
39 | This class processes a list of QueryBase filters, validates them, and combines
40 | them into a single query string. It handles validation errors and provides
41 | optional verbose logging.
42 |
43 | Attributes:
44 | _verbose (bool): When True, enables detailed logging of the build process
45 | """
46 |
47 | def __init__(self, verbose: bool = False):
48 | self._verbose = verbose
49 | if self._verbose:
50 | logging.basicConfig(level=logging.INFO)
51 |
52 | def build(self, filters: List[QueryBase]) -> QueryContext:
53 | """Build a query string from a list of filters.
54 |
55 | Processes each filter in the list, validates it, and combines valid filters
56 | into a single query string using 'and' as the connector.
57 |
58 | Args:
59 | filters (List[QueryBase]): List of query filter objects to process
60 |
61 | Returns:
62 | QueryContext: A context object containing the query string, original filters,
63 | and any validation errors
64 |
65 | Notes:
66 | - Skips filters that aren't instances of QueryBase
67 | - Collects validation errors but continues processing remaining filters
68 | - Combines valid filters with 'and' operator
69 | - Returns empty query string if no valid filters are found
70 | """
71 | result_query: str = ""
72 | output_filters: List[str] = []
73 | errors: List[str] = []
74 | for f in filters:
75 | if not isinstance(f, QueryBase):
76 | if self._verbose:
77 | logging.info(f"Input filter is not of type QueryBase: {f.__name__}")
78 | continue
79 |
80 | # Validate the filter
81 | try:
82 | if not f.validate():
83 | raise InvalidQueryValueException(f"Filter failed validation: {str(f)}")
84 | except InvalidQueryValueException as e:
85 | if self._verbose:
86 | logging.error(e)
87 | errors.append(str(e))
88 | continue
89 |
90 | output_filters.append(f.to_query())
91 | else:
92 | if len(output_filters) > 0:
93 | result_query = " and ".join(output_filters)
94 |
95 | return QueryContext(query=result_query, filters=filters, errors=errors)
96 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/__init__.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from typing import Union, List
3 |
4 |
5 | class QueryBase(ABC):
6 | @abstractmethod
7 | def to_query(self) -> str:
8 | pass
9 |
10 | @abstractmethod
11 | def validate(self) -> Union[bool, None]:
12 | return True
13 |
14 |
15 | def _goalie_stats_sorts(report: str) -> List[dict]:
16 | """
17 | This is default criteria for sorting on goalie stats. I hate this method
18 | :param report:
19 | :return:
20 | """
21 | if report == "summary":
22 | return [
23 | {"property": "wins", "direction": "DESC"},
24 | {"property": "gamesPlayed", "direction": "ASC"},
25 | {"property": "playerId", "direction": "ASC"},
26 | ]
27 | elif report == "advanced":
28 | return [
29 | {"property": "qualityStart", "direction": "DESC"},
30 | {"property": "goalsAgainstAverage", "direction": "ASC"},
31 | {"property": "playerId", "direction": "ASC"},
32 | ]
33 | elif report == "bios":
34 | return [
35 | {"property": "lastName", "direction": "ASC_CI"},
36 | {"property": "goalieFullName", "direction": "ASC_CI"},
37 | {"property": "playerId", "direction": "ASC"},
38 | ]
39 | elif report == "daysrest":
40 | return [
41 | {"property": "wins", "direction": "DESC"},
42 | {"property": "savePct", "direction": "DESC"},
43 | {"property": "playerId", "direction": "ASC"},
44 | ]
45 | elif report == "penaltyShots":
46 | return [
47 | {"property": "penaltyShotsSaves", "direction": "DESC"},
48 | {"property": "penaltyShotSavePct", "direction": "DESC"},
49 | {"property": "playerId", "direction": "ASC"},
50 | ]
51 | elif report == "savesByStrength":
52 | return [
53 | {"property": "wins", "direction": "DESC"},
54 | {"property": "savePct", "direction": "DESC"},
55 | {"property": "playerId", "direction": "ASC"},
56 | ]
57 | elif report == "shootout":
58 | return [
59 | {"property": "shootoutWins", "direction": "DESC"},
60 | {"property": "shootoutSavePct", "direction": "DESC"},
61 | {"property": "playerId", "direction": "ASC"},
62 | ]
63 | elif report == "startedVsRelieved":
64 | return [
65 | {"property": "gamesStarted", "direction": "DESC"},
66 | {"property": "gamesStartedSavePct", "direction": "DESC"},
67 | {"property": "playerId", "direction": "ASC"},
68 | ]
69 | else:
70 | return [{}]
71 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/decision.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import Union
3 |
4 | from nhlpy.api.query import InvalidQueryValueException
5 | from nhlpy.api.query.filters import QueryBase
6 |
7 |
8 | logger = logging.getLogger(__name__)
9 |
10 |
11 | class DecisionQuery(QueryBase):
12 | def __init__(self, decision: str):
13 | """
14 | Decision filter. W=win, L=loss, O=overtime loss,
15 | :param decision: W, L, O
16 | """
17 | self.decision = decision
18 | self._decision_q = "decision"
19 |
20 | def __str__(self):
21 | return f"DecisionQuery: Value={self.decision}"
22 |
23 | def to_query(self) -> str:
24 | return f"{self._decision_q}='{self.decision}'"
25 |
26 | def validate(self) -> Union[bool, None]:
27 | if self.decision not in ["W", "L", "O"]:
28 | raise InvalidQueryValueException("Decision value must be one of [W, L, O]")
29 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/draft.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 |
6 | class DraftQuery(QueryBase):
7 | def __init__(self, year: str, draft_round: Optional[str] = None):
8 | """
9 |
10 | :param year:
11 | :param draft_round: This seems to default to "1" on the API. Should
12 | check not supplying it.
13 | """
14 | self.year = year
15 | self.round = draft_round
16 | self._year_q = "draftYear"
17 | self._round_q = "draftRound"
18 |
19 | def to_query(self) -> str:
20 | query = f"{self._year_q}={self.year}"
21 | if self.round:
22 | query += " and "
23 | query += f"{self._round_q}={self.round}"
24 | return query
25 |
26 | def validate(self) -> Union[bool, None]:
27 | return True
28 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/experience.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 |
6 | class ExperienceQuery(QueryBase):
7 | def __init__(self, is_rookie: bool):
8 | """
9 | Experience filter. R=rookie, S=sophomore, V=veteran
10 | :param experience: R, S, V
11 | """
12 | self.is_rookie: bool = is_rookie
13 | self._experience_q = "isRookie"
14 |
15 | def to_query(self) -> str:
16 | val = "1" if self.is_rookie else "0"
17 | return f"{self._experience_q}='{val}'"
18 |
19 | def validate(self) -> Union[bool, None]:
20 | return True
21 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/franchise.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.builder import QueryBase
4 |
5 |
6 | class FranchiseQuery(QueryBase):
7 | def __init__(self, franchise_id: str):
8 | self.franchise_id = franchise_id
9 | self._franchise_q = "franchiseId"
10 |
11 | def to_query(self) -> str:
12 | return f"{self._franchise_q}={self.franchise_id}"
13 |
14 | def validate(self) -> Union[bool, None]:
15 | return True
16 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/game_type.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.builder import QueryBase
4 |
5 |
6 | class GameTypeQuery(QueryBase):
7 | def __init__(self, game_type: str):
8 | self.game_type = game_type
9 | self._game_type_q = "gameTypeId"
10 |
11 | def to_query(self) -> str:
12 | return f"{self._game_type_q}={self.game_type}"
13 |
14 | def validate(self) -> Union[bool, None]:
15 | return True
16 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/home_road.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 |
6 | class HomeRoadQuery(QueryBase):
7 | def __init__(self, home_road: str):
8 | """
9 | H or R to indicate home or road games.
10 | :param home_road:
11 | """
12 | self.home_road = home_road
13 | self._home_road_q = "homeRoad"
14 |
15 | def to_query(self) -> str:
16 | return f"{self._home_road_q}='{self.home_road}'"
17 |
18 | def validate(self) -> Union[bool, None]:
19 | return True
20 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/nationality.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.builder import QueryBase
4 |
5 |
6 | class NationalityQuery(QueryBase):
7 | """
8 | Country/Nationality codes can be found via client.misc.countries() endpoint. As of 2/15/24 these are the codes"
9 | [
10 | "AUS", "AUT", "BEL", "BHS", "BLR", "BRA",
11 | "CAN", "CHE", "CHN", "DEU", "DNK", "EST",
12 | "FIN", "FRA", "GBR", "GRC", "GUY", "HRV",
13 | "HTI", "HUN", "IRL", "ISR", "ITA", "JAM",
14 | "JPN", "KAZ", "KOR", "LBN", "LTU", "LVA",
15 | "MEX", "NGA", "NLD", "NOR", "POL", "PRY",
16 | "ROU", "RUS", "SRB", "SVK", "SVN", "SWE",
17 | "THA", "UKR", "USA", "VEN", "YUG", "ZAF",
18 | "CZE"
19 | ]
20 |
21 | """
22 |
23 | def __init__(self, nation_code: str):
24 | self.nation_code = nation_code
25 | self._nation_q = "nationalityCode"
26 |
27 | def validate(self) -> Union[bool, None]:
28 | return True
29 |
30 | def to_query(self) -> str:
31 | return f"{self._nation_q}='{self.nation_code}'"
32 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/opponent.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 |
6 | class OpponentQuery(QueryBase):
7 | def __init__(self, opponent_franchise_id: str):
8 | """
9 | Opponent filter. Takes in the ID of the franchise.
10 | :param opponent_id: int
11 | """
12 | self.opponent_id: str = opponent_franchise_id
13 | self._opponent_q = "opponentFranchiseId"
14 |
15 | def to_query(self) -> str:
16 | return f"{self._opponent_q}={self.opponent_id}"
17 |
18 | def validate(self) -> Union[bool, None]:
19 | return True
20 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/position.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 | from enum import Enum
3 |
4 | from nhlpy.api.query.builder import QueryBase
5 |
6 |
7 | class PositionTypes(str, Enum):
8 | ALL_FORWARDS = "F"
9 | CENTER = "C"
10 | LEFT_WING = "L"
11 | RIGHT_WING = "R"
12 | DEFENSE = "D"
13 |
14 |
15 | class PositionQuery(QueryBase):
16 | def __init__(self, position: PositionTypes):
17 | self.position = position
18 | self._position_q = "positionCode"
19 |
20 | def to_query(self) -> str:
21 | # All forwards require an OR clause
22 | if self.position == PositionTypes.ALL_FORWARDS:
23 | return (
24 | f"({self._position_q}='{PositionTypes.LEFT_WING.value}' "
25 | f"or {self._position_q}='{PositionTypes.RIGHT_WING.value}' "
26 | f"or {self._position_q}='{PositionTypes.CENTER.value}')"
27 | )
28 |
29 | return f"{self._position_q}='{self.position.value}'"
30 |
31 | def validate(self) -> Union[bool, None]:
32 | return True
33 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/season.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 |
6 | class SeasonQuery(QueryBase):
7 | def __init__(self, season_start: str, season_end: str):
8 | self.season_start = season_start
9 | self.season_end = season_end
10 | self._season_start_q = "seasonId"
11 | self._season_start_q_exp = ">="
12 | self._season_end_q = "seasonId"
13 | self._season_end_q_exp = "<="
14 |
15 | def to_query(self) -> str:
16 | query = f"{self._season_start_q} {self._season_start_q_exp} {self.season_start}"
17 | query += " and "
18 | query += f"{self._season_end_q} {self._season_end_q_exp} {self.season_end}"
19 | return query
20 |
21 | def validate(self) -> Union[bool, None]:
22 | return True
23 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/shoot_catch.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.builder import QueryBase
4 |
5 |
6 | class ShootCatchesQuery(QueryBase):
7 | def __init__(self, shoot_catch: str):
8 | """
9 | Shoot / catch filter. L or R, for both I believe its nothing.
10 | :param shoot_catch: L, R
11 | """
12 | self.shoot_catch = shoot_catch
13 | self.shoot_catch_q = "shootsCatches"
14 |
15 | def to_query(self) -> str:
16 | return f"{self.shoot_catch_q}='{self.shoot_catch}'"
17 |
18 | def validate(self) -> Union[bool, None]:
19 | return True
20 |
--------------------------------------------------------------------------------
/nhlpy/api/query/filters/status.py:
--------------------------------------------------------------------------------
1 | from typing import Union
2 |
3 | from nhlpy.api.query.filters import QueryBase
4 |
5 | # Not thrilled with this implementation, having 2 bools with the later overridding the first.
6 | # Ill think of a better design pattern for this.
7 |
8 |
9 | class StatusQuery(QueryBase):
10 | def __init__(self, is_active: bool = False, is_hall_of_fame: bool = False):
11 | """
12 | Player status. is_active=True for current active players, not suppling this
13 | defaults to active/inactive. OR you can specify is_hall_of_fame=True, for
14 | only HOF Players
15 | :param is_active:
16 | :param is_hall_of_fame:
17 | """
18 | self.is_active: bool = is_active
19 | self.is_hall_of_fame: bool = is_hall_of_fame
20 | self._active_q = "active"
21 | self._hof_q = "isInHallOfFame"
22 |
23 | def to_query(self) -> str:
24 | if self.is_hall_of_fame:
25 | return f"{self._hof_q}=1"
26 | elif self.is_active:
27 | return f"{self._active_q}=1"
28 | else:
29 | return ""
30 |
31 | def validate(self) -> Union[bool, None]:
32 | return True
33 |
--------------------------------------------------------------------------------
/nhlpy/api/query/sorting/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coreyjs/nhl-api-py/d0f71371893a29b3bc067ee12e293391a8d6319f/nhlpy/api/query/sorting/__init__.py
--------------------------------------------------------------------------------
/nhlpy/api/query/sorting/sorting_options.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import List
3 |
4 | logger = logging.getLogger(__name__)
5 |
6 | skater_summary_default_sorting = [
7 | {"property": "points", "direction": "DESC"},
8 | {"property": "gamesPlayed", "direction": "ASC"},
9 | {"property": "playerId", "direction": "ASC"},
10 | ]
11 |
12 | skater_bios_default_sorting = [
13 | {"property": "lastName", "direction": "ASC_CI"},
14 | {"property": "skaterFullName", "direction": "ASC_CI"},
15 | {"property": "playerId", "direction": "ASC"},
16 | ]
17 |
18 | faceoffs_default_sorting = [
19 | {"property": "totalFaceoffs", "direction": "DESC"},
20 | {"property": "playerId", "direction": "ASC"},
21 | ]
22 |
23 | faceoff_wins_default_sorting = [
24 | {"property": "totalFaceoffWins", "direction": "DESC"},
25 | {"property": "faceoffWinPct", "direction": "DESC"},
26 | {"property": "playerId", "direction": "ASC"},
27 | ]
28 |
29 | goalsForAgainst_default_sorting = [
30 | {"property": "evenStrengthGoalDifference", "direction": "DESC"},
31 | {"property": "playerId", "direction": "ASC"},
32 | ]
33 |
34 |
35 | realtime_default_sorting = [{"property": "hits", "direction": "DESC"}, {"property": "playerId", "direction": "ASC"}]
36 |
37 | penalties_default_sorting = [
38 | {"property": "penaltyMinutes", "direction": "DESC"},
39 | {"property": "playerId", "direction": "ASC"},
40 | ]
41 |
42 | penaltyKill_default_sorting = [
43 | {"property": "shTimeOnIce", "direction": "DESC"},
44 | {"property": "playerId", "direction": "ASC"},
45 | ]
46 |
47 | penalty_shot_default_sorting = [
48 | {"property": "penaltyShotsGoals", "direction": "DESC"},
49 | {"property": "playerId", "direction": "ASC"},
50 | ]
51 |
52 | powerplay_default_sorting = [
53 | {"property": "ppTimeOnIce", "direction": "DESC"},
54 | {"property": "playerId", "direction": "ASC"},
55 | ]
56 |
57 | puckposs_default_sorting = [{"property": "satPct", "direction": "DESC"}, {"property": "playerId", "direction": "ASC"}]
58 |
59 | summary_shooting_default_sorting = [
60 | {"property": "satTotal", "direction": "DESC"},
61 | {"property": "usatTotal", "direction": "DESC"},
62 | {"property": "playerId", "direction": "ASC"},
63 | ]
64 |
65 | percentages_default_sorting = [
66 | {"property": "satPercentage", "direction": "DESC"},
67 | {"property": "playerId", "direction": "ASC"},
68 | ]
69 |
70 | scoringratesdefault_sorting = [
71 | {"property": "pointsPer605v5", "direction": "DESC"},
72 | {"property": "goalsPer605v5", "direction": "DESC"},
73 | {"property": "playerId", "direction": "ASC"},
74 | ]
75 |
76 | scoring_per_game_default_sorting = [
77 | {"property": "pointsPerGame", "direction": "DESC"},
78 | {"property": "goalsPerGame", "direction": "DESC"},
79 | {"property": "playerId", "direction": "ASC"},
80 | ]
81 |
82 | shootout_default_scoring = [
83 | {"property": "shootoutGoals", "direction": "DESC"},
84 | {"property": "playerId", "direction": "ASC"},
85 | ]
86 |
87 | shottype_default_sorting = [
88 | {"property": "shootingPct", "direction": "DESC"},
89 | {"property": "shootingPctBat", "direction": "DESC"},
90 | {"property": "playerId", "direction": "ASC"},
91 | ]
92 |
93 |
94 | time_on_ice_default_sorting = [
95 | {"property": "timeOnIce", "direction": "DESC"},
96 | {"property": "playerId", "direction": "ASC"},
97 | ]
98 |
99 |
100 | class SortingOptions:
101 | @staticmethod
102 | def get_default_sorting_for_report(report: str) -> List[dict]:
103 | """
104 | I know this us ugly. But hopefully its out of sight out of mind.
105 | :param report:
106 | :return:
107 | """
108 | if report == "summary":
109 | return skater_summary_default_sorting
110 | elif report == "bios":
111 | return skater_bios_default_sorting
112 | elif report == "faceoffpercentages":
113 | return faceoffs_default_sorting
114 | elif report == "faceoffwins":
115 | return faceoff_wins_default_sorting
116 | elif report == "goalsForAgainst":
117 | return goalsForAgainst_default_sorting
118 | elif report == "realtime":
119 | return realtime_default_sorting
120 | elif report == "penalties":
121 | return penalties_default_sorting
122 | elif report == "penaltykill":
123 | return penaltyKill_default_sorting
124 | elif report == "penaltyShots":
125 | return penalty_shot_default_sorting
126 | elif report == "powerplay":
127 | return powerplay_default_sorting
128 | elif report == "puckPossessions":
129 | return puckposs_default_sorting
130 | elif report == "summaryshooting":
131 | return summary_shooting_default_sorting
132 | elif report == "percentages":
133 | return percentages_default_sorting
134 | elif report == "scoringRates":
135 | return scoringratesdefault_sorting
136 | elif report == "scoringpergame":
137 | return scoring_per_game_default_sorting
138 | elif report == "shootout":
139 | return shootout_default_scoring
140 | elif report == "shottype":
141 | return shottype_default_sorting
142 | elif report == "timeonice":
143 | return time_on_ice_default_sorting
144 | else:
145 | logger.info("No default sort criteria setup for this report type, defaulting to skater summary")
146 | return skater_summary_default_sorting
147 |
--------------------------------------------------------------------------------
/nhlpy/api/schedule.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from typing import Optional, List
3 |
4 | from nhlpy.http_client import HttpClient
5 |
6 |
7 | class Schedule:
8 | def __init__(self, http_client: HttpClient) -> None:
9 | self.client = http_client
10 |
11 | def get_schedule(self, date: str = None) -> dict:
12 | """Gets NHL schedule for a specific date.
13 |
14 | Args:
15 | date (str): Date in YYYY-MM-DD format.
16 |
17 | Returns:
18 | dict: Game schedule data for the specified date.
19 | """
20 | try:
21 | # Parse and reformat the date to ensure YYYY-MM-DD
22 | date = datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m-%d")
23 | except ValueError:
24 | raise ValueError("Invalid date format. Please use YYYY-MM-DD.")
25 |
26 | schedule_data: dict = self.client.get(resource=f"schedule/{date}").json()
27 | response_payload = {
28 | "nextStartDate": schedule_data.get("nextStartDate", None),
29 | "previousStartDate": schedule_data.get("previousStartDate", None),
30 | "date": date,
31 | "oddsPartners": schedule_data.get("oddsPartners", None),
32 | }
33 |
34 | game_week = schedule_data.get("gameWeek", [])
35 | matching_day = next((day for day in game_week if day.get("date") == date), None)
36 |
37 | if matching_day:
38 | games = matching_day.get("games", [])
39 | response_payload["games"] = games
40 | response_payload["numberOfGames"] = len(games)
41 |
42 | return response_payload
43 |
44 | def get_weekly_schedule(self, date: Optional[str] = None) -> dict:
45 | """Gets NHL schedule for a week starting from the specified date.
46 |
47 | Args:
48 | date (str, optional): Date in YYYY-MM-DD format. Defaults to today's date.
49 | Note: NHL's "today" typically shifts around 12:00 EST.
50 |
51 | Returns:
52 | dict: Weekly game schedule data.
53 | """
54 | res = date if date else "now"
55 |
56 | return self.client.get(resource=f"schedule/{res}").json()
57 |
58 | def get_schedule_by_team_by_month(self, team_abbr: str, month: Optional[str] = None) -> List[dict]:
59 | """Gets monthly schedule for specified team or the given month. If no month is supplied it will default to now.
60 |
61 | Args:
62 | team_abbr (str): Three-letter team abbreviation (e.g., BUF, TOR)
63 | month (str, optional): Month in YYYY-MM format (e.g., 2021-10). Defaults to current month.
64 |
65 | Returns:
66 | List[dict]: List of games in the monthly schedule.
67 | """
68 | resource = f"club-schedule/{team_abbr}/month/{month if month else 'now'}"
69 | response = self.client.get(resource=resource).json()
70 | return response.get("games", [])
71 |
72 | def get_schedule_by_team_by_week(self, team_abbr: str, date: Optional[str] = None) -> List[dict]:
73 | """Gets weekly schedule for specified team. If no date is supplied it will default to current week.
74 |
75 | Args:
76 | team_abbr (str): Three-letter team abbreviation (e.g., BUF, TOR)
77 | date (str, optional): Date in YYYY-MM-DD format. Gets schedule for week containing this date.
78 | Defaults to current week.
79 |
80 | Returns:
81 | List[dict]: List of games in the weekly schedule.
82 | """
83 | resource = f"club-schedule/{team_abbr}/week/{date if date else 'now'}"
84 | response = self.client.get(resource=resource).json()
85 | return response.get("games", [])
86 |
87 | def get_season_schedule(self, team_abbr: str, season: str) -> dict:
88 | """Gets full season schedule for specified team.
89 |
90 | Args:
91 | team_abbr (str): Three-letter team abbreviation (e.g., BUF, TOR)
92 | season (str): Season in YYYYYYYY format (e.g., 20232024)
93 |
94 | Returns:
95 | dict: Complete season schedule data including metadata.
96 | """
97 | request = self.client.get(resource=f"club-schedule-season/{team_abbr}/{season}")
98 |
99 | return request.json()
100 |
101 | def schedule_calendar(self, date: str) -> dict:
102 | """Gets schedule in calendar format for specified date. Im not really sure
103 | how this is diff from the other endppoints.
104 |
105 | Args:
106 | date (str): Date in YYYY-MM-DD format (e.g., 2023-11-23)
107 |
108 | Returns:
109 | dict: Calendar-formatted schedule data.
110 |
111 | Example:
112 | API endpoint: https://api-web.nhle.com/v1/schedule-calendar/2023-11-08
113 | """
114 | return self.client.get(resource=f"schedule-calendar/{date}").json()
115 |
--------------------------------------------------------------------------------
/nhlpy/api/standings.py:
--------------------------------------------------------------------------------
1 | import importlib.resources
2 |
3 | from typing import List, Optional
4 |
5 |
6 | class Standings:
7 | def __init__(self, http_client):
8 | self.client = http_client
9 |
10 | def get_standings(self, date: Optional[str] = None, season: Optional[str] = None, cache=True) -> dict:
11 | """Gets league standings for a specified season or date.
12 |
13 | Retrieves NHL standings either for a specific date or for the end of a season.
14 | If both parameters are provided, season takes precedence.
15 |
16 | Args:
17 | date (str, optional): Date in YYYY-MM-DD format. Defaults to current date.
18 | season (str, optional): Season identifier to get final standings.
19 | Takes precedence over date parameter if both are provided.
20 | cache (bool, optional, deprecated): When True, loads data from local cache instead of API.
21 | Note: Cache data may become outdated if not regularly updated.
22 | Defaults to False.
23 |
24 | Returns:
25 | dict: Dictionary containing league standings data
26 | """
27 |
28 | # We need to look up the last date of the season and use that as the date, since it doesnt seem to take
29 | # season as a param.
30 | if season:
31 | if cache:
32 | # load json from data/seasonal_information_manifest.json
33 | import json
34 |
35 | data_resource = importlib.resources.files("nhlpy") / "data"
36 | manifest_data = json.loads((data_resource / "seasonal_information_manifest.json").read_text())
37 | seasons = manifest_data.get("seasons", [])
38 | else:
39 | seasons = self.season_standing_manifest()
40 |
41 | season_data = next((s for s in seasons if s.get("id") == int(season)), None)
42 | if not season_data:
43 | raise ValueError(f"Invalid Season Id {season}")
44 | date = season_data.get("standingsEnd")
45 |
46 | res = date if date else "now"
47 |
48 | return self.client.get(resource=f"standings/{res}").json()
49 |
50 | def season_standing_manifest(self) -> List[dict]:
51 | """Gets metadata for all NHL seasons.
52 | Returns information about what seems like every season. Start date, end date, etc.
53 |
54 | Args:
55 | None
56 |
57 | Returns:
58 | dict: Season metadata including dates, conference/division usage, and scoring rules.
59 |
60 | Example:
61 | Response format:
62 | [{
63 | "id": 20232024,
64 | "conferencesInUse": true,
65 | "divisionsInUse": true,
66 | "pointForOTlossInUse": true,
67 | "regulationWinsInUse": true,
68 | "rowInUse": true,
69 | "standingsEnd": "2023-11-10",
70 | "standingsStart": "2023-10-10",
71 | "tiesInUse": false,
72 | "wildcardInUse": true
73 | }]
74 | """
75 | response = self.client.get(resource="standings-season").json()
76 | return response.get("seasons", [])
77 |
--------------------------------------------------------------------------------
/nhlpy/api/stats.py:
--------------------------------------------------------------------------------
1 | import json
2 | from typing import List
3 |
4 | from nhlpy.api.query.builder import QueryContext
5 | from nhlpy.api.query.filters import _goalie_stats_sorts
6 | from nhlpy.api.query.sorting.sorting_options import SortingOptions
7 | from nhlpy.http_client import HttpClient
8 |
9 |
10 | class Stats:
11 | def __init__(self, http_client: HttpClient):
12 | self.client = http_client
13 |
14 | def gametypes_per_season_directory_by_team(self, team_abbr: str) -> dict:
15 | """Gets all game types played by a team throughout their history.
16 |
17 | A dictionary containing game types for each season the team has existed in the league.
18 |
19 | Args:
20 | team_abbr (str): The 3 letter abbreviation of the team (e.g., BUF, TOR)
21 |
22 | Returns:
23 | dict: A mapping of seasons to game types played by the team
24 |
25 | Example:
26 | https://api-web.nhle.com/v1/club-stats-season/TOR
27 |
28 | [
29 | {'season': 20242025, 'gameTypes': [2]},
30 | {'season': 20232024, 'gameTypes': [2, 3]},
31 | {'season': 20222023, 'gameTypes': [2, 3]},
32 | {'season': 20212022, 'gameTypes': [2, 3]},
33 | ...
34 | ]
35 |
36 | """
37 | return self.client.get(resource=f"club-stats-season/{team_abbr}").json()
38 |
39 | def player_career_stats(self, player_id: str) -> dict:
40 | """Gets a player's career statistics and biographical information.
41 |
42 | Retrieves comprehensive player data including career stats and personal details from the NHL API.
43 | API endpoint example: https://api-web.nhle.com/v1/player/8481528/landing
44 |
45 | Args:
46 | player_id (str): The unique identifier for the NHL player
47 |
48 | Returns:
49 | dict: A dictionary containing the player's career statistics and personal information
50 |
51 | Example:
52 | Full Example: https://github.com/coreyjs/nhl-api-py/wiki/Player-Career-Stats-%E2%80%90-Example-Payload
53 |
54 | {'playerId': 8478402,
55 | 'isActive': True,
56 | 'currentTeamId': 22,
57 | 'currentTeamAbbrev': 'EDM',
58 | 'fullTeamName': {'default': 'Edmonton Oilers', 'fr': "Oilers d'Edmonton"},
59 | 'teamCommonName': {'default': 'Oilers'},
60 | 'teamPlaceNameWithPreposition': {'default': 'Edmonton', 'fr': "d'Edmonton"},
61 | 'firstName': {'default': 'Connor'},
62 | 'lastName': {'default': 'McDavid'},
63 | 'badges': [{'logoUrl': {'default': 'https://assets.nhle.com/badges/4n_face-off.svg',
64 | 'fr': 'https://assets.nhle.com/badges/4n_face-off_fr.svg'},
65 | 'title': {'default': '4 Nations Face-Off',
66 | 'fr': 'Confrontation Des 4 Nations'}}],
67 | 'teamLogo': 'https://assets.nhle.com/logos/nhl/svg/EDM_light.svg',
68 | 'sweaterNumber': 97,
69 | 'position': 'C',
70 | """
71 | return self.client.get(resource=f"player/{player_id}/landing").json()
72 |
73 | def player_game_log(self, player_id: str, season_id: str, game_type: int) -> List[dict]:
74 | """Gets a player's game log for a specific season and game type.
75 |
76 | Retrieves detailed game-by-game statistics for a player during a specified season and game type.
77 |
78 | Args:
79 | game_type (int): The type of games to retrieve:
80 | 1: Preseason
81 | 2: Regular season
82 | 3: Playoffs
83 | season_id (str): The season identifier in YYYYYYYY format (e.g., "20222023", "20232024")
84 | player_id (str): The unique identifier for the NHL player
85 |
86 | Returns:
87 | dict: A dictionary containing the player's game-by-game statistics for the specified parameters
88 |
89 | Example:
90 | Full example here https://github.com/coreyjs/nhl-api-py/wiki/Stats.Player-Game-Log-%E2%80%90-Example-Response
91 | [
92 | {'gameId': 2024020641,
93 | 'teamAbbrev': 'EDM',
94 | 'homeRoadFlag': 'R',
95 | 'gameDate': '2025-01-07',
96 | 'goals': 1,
97 | 'assists': 0,
98 | 'commonName': {'default': 'Oilers'},
99 | 'opponentCommonName': {'default': 'Bruins'},
100 | 'points': 1,
101 | 'plusMinus': 0,
102 | 'powerPlayGoals': 1,
103 | 'powerPlayPoints': 1,
104 | 'gameWinningGoals': 0,
105 | 'otGoals': 0,
106 | 'shots': 5,
107 | 'shifts': 18,
108 | 'shorthandedGoals': 0,
109 | 'shorthandedPoints': 0,
110 | 'opponentAbbrev': 'BOS',
111 | 'pim': 0,
112 | 'toi': '18:04'},
113 | ...
114 | ]
115 | """
116 | data = self.client.get(resource=f"player/{player_id}/game-log/{season_id}/{game_type}").json()
117 | return data.get("gameLog", [])
118 |
119 | def team_summary(
120 | self,
121 | start_season: str,
122 | end_season: str,
123 | game_type_id: int = 2,
124 | is_game: bool = False,
125 | is_aggregate: bool = False,
126 | sort_expr: List[dict] = None,
127 | start: int = 0,
128 | limit: int = 50,
129 | fact_cayenne_exp: str = "gamesPlayed>1",
130 | default_cayenne_exp: str = None,
131 | ) -> List[dict]:
132 | """Retrieves team summary statistics across one or more seasons.
133 |
134 | Gets aggregated team statistics for a specified range of seasons with optional filtering and sorting.
135 |
136 | Args:
137 | start_season (str): Beginning of season range in YYYYYYYY format (e.g., "20202021").
138 | For single season queries, set equal to end_season.
139 | end_season (str): End of season range in YYYYYYYY format (e.g., "20212022")
140 | game_type_id (int, optional): Type of games to include:
141 | 2: Regular season (default)
142 | 3: Playoffs
143 | 1: Preseason
144 | is_game (bool, optional): Defaults False. (dev notes: not sure what this is, its part of the api call)
145 | is_aggregate (bool, optional): Defaults False. Whether to aggregate the statistics
146 | sort_expr (List[dict], optional): List of sorting criteria. Defaults to:
147 | [
148 | {"property": "points", "direction": "DESC"},
149 | {"property": "wins", "direction": "DESC"},
150 | {"property": "teamId", "direction": "ASC"}
151 | ]
152 | start (int, optional): Starting index for pagination. Defaults to 0
153 | limit (int, optional): Maximum number of results to return. Defaults to 50
154 | fact_cayenne_exp (str, optional): Apache Cayenne filter expression.
155 | Defaults to 'gamesPlayed>=1'
156 | default_cayenne_exp (str, optional): Additional Apache Cayenne filter.
157 | Example: "gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024"
158 | If provided, overrides the automatically generated expression.
159 |
160 | Returns:
161 | List[dict]: List of dictionaries containing team summary statistics
162 |
163 | Examples:
164 | Full Response Example: https://github.com/coreyjs/nhl-api-py/wiki/Stats.Team-Summary-%E2%80%90-Example-Response
165 | c.stats.team_summary(start_season="20202021", end_season="20212022", game_type_id=2)
166 | c.stats.team_summary(start_season="20202021", end_season="20212022")
167 |
168 | [{'faceoffWinPct': 0.48235,
169 | 'gamesPlayed': 82,
170 | 'goalsAgainst': 242,
171 | 'goalsAgainstPerGame': 2.95121,
172 | 'goalsFor': 337,
173 | 'goalsForPerGame': 4.10975,
174 | 'losses': 18,
175 | 'otLosses': 6,
176 | 'penaltyKillNetPct': 0.841698,
177 | 'penaltyKillPct': 0.795367,
178 | 'pointPct': 0.7439,
179 | 'points': 122,
180 | 'powerPlayNetPct': 0.21374,
181 | 'powerPlayPct': 0.244274,
182 | 'regulationAndOtWins': 55,
183 | 'seasonId': 20212022,
184 | 'shotsAgainstPerGame': 30.67073,
185 | 'shotsForPerGame': 37.34146,
186 | 'teamFullName': 'Florida Panthers',
187 | 'teamId': 13,
188 | 'ties': None,
189 | 'wins': 58,
190 | 'winsInRegulation': 42,
191 | 'winsInShootout': 3},
192 | ... ]
193 | """
194 | q_params = {
195 | "isAggregate": is_aggregate,
196 | "isGame": is_game,
197 | "start": start,
198 | "limit": limit,
199 | "factCayenneExp": fact_cayenne_exp,
200 | }
201 |
202 | if not sort_expr:
203 | sort_expr = [
204 | {"property": "points", "direction": "DESC"},
205 | {"property": "wins", "direction": "DESC"},
206 | {"property": "teamId", "direction": "ASC"},
207 | ]
208 | q_params["sort"] = json.dumps(sort_expr)
209 |
210 | if not default_cayenne_exp:
211 | default_cayenne_exp = f"gameTypeId={game_type_id} and seasonId<={end_season} and seasonId>={start_season}"
212 | q_params["cayenneExp"] = default_cayenne_exp
213 |
214 | return self.client.get_by_url("https://api.nhle.com/stats/rest/en/team/summary", query_params=q_params).json()[
215 | "data"
216 | ]
217 |
218 | def skater_stats_summary_simple(
219 | self,
220 | start_season: str,
221 | end_season: str,
222 | franchise_id: str = None,
223 | game_type_id: int = 2,
224 | aggregate: bool = False,
225 | sort_expr: List[dict] = None,
226 | start: int = 0,
227 | limit: int = 25,
228 | fact_cayenne_exp: str = "gamesPlayed>=1",
229 | default_cayenne_exp: str = None,
230 | ) -> List[dict]:
231 | """Gets simplified skater statistics summary for specified seasons and franchises.
232 |
233 | Retrieves aggregated or season-by-season skating statistics with optional filtering and sorting.
234 |
235 |
236 | Args:
237 | start_season (str): Beginning of season range in YYYYYYYY format (e.g., "20202021")
238 | end_season (str): End of season range in YYYYYYYY format
239 | franchise_id (str, optional): Franchise identifier specific to /stats APIs.
240 | Note: Different from team_id used in other endpoints
241 | game_type_id (int, optional): Type of games to include:
242 | 2: Regular season (Default)
243 | 3: Playoffs
244 | 1: Preseason
245 | aggregate (bool, optional): When True, combines multiple seasons' data per player.
246 | When False, returns separate entries per season. Defaults to False.
247 | sort_expr (List[dict], optional): List of sorting criteria. Defaults to:
248 | [
249 | {"property": "points", "direction": "DESC"},
250 | {"property": "gamesPlayed", "direction": "ASC"},
251 | {"property": "playerId", "direction": "ASC"}
252 | ]
253 | start (int, optional): Starting index for pagination
254 | limit (int, optional): Maximum number of results to return. Defaults to 25.
255 | fact_cayenne_exp (str, optional): Base filter criteria. Defaults to 'gamesPlayed>=1'
256 | Can be modified for custom filtering
257 | default_cayenne_exp (str, optional): Additional filter expression
258 |
259 | Returns:
260 | List[dict]: List of dictionaries containing skater statistics
261 |
262 | Examples:
263 | Full Response Example: https://github.com/coreyjs/nhl-api-py/wiki/Stats.Skater-Stats-Summary-Simple
264 | c.stats.skater_stats_summary_simple(start_season="20232024", end_season="20232024")
265 | c.stats.skater_stats_summary_simple(franchise_id=10, start_season="20232024", end_season="20232024")
266 |
267 | [{'assists': 71,
268 | 'evGoals': 38,
269 | 'evPoints': 75,
270 | 'faceoffWinPct': 0.1,
271 | 'gameWinningGoals': 5,
272 | 'gamesPlayed': 82,
273 | 'goals': 49,
274 | 'lastName': 'Panarin',
275 | 'otGoals': 1,
276 | 'penaltyMinutes': 24,
277 | 'playerId': 8478550,
278 | 'plusMinus': 18,
279 | 'points': 120,
280 | 'pointsPerGame': 1.46341,
281 | 'positionCode': 'L',
282 | 'ppGoals': 11,
283 | 'ppPoints': 44,
284 | 'seasonId': 20232024,
285 | 'shGoals': 0,
286 | 'shPoints': 1,
287 | 'shootingPct': 0.16171,
288 | 'shootsCatches': 'R',
289 | 'shots': 303,
290 | 'skaterFullName': 'Artemi Panarin',
291 | 'teamAbbrevs': 'NYR',
292 | 'timeOnIcePerGame': 1207.1341},
293 | ... ]
294 | """
295 | q_params = {
296 | "isAggregate": aggregate,
297 | "isGame": False,
298 | "start": start,
299 | "limit": limit,
300 | "factCayenneExp": fact_cayenne_exp,
301 | }
302 |
303 | if not sort_expr:
304 | sort_expr = [
305 | {"property": "points", "direction": "DESC"},
306 | {"property": "gamesPlayed", "direction": "ASC"},
307 | {"property": "playerId", "direction": "ASC"},
308 | ]
309 | q_params["sort"] = json.dumps(sort_expr)
310 |
311 | if not default_cayenne_exp:
312 | default_cayenne_exp = f"gameTypeId={game_type_id} and seasonId<={end_season} and seasonId>={start_season}"
313 | if franchise_id:
314 | default_cayenne_exp = f"franchiseId={franchise_id} and {default_cayenne_exp}"
315 | q_params["cayenneExp"] = default_cayenne_exp
316 |
317 | return self.client.get_by_url("https://api.nhle.com/stats/rest/en/skater/summary", query_params=q_params).json()[
318 | "data"
319 | ]
320 |
321 | def skater_stats_with_query_context(
322 | self,
323 | query_context: QueryContext,
324 | report_type: str,
325 | sort_expr: List[dict] = None,
326 | aggregate: bool = False,
327 | start: int = 0,
328 | limit: int = 25,
329 | ) -> dict:
330 | """Retrieves skater statistics using a query context and specified report type.
331 |
332 | Gets detailed skater statistics with customizable filtering, sorting, and aggregation options.
333 |
334 | Args:
335 | query_context (QueryContext): Context object containing query parameters
336 | report_type (str): Type of statistical report to retrieve:
337 | 'summary', 'bios', 'faceoffpercentages', 'faceoffwins',
338 | 'goalsForAgainst', 'realtime', 'penalties', 'penaltykill',
339 | 'penaltyShots', 'powerplay', 'puckPossessions',
340 | 'summaryshooting', 'percentages', 'scoringRates',
341 | 'scoringpergame', 'shootout', 'shottype', 'timeonice'
342 | sort_expr (List[dict], optional): List of sorting criteria. Defaults to None.
343 | Example format:
344 | [
345 | {"property": "points", "direction": "DESC"},
346 | {"property": "gamesPlayed", "direction": "ASC"},
347 | {"property": "playerId", "direction": "ASC"}
348 | ]
349 | aggregate (bool, optional): When True, combines multiple seasons' data per player.
350 | When False, returns separate entries per season. Defaults to False.
351 | start (int, optional): Starting index for pagination. Defaults to 0.
352 | limit (int, optional): Maximum number of results to return. Defaults to 25.
353 |
354 | Returns:
355 | dict: Dictionary containing skater statistics based on the specified report type
356 |
357 | Example:
358 | Full example here: https://github.com/coreyjs/nhl-api-py/wiki/Stats.Skater-Stats-with-Query-Context
359 |
360 | filters = [
361 | GameTypeQuery(game_type="2"),
362 | DraftQuery(year="2020", draft_round="2"),
363 | SeasonQuery(season_start="20202021", season_end="20232024"),
364 | PositionQuery(position=PositionTypes.ALL_FORWARDS)
365 | ]
366 |
367 | query_builder = QueryBuilder()
368 | query_context: QueryContext = query_builder.build(filters=filters)
369 |
370 | data = client.stats.skater_stats_with_query_context(
371 | report_type='summary',
372 | query_context=query_context,
373 | aggregate=True
374 | )
375 |
376 | Response:
377 | {'data': [{'assists': 42,
378 | 'evGoals': 35,
379 | 'evPoints': 70,
380 | 'faceoffWinPct': 0.33333,
381 | 'gameWinningGoals': 6,
382 | 'gamesPlayed': 161,
383 | 'goals': 40,
384 | 'lastName': 'Peterka',
385 | 'otGoals': 0,
386 | 'penaltyMinutes': 54,
387 | 'playerId': 8482175,
388 | 'plusMinus': -5,
389 | 'points': 82,
390 | 'pointsPerGame': 0.50931,
391 | 'positionCode': 'R',
392 | 'ppGoals': 5,
393 | 'ppPoints': 12,
394 | 'shGoals': 0,
395 | 'shPoints': 0,
396 | 'shootingPct': 0.11299,
397 | 'shootsCatches': 'L',
398 | 'shots': 354,
399 | 'skaterFullName': 'JJ Peterka',
400 | 'timeOnIcePerGame': 904.5714},
401 | ...]
402 | """
403 | q_params = {
404 | "isAggregate": aggregate,
405 | "isGame": False,
406 | "start": start,
407 | "limit": limit,
408 | "factCayenneExp": query_context.fact_query,
409 | }
410 |
411 | if not sort_expr:
412 | sort_expr = SortingOptions.get_default_sorting_for_report(report_type)
413 |
414 | q_params["sort"] = json.dumps(sort_expr)
415 | q_params["cayenneExp"] = query_context.query_str
416 | return self.client.get_by_url(
417 | f"https://api.nhle.com/stats/rest/en/skater/{report_type}", query_params=q_params
418 | ).json()
419 |
420 | def goalie_stats_summary_simple(
421 | self,
422 | start_season: str,
423 | end_season: str = None,
424 | stats_type: str = "summary",
425 | game_type_id: int = 2,
426 | franchise_id: str = None,
427 | aggregate: bool = False,
428 | sort_expr: List[dict] = None,
429 | start: int = 0,
430 | limit: int = 25,
431 | fact_cayenne_exp: str = None,
432 | default_cayenne_exp: str = None,
433 | ) -> List[dict]:
434 | """Retrieves goalie statistics with various filtering and aggregation options.
435 |
436 | A simple endpoint that returns different types of goalie statistics based on the specified stats_type parameter.
437 |
438 | Args:
439 | start_season (str): Beginning of season range in YYYYYYYY format (e.g., "20202021")
440 | end_season (str, optional): End of season range in YYYYYYYY format.
441 | Defaults to start_season if not provided.
442 | stats_type (str): Type of statistics to retrieve:
443 | 'summary', 'advanced', 'bios', 'daysrest', 'penaltyShots',
444 | 'savesByStrength', 'shootout', 'startedVsRelieved'
445 | game_type_id (int, optional): Type of games to include:
446 | 2: Regular season
447 | 3: Playoffs
448 | 1: Preseason (tentative)
449 | franchise_id (str, optional): Franchise identifier to filter results
450 | aggregate (bool, optional): When True, combines multiple seasons' data per goalie.
451 | When False, returns separate entries per season. Defaults to False.
452 | sort_expr (List[dict], optional): List of sorting criteria. Uses EDGE stats site defaults.
453 | Can be customized using any properties from the response payload.
454 | start (int, optional): Starting index for pagination
455 | limit (int, optional): Defaults to 25. Maximum number of results to return
456 | fact_cayenne_exp (str, optional): Base filter criteria
457 | default_cayenne_exp (str, optional): Additional filter expression
458 |
459 | Returns:
460 | dict: Dictionary containing goalie statistics based on the specified parameters
461 |
462 | Example:
463 | client.stats.goalie_stats_summary_simple(start_season="20242025", stats_type="summary")
464 |
465 | [{'assists': 0,
466 | 'gamesPlayed': 33,
467 | 'gamesStarted': 33,
468 | 'goalieFullName': 'Connor Hellebuyck',
469 | 'goals': 0,
470 | 'goalsAgainst': 69,
471 | 'goalsAgainstAverage': 2.08485,
472 | 'lastName': 'Hellebuyck',
473 | 'losses': 6,
474 | 'otLosses': 2,
475 | 'penaltyMinutes': 0,
476 | 'playerId': 8476945,
477 | 'points': 0,
478 | 'savePct': 0.92612,
479 | 'saves': 865,
480 | 'seasonId': 20242025,
481 | 'shootsCatches': 'L',
482 | 'shotsAgainst': 934,
483 | 'shutouts': 5,
484 | 'teamAbbrevs': 'WPG',
485 | 'ties': None,
486 | 'timeOnIce': 119145,
487 | 'wins': 25},
488 | """
489 | q_params = {
490 | "isAggregate": aggregate,
491 | "isGame": False,
492 | "start": start,
493 | "limit": limit,
494 | "factCayenneExp": fact_cayenne_exp,
495 | }
496 |
497 | if end_season is None:
498 | end_season = start_season
499 |
500 | if not sort_expr:
501 | sort_expr = _goalie_stats_sorts(report=stats_type)
502 |
503 | q_params["sort"] = json.dumps(sort_expr)
504 |
505 | if not default_cayenne_exp:
506 | default_cayenne_exp = f"gameTypeId={game_type_id} and seasonId<={end_season} and seasonId>={start_season}"
507 |
508 | if franchise_id:
509 | default_cayenne_exp = f"franchiseId={franchise_id} and {default_cayenne_exp}"
510 |
511 | q_params["cayenneExp"] = default_cayenne_exp
512 |
513 | response = self.client.get_by_url(
514 | f"https://api.nhle.com/stats/rest/en/goalie/{stats_type}", query_params=q_params
515 | ).json()
516 | return response.get("data", [])
517 |
--------------------------------------------------------------------------------
/nhlpy/api/teams.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from nhlpy.http_client import HttpClient
4 |
5 |
6 | class Teams:
7 | def __init__(self, http_client: HttpClient) -> None:
8 | self.client = http_client
9 | self.base_url = "https://api.nhle.com"
10 | self.api_ver = "/stats/rest/"
11 |
12 | def teams_info(self, date: str = "now") -> List[dict]:
13 | """Get a list of all NHL teams with their conference, division, and franchise information.
14 |
15 | Args:
16 | date (str, optional): Date in format YYYY-MM-DD. Defaults to "now".
17 | Note that while the NHL API uses "now" to default to the current date,
18 | during preseason this may default to last year's season. To get accurate
19 | teams for the current season, supply a date (YYYY-MM-DD) at the start of
20 | the upcoming season. For example:
21 | - 2024-04-18 for season 2023-2024
22 | - 2024-10-04 for season 2024-2025
23 |
24 | Returns:
25 | dict: List of dictionaries containing team information including conference,
26 | division, and franchise ID. Data is aggregated from the current standings
27 | API and joined with franchise information.
28 |
29 | Note:
30 | Updated in 2.10.0: Now pulls from current standings API, aggregates team
31 | conference/division data, and joins with franchise ID. This workaround is
32 | necessary due to NHL API limitations preventing this data from being retrieved
33 | in a single request.
34 | """
35 |
36 | teams_info = self.client.get_by_url(full_resource=f"https://api-web.nhle.com/v1/standings/{date}").json()[
37 | "standings"
38 | ]
39 | teams = []
40 | for i in teams_info:
41 | team_name = i.get("teamName", {}).get("default", "")
42 | team_common_name = i.get("teamCommonName", {}).get("default", "")
43 | team_abbrev = i.get("teamAbbrev", {}).get("default", "")
44 |
45 | team = {
46 | "conference": {"abbr": i.get("conferenceAbbrev", ""), "name": i.get("conferenceName", "")},
47 | "division": {"abbr": i.get("divisionAbbrev", ""), "name": i.get("divisionName", "")},
48 | "name": team_name,
49 | "common_name": team_common_name,
50 | "abbr": team_abbrev,
51 | "logo": i.get("teamLogo", ""),
52 | }
53 | teams.append(team)
54 |
55 | # We also need to get "franchise_id", which is different than team_id. This is used in the stats.
56 | franchises = self.all_franchises()
57 | for f in franchises:
58 | franchise_full_name = f.get("fullName", "")
59 | franchise_id = f.get("id")
60 |
61 | for team in teams:
62 | team_name = team.get("name", "")
63 |
64 | if "Canadiens" in franchise_full_name and "Canadiens" in team_name:
65 | team["franchise_id"] = franchise_id
66 | continue
67 |
68 | if franchise_full_name == team_name:
69 | team["franchise_id"] = franchise_id
70 |
71 | return teams
72 |
73 | def roster(self, team_abbr: str, season: str) -> dict:
74 | """Returns the roster for the given team and season.
75 |
76 | Args:
77 | team_abbr (str): Team abbreviation (e.g., BUF, TOR)
78 | season (str): Season in format YYYYYYYY (e.g., 20202021, 20212022)
79 |
80 | Returns:
81 | Not specified in original docstring
82 | """
83 | return self.client.get(resource=f"roster/{team_abbr}/{season}").json()
84 |
85 | def all_franchises(self) -> List[dict]:
86 | """Returns a list of all past and current NHL franchises.
87 |
88 | Returns:
89 | List of all NHL franchises, including historical/defunct teams.
90 | """
91 | response = self.client.get_by_url(full_resource="https://api.nhle.com/stats/rest/en/franchise").json()
92 | return response.get("data", [])
93 |
--------------------------------------------------------------------------------
/nhlpy/config.py:
--------------------------------------------------------------------------------
1 | class ClientConfig:
2 | def __init__(
3 | self, verbose: bool = False, timeout: int = 10, ssl_verify: bool = True, follow_redirects: bool = True
4 | ) -> None:
5 | self.verbose = verbose
6 | self.timeout = timeout
7 | self.ssl_verify = ssl_verify
8 | self.follow_redirects = follow_redirects
9 |
10 | self.api_web_base_url = "https://api-web.nhle.com"
11 | self.api_base_url = "https://api.nhle.com"
12 | self.api_web_api_ver = "/v1/"
13 |
--------------------------------------------------------------------------------
/nhlpy/data/team_stat_ids.json:
--------------------------------------------------------------------------------
1 | {
2 | "data": [
3 | {
4 | "id": 1,
5 | "fullName": "Montréal Canadiens",
6 | "teamCommonName": "Canadiens",
7 | "teamPlaceName": "Montréal"
8 | },
9 | {
10 | "id": 2,
11 | "fullName": "Montreal Wanderers",
12 | "teamCommonName": "Wanderers",
13 | "teamPlaceName": "Montreal"
14 | },
15 | {
16 | "id": 3,
17 | "fullName": "St. Louis Eagles",
18 | "teamCommonName": "Eagles",
19 | "teamPlaceName": "St. Louis"
20 | },
21 | {
22 | "id": 4,
23 | "fullName": "Hamilton Tigers",
24 | "teamCommonName": "Tigers",
25 | "teamPlaceName": "Hamilton"
26 | },
27 | {
28 | "id": 5,
29 | "fullName": "Toronto Maple Leafs",
30 | "teamCommonName": "Maple Leafs",
31 | "teamPlaceName": "Toronto"
32 | },
33 | {
34 | "id": 6,
35 | "fullName": "Boston Bruins",
36 | "teamCommonName": "Bruins",
37 | "teamPlaceName": "Boston"
38 | },
39 | {
40 | "id": 7,
41 | "fullName": "Montreal Maroons",
42 | "teamCommonName": "Maroons",
43 | "teamPlaceName": "Montreal"
44 | },
45 | {
46 | "id": 8,
47 | "fullName": "Brooklyn Americans",
48 | "teamCommonName": "Americans",
49 | "teamPlaceName": "Brooklyn"
50 | },
51 | {
52 | "id": 9,
53 | "fullName": "Philadelphia Quakers",
54 | "teamCommonName": "Quakers",
55 | "teamPlaceName": "Philadelphia"
56 | },
57 | {
58 | "id": 10,
59 | "fullName": "New York Rangers",
60 | "teamCommonName": "Rangers",
61 | "teamPlaceName": "New York"
62 | },
63 | {
64 | "id": 11,
65 | "fullName": "Chicago Blackhawks",
66 | "teamCommonName": "Blackhawks",
67 | "teamPlaceName": "Chicago"
68 | },
69 | {
70 | "id": 12,
71 | "fullName": "Detroit Red Wings",
72 | "teamCommonName": "Red Wings",
73 | "teamPlaceName": "Detroit"
74 | },
75 | {
76 | "id": 13,
77 | "fullName": "Cleveland Barons",
78 | "teamCommonName": "Barons",
79 | "teamPlaceName": "Cleveland"
80 | },
81 | {
82 | "id": 14,
83 | "fullName": "Los Angeles Kings",
84 | "teamCommonName": "Kings",
85 | "teamPlaceName": "Los Angeles"
86 | },
87 | {
88 | "id": 15,
89 | "fullName": "Dallas Stars",
90 | "teamCommonName": "Stars",
91 | "teamPlaceName": "Dallas"
92 | },
93 | {
94 | "id": 16,
95 | "fullName": "Philadelphia Flyers",
96 | "teamCommonName": "Flyers",
97 | "teamPlaceName": "Philadelphia"
98 | },
99 | {
100 | "id": 17,
101 | "fullName": "Pittsburgh Penguins",
102 | "teamCommonName": "Penguins",
103 | "teamPlaceName": "Pittsburgh"
104 | },
105 | {
106 | "id": 18,
107 | "fullName": "St. Louis Blues",
108 | "teamCommonName": "Blues",
109 | "teamPlaceName": "St. Louis"
110 | },
111 | {
112 | "id": 19,
113 | "fullName": "Buffalo Sabres",
114 | "teamCommonName": "Sabres",
115 | "teamPlaceName": "Buffalo"
116 | },
117 | {
118 | "id": 20,
119 | "fullName": "Vancouver Canucks",
120 | "teamCommonName": "Canucks",
121 | "teamPlaceName": "Vancouver"
122 | },
123 | {
124 | "id": 21,
125 | "fullName": "Calgary Flames",
126 | "teamCommonName": "Flames",
127 | "teamPlaceName": "Calgary"
128 | },
129 | {
130 | "id": 22,
131 | "fullName": "New York Islanders",
132 | "teamCommonName": "Islanders",
133 | "teamPlaceName": "New York"
134 | },
135 | {
136 | "id": 23,
137 | "fullName": "New Jersey Devils",
138 | "teamCommonName": "Devils",
139 | "teamPlaceName": "New Jersey"
140 | },
141 | {
142 | "id": 24,
143 | "fullName": "Washington Capitals",
144 | "teamCommonName": "Capitals",
145 | "teamPlaceName": "Washington"
146 | },
147 | {
148 | "id": 25,
149 | "fullName": "Edmonton Oilers",
150 | "teamCommonName": "Oilers",
151 | "teamPlaceName": "Edmonton"
152 | },
153 | {
154 | "id": 26,
155 | "fullName": "Carolina Hurricanes",
156 | "teamCommonName": "Hurricanes",
157 | "teamPlaceName": "Carolina"
158 | },
159 | {
160 | "id": 27,
161 | "fullName": "Colorado Avalanche",
162 | "teamCommonName": "Avalanche",
163 | "teamPlaceName": "Colorado"
164 | },
165 | {
166 | "id": 28,
167 | "fullName": "Arizona Coyotes",
168 | "teamCommonName": "Coyotes",
169 | "teamPlaceName": "Arizona"
170 | },
171 | {
172 | "id": 29,
173 | "fullName": "San Jose Sharks",
174 | "teamCommonName": "Sharks",
175 | "teamPlaceName": "San Jose"
176 | },
177 | {
178 | "id": 30,
179 | "fullName": "Ottawa Senators",
180 | "teamCommonName": "Senators",
181 | "teamPlaceName": "Ottawa"
182 | },
183 | {
184 | "id": 31,
185 | "fullName": "Tampa Bay Lightning",
186 | "teamCommonName": "Lightning",
187 | "teamPlaceName": "Tampa Bay"
188 | },
189 | {
190 | "id": 32,
191 | "fullName": "Anaheim Ducks",
192 | "teamCommonName": "Ducks",
193 | "teamPlaceName": "Anaheim"
194 | },
195 | {
196 | "id": 33,
197 | "fullName": "Florida Panthers",
198 | "teamCommonName": "Panthers",
199 | "teamPlaceName": "Florida"
200 | },
201 | {
202 | "id": 34,
203 | "fullName": "Nashville Predators",
204 | "teamCommonName": "Predators",
205 | "teamPlaceName": "Nashville"
206 | },
207 | {
208 | "id": 35,
209 | "fullName": "Winnipeg Jets",
210 | "teamCommonName": "Jets",
211 | "teamPlaceName": "Winnipeg"
212 | },
213 | {
214 | "id": 36,
215 | "fullName": "Columbus Blue Jackets",
216 | "teamCommonName": "Blue Jackets",
217 | "teamPlaceName": "Columbus"
218 | },
219 | {
220 | "id": 37,
221 | "fullName": "Minnesota Wild",
222 | "teamCommonName": "Wild",
223 | "teamPlaceName": "Minnesota"
224 | },
225 | {
226 | "id": 38,
227 | "fullName": "Vegas Golden Knights",
228 | "teamCommonName": "Golden Knights",
229 | "teamPlaceName": "Vegas"
230 | },
231 | {
232 | "id": 39,
233 | "fullName": "Seattle Kraken",
234 | "teamCommonName": "Kraken",
235 | "teamPlaceName": "Seattle"
236 | },
237 | {
238 | "id": 40,
239 | "fullName": "Utah Hockey Club",
240 | "teamCommonName": "Hockey Club",
241 | "teamPlaceName": "Utah"
242 | }
243 | ],
244 | "total": 40
245 | }
--------------------------------------------------------------------------------
/nhlpy/data/teams_20232024.json:
--------------------------------------------------------------------------------
1 | {
2 | "teams": [
3 | { "id": "24", "abbreviation": "ANA", "name": "Anaheim Ducks" },
4 | { "id": "53", "abbreviation": "ARI", "name": "Arizona Coyotes" },
5 | { "id": "6", "abbreviation": "BOS", "name": "Boston Bruins" },
6 | { "id": "7", "abbreviation": "BUF", "name": "Buffalo Sabres" },
7 | { "id": "20", "abbreviation": "CGY", "name": "Calgary Flames" },
8 | { "id": "12", "abbreviation": "CAR", "name": "Carolina Hurricanes" },
9 | { "id": "16", "abbreviation": "CHI", "name": "Chicago Blackhawks" },
10 | { "id": "21", "abbreviation": "COL", "name": "Colorado Avalanche" },
11 | { "id": "29", "abbreviation": "CBJ", "name": "Columbus Blue Jackets" },
12 | { "id": "25", "abbreviation": "DAL", "name": "Dallas Stars" },
13 | { "id": "17", "abbreviation": "DET", "name": "Detroit Red Wings" },
14 | { "id": "22", "abbreviation": "EDM", "name": "Edmonton Oilers" },
15 | { "id": "13", "abbreviation": "FLA", "name": "Florida Panthers" },
16 | { "id": "26", "abbreviation": "LAK", "name": "Los Angeles Kings" },
17 | { "id": "30", "abbreviation": "MIN", "name": "Minnesota Wild" },
18 | { "id": "8", "abbreviation": "MTL", "name": "Montreal Canadiens" },
19 | { "id": "18", "abbreviation": "NSH", "name": "Nashville Predators" },
20 | { "id": "1", "abbreviation": "NJD", "name": "New Jersey Devils" },
21 | { "id": "2", "abbreviation": "NYI", "name": "New York Islanders" },
22 | { "id": "3", "abbreviation": "NYR", "name": "New York Rangers" },
23 | { "id": "9", "abbreviation": "OTT", "name": "Ottawa Senators" },
24 | { "id": "4", "abbreviation": "PHI", "name": "Philadelphia Flyers" },
25 | { "id": "5", "abbreviation": "PIT", "name": "Pittsburgh Penguins" },
26 | { "id": "28", "abbreviation": "SJS", "name": "San Jose Sharks" },
27 | { "id": "55", "abbreviation": "SEA", "name": "Seattle Kraken"},
28 | { "id": "19", "abbreviation": "STL", "name": "St. Louis Blues" },
29 | { "id": "14", "abbreviation": "TBL", "name": "Tampa Bay Lightning" },
30 | { "id": "10", "abbreviation": "TOR", "name": "Toronto Maple Leafs" },
31 | { "id": "23", "abbreviation": "VAN", "name": "Vancouver Canucks" },
32 | { "id": "54", "abbreviation": "VGK", "name": "Vegas Golden Knights" },
33 | { "id": "15", "abbreviation": "WSH", "name": "Washington Capitals" },
34 | { "id": "52", "abbreviation": "WPG", "name": "Winnipeg Jets" },
35 | { "id": "40", "abbreviation": "UTA", "name": "Utah Hockey Club"}
36 | ]
37 | }
38 |
--------------------------------------------------------------------------------
/nhlpy/http_client.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from typing import Optional
3 |
4 | import httpx
5 | import logging
6 |
7 |
8 | class NHLApiErrorCode(Enum):
9 | """Enum for NHL API specific error codes if any"""
10 |
11 | RESOURCE_NOT_FOUND = "RESOURCE_NOT_FOUND"
12 | RATE_LIMIT_EXCEEDED = "RATE_LIMIT_EXCEEDED"
13 | SERVER_ERROR = "SERVER_ERROR"
14 | BAD_REQUEST = "BAD_REQUEST"
15 | UNAUTHORIZED = "UNAUTHORIZED"
16 |
17 |
18 | class NHLApiException(Exception):
19 | """Base exception for NHL API errors"""
20 |
21 | def __init__(self, message: str, status_code: int, error_code: Optional[NHLApiErrorCode] = None):
22 | self.message = message
23 | self.status_code = status_code
24 | self.error_code = error_code
25 | super().__init__(self.message)
26 |
27 |
28 | class ResourceNotFoundException(NHLApiException):
29 | """Raised when a resource is not found (404)"""
30 |
31 | def __init__(self, message: str, status_code: int = 404):
32 | super().__init__(message, status_code, NHLApiErrorCode.RESOURCE_NOT_FOUND)
33 |
34 |
35 | class RateLimitExceededException(NHLApiException):
36 | """Raised when rate limit is exceeded (429)"""
37 |
38 | def __init__(self, message: str, status_code: int = 429):
39 | super().__init__(message, status_code, NHLApiErrorCode.RATE_LIMIT_EXCEEDED)
40 |
41 |
42 | class ServerErrorException(NHLApiException):
43 | """Raised for server errors (5xx)"""
44 |
45 | def __init__(self, message: str, status_code: int):
46 | super().__init__(message, status_code, NHLApiErrorCode.SERVER_ERROR)
47 |
48 |
49 | class BadRequestException(NHLApiException):
50 | """Raised for client errors (400)"""
51 |
52 | def __init__(self, message: str, status_code: int = 400):
53 | super().__init__(message, status_code, NHLApiErrorCode.BAD_REQUEST)
54 |
55 |
56 | class UnauthorizedException(NHLApiException):
57 | """Raised for authentication errors (401)"""
58 |
59 | def __init__(self, message: str, status_code: int = 401):
60 | super().__init__(message, status_code, NHLApiErrorCode.UNAUTHORIZED)
61 |
62 |
63 | class HttpClient:
64 | def __init__(self, config) -> None:
65 | self._config = config
66 | if self._config.verbose:
67 | logging.basicConfig(level=logging.INFO)
68 | else:
69 | logging.basicConfig(level=logging.WARNING)
70 |
71 | def _handle_response(self, response: httpx.Response, url: str) -> None:
72 | """Handle different HTTP status codes and raise appropriate exceptions"""
73 |
74 | if response.is_success:
75 | return
76 |
77 | # Build error message
78 | error_message = f"Request to {url} failed"
79 | try:
80 | response_json = response.json()
81 | if isinstance(response_json, dict):
82 | error_detail = response_json.get("message")
83 | if error_detail:
84 | error_message = f"{error_message}: {error_detail}"
85 | except Exception:
86 | # If response isn't JSON or doesn't have a message field
87 | pass
88 |
89 | if response.status_code == 404:
90 | raise ResourceNotFoundException(error_message)
91 | elif response.status_code == 429:
92 | raise RateLimitExceededException(error_message)
93 | elif response.status_code == 400:
94 | raise BadRequestException(error_message)
95 | elif response.status_code == 401:
96 | raise UnauthorizedException(error_message)
97 | elif 500 <= response.status_code < 600:
98 | raise ServerErrorException(error_message, response.status_code)
99 | else:
100 | raise NHLApiException(f"Unexpected error: {error_message}", response.status_code)
101 |
102 | def get(self, resource: str) -> httpx.Response:
103 | """
104 | Private method to make a get request to the NHL API. This wraps the lib httpx functionality.
105 | :param resource:
106 | :return: httpx.Response
107 | :raises:
108 | ResourceNotFoundException: When the resource is not found
109 | RateLimitExceededException: When rate limit is exceeded
110 | ServerErrorException: When server returns 5xx error
111 | BadRequestException: When request is malformed
112 | UnauthorizedException: When authentication fails
113 | NHLApiException: For other unexpected errors
114 | """
115 | with httpx.Client(
116 | verify=self._config.ssl_verify, timeout=self._config.timeout, follow_redirects=self._config.follow_redirects
117 | ) as client:
118 | r: httpx.Response = client.get(
119 | url=f"{self._config.api_web_base_url}{self._config.api_web_api_ver}{resource}"
120 | )
121 |
122 | self._handle_response(r, resource)
123 | return r
124 |
125 | def get_by_url(self, full_resource: str, query_params: dict = None) -> httpx.Response:
126 | """
127 | Private method to make a get request to any HTTP resource. This wraps the lib httpx functionality.
128 | :param query_params:
129 | :param full_resource: The full resource to get.
130 | :return: httpx.Response
131 | :raises:
132 | ResourceNotFoundException: When the resource is not found
133 | RateLimitExceededException: When rate limit is exceeded
134 | ServerErrorException: When server returns 5xx error
135 | BadRequestException: When request is malformed
136 | UnauthorizedException: When authentication fails
137 | NHLApiException: For other unexpected errors
138 | """
139 | with httpx.Client(
140 | verify=self._config.ssl_verify, timeout=self._config.timeout, follow_redirects=self._config.follow_redirects
141 | ) as client:
142 | r: httpx.Response = client.get(url=full_resource, params=query_params)
143 |
144 | self._handle_response(r, full_resource)
145 | return r
146 |
--------------------------------------------------------------------------------
/nhlpy/nhl_client.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api import teams, standings, schedule, game_center, stats, misc, playoffs, helpers
2 | from nhlpy.http_client import HttpClient
3 | from nhlpy.config import ClientConfig
4 |
5 |
6 | class NHLClient:
7 | """
8 | This is the main class that is used to access the NHL API.
9 |
10 | You can instantiate this class and then access the various endpoints of the API,
11 | such as:
12 | client = NHLClient()
13 | client = NHLClient(verbose=True) # for a lil extra logging
14 | """
15 |
16 | def __init__(
17 | self, verbose: bool = False, timeout: int = 10, ssl_verify: bool = True, follow_redirects: bool = True
18 | ) -> None:
19 | """
20 | :param follow_redirects: bool. Some of these endpoints use redirects (ew). This is the case when using
21 | endpoints that use "/now" in them, which will redirect to todays data.
22 | :param verbose: bool, Defaults to False. Set to True for extra logging.
23 | :param timeout: int, Defaults to 10 seconds.
24 | :param ssl_verify: bool, Defaults to True. Set to false if you want to ignore SSL verification.
25 | """
26 | # This config type setup isnt doing what I thought it would. This will be reworked later on.
27 | self._config = ClientConfig(
28 | verbose=verbose, timeout=timeout, ssl_verify=ssl_verify, follow_redirects=follow_redirects
29 | )
30 | self._http_client = HttpClient(self._config)
31 |
32 | self.teams = teams.Teams(http_client=self._http_client)
33 | self.standings = standings.Standings(http_client=self._http_client)
34 | self.schedule = schedule.Schedule(http_client=self._http_client)
35 | self.game_center = game_center.GameCenter(http_client=self._http_client)
36 | self.stats = stats.Stats(http_client=self._http_client)
37 | self.misc = misc.Misc(http_client=self._http_client)
38 | self.playoffs = playoffs.Playoffs(http_client=self._http_client)
39 | self.helpers = helpers.Helpers(http_client=self._http_client)
40 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["poetry-core"]
3 | build-backend = "poetry.core.masonry.api"
4 |
5 | [tool.poetry]
6 | name = "nhl-api-py"
7 | version = "2.19.0"
8 | description = "NHL API (Updated for 2024/2025) and EDGE Stats. For standings, team stats, outcomes, player information. Contains each individual API endpoint as well as convience methods as well as pythonic query builder for more indepth EDGE stats."
9 | authors = ["Corey Schaf "]
10 | readme = "README.md"
11 | packages = [{include = "nhlpy"}]
12 | license = "GPL-3.0-or-later"
13 | homepage = "https://github.com/coreyjs/nhl-api-py"
14 | repository = "https://github.com/coreyjs/nhl-api-py"
15 | keywords = ["nhl", "api", "wrapper", "hockey", "sports", "edge", "edge stats", "edge analytics", "edge sports",
16 | "edge hockey", "edge nhl", "edge nhl stats", "edge nhl analytics", "edge nhl sports", "edge nhl hockey",
17 | "edge nhl data", "edge nhl data analytics", "edge nhl data stats", "edge nhl data sports", "edge nhl data hockey",
18 | "edge nhl data stats analytics", "edge nhl data stats sports", "edge nhl data stats hockey", "hockey ai", "hockey machine learning", "nhl ML", "nhl AI",
19 | "nhl machine learning", "nhl stats", "nhl analytics", "nhl sports", "nhl hockey", "nhl nhl", "nhl nhl stats", "nhl nhl analytics", "nhl nhl sports",
20 | "edge nhl data hockey stats"]
21 | classifiers = [
22 | "Development Status :: 5 - Production/Stable",
23 | "Intended Audience :: Developers",
24 | "Intended Audience :: Education",
25 | "License :: OSI Approved :: MIT License",
26 | "Programming Language :: Python :: 3",
27 | "Programming Language :: Python :: 3.9",
28 | "Programming Language :: Python :: 3.10",
29 | "Programming Language :: Python :: 3.11",
30 | "Programming Language :: Python :: 3.12",
31 | "Programming Language :: Python :: 3 :: Only",
32 | "Topic :: Software Development :: Libraries :: Python Modules",
33 | "Topic :: Software Development :: Libraries",
34 | "Topic :: Software Development :: Libraries :: Application Frameworks",
35 | "Topic :: Software Development :: Libraries :: Python Modules"
36 | ]
37 | include = [
38 | "nhlpy/data/*",
39 | ]
40 |
41 | [tool.poetry.dependencies]
42 | python = "^3.9"
43 | httpx = "*"
44 |
45 | [tool.poetry.group.dev.dependencies]
46 | pytest="^7.1.3"
47 | pytest-mock = "*"
48 | mypy = "*"
49 | ruff = "*"
50 | black = "*"
51 | ipykernel = "*"
52 |
53 | [tool.ruff]
54 | exclude = [
55 | ".bzr",
56 | ".direnv",
57 | ".eggs",
58 | ".git",
59 | ".git-rewrite",
60 | ".hg",
61 | ".mypy_cache",
62 | ".nox",
63 | ".pants.d",
64 | ".pytype",
65 | ".ruff_cache",
66 | ".svn",
67 | ".tox",
68 | ".venv",
69 | "__pypackages__",
70 | "_build",
71 | "buck-out",
72 | "build",
73 | "dist",
74 | "node_modules",
75 | "venv",
76 | ]
77 | line-length = 121
78 |
79 |
80 |
81 | [tool.black]
82 | line-length = 121
83 | indent = 4
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coreyjs/nhl-api-py/d0f71371893a29b3bc067ee12e293391a8d6319f/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from nhlpy.nhl_client import NHLClient
4 |
5 |
6 | @pytest.fixture(scope="function")
7 | def nhl_client() -> NHLClient:
8 | yield NHLClient()
9 |
--------------------------------------------------------------------------------
/tests/query/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coreyjs/nhl-api-py/d0f71371893a29b3bc067ee12e293391a8d6319f/tests/query/__init__.py
--------------------------------------------------------------------------------
/tests/query/filters/test_decision.py:
--------------------------------------------------------------------------------
1 | from pytest import raises
2 |
3 | from nhlpy.api.query import InvalidQueryValueException
4 | from nhlpy.api.query.filters.decision import DecisionQuery
5 |
6 |
7 | def test_win_outcome():
8 | decision = DecisionQuery(decision="W")
9 | assert decision.to_query() == "decision='W'"
10 |
11 |
12 | def test_loss_outcome():
13 | decision = DecisionQuery(decision="L")
14 | assert decision.to_query() == "decision='L'"
15 |
16 |
17 | def test_overtime_loss_outcome():
18 | decision = DecisionQuery(decision="O")
19 | assert decision.to_query() == "decision='O'"
20 |
21 |
22 | def test_invalid_data():
23 | decision = DecisionQuery(decision="A")
24 | with raises(InvalidQueryValueException):
25 | assert decision.validate() is False
26 |
--------------------------------------------------------------------------------
/tests/query/filters/test_draft.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.draft import DraftQuery
2 |
3 |
4 | def test_draft_year_with_round():
5 | draft = DraftQuery(year="2020", draft_round="2")
6 | assert draft.to_query() == "draftYear=2020 and draftRound=2"
7 |
8 |
9 | def test_draft_year_without_round():
10 | draft = DraftQuery(year="2020")
11 | assert draft.to_query() == "draftYear=2020"
12 |
--------------------------------------------------------------------------------
/tests/query/filters/test_experience.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.experience import ExperienceQuery
2 |
3 |
4 | def test_is_rookie():
5 | experience = ExperienceQuery(is_rookie=True)
6 | assert experience.to_query() == "isRookie='1'"
7 |
8 |
9 | def test_is_veteran():
10 | experience = ExperienceQuery(is_rookie=False)
11 | assert experience.to_query() == "isRookie='0'"
12 |
--------------------------------------------------------------------------------
/tests/query/filters/test_franchise.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.franchise import FranchiseQuery
2 |
3 |
4 | def test_franchise_query():
5 | franchise_query = FranchiseQuery(franchise_id="1")
6 | assert franchise_query.to_query() == "franchiseId=1"
7 |
--------------------------------------------------------------------------------
/tests/query/filters/test_game_type.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.game_type import GameTypeQuery
2 |
3 |
4 | def test_game_type_preseason():
5 | game_type = GameTypeQuery(game_type="1")
6 | assert game_type.to_query() == "gameTypeId=1"
7 |
8 |
9 | def test_game_type_regular():
10 | game_type = GameTypeQuery(game_type="2")
11 | assert game_type.to_query() == "gameTypeId=2"
12 |
--------------------------------------------------------------------------------
/tests/query/filters/test_home_road.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.home_road import HomeRoadQuery
2 |
3 |
4 | def test_home_game():
5 | home_road = HomeRoadQuery(home_road="H")
6 | assert home_road.to_query() == "homeRoad='H'"
7 |
8 |
9 | def test_road_game():
10 | home_road = HomeRoadQuery(home_road="R")
11 | assert home_road.to_query() == "homeRoad='R'"
12 |
--------------------------------------------------------------------------------
/tests/query/filters/test_nationality.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.nationality import NationalityQuery
2 |
3 |
4 | def test_nation_usa():
5 | nation = NationalityQuery(nation_code="USA")
6 | assert nation.to_query() == "nationalityCode='USA'"
7 |
--------------------------------------------------------------------------------
/tests/query/filters/test_position.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.position import PositionQuery, PositionTypes
2 |
3 |
4 | def test_centers():
5 | position = PositionQuery(position=PositionTypes.CENTER)
6 | assert position.to_query() == "positionCode='C'"
7 |
8 |
9 | def test_left_wings():
10 | position = PositionQuery(position=PositionTypes.LEFT_WING)
11 | assert position.to_query() == "positionCode='L'"
12 |
13 |
14 | def test_right_wings():
15 | position = PositionQuery(position=PositionTypes.RIGHT_WING)
16 | assert position.to_query() == "positionCode='R'"
17 |
18 |
19 | def test_forwards():
20 | position = PositionQuery(position=PositionTypes.ALL_FORWARDS)
21 | assert position.to_query() == "(positionCode='L' or positionCode='R' or positionCode='C')"
22 |
23 |
24 | def test_defense():
25 | position = PositionQuery(position=PositionTypes.DEFENSE)
26 | assert position.to_query() == "positionCode='D'"
27 |
--------------------------------------------------------------------------------
/tests/query/filters/test_season.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.season import SeasonQuery
2 |
3 |
4 | def test_season_query_range():
5 | season_query = SeasonQuery(season_start="20202021", season_end="20232024")
6 | assert season_query.to_query() == "seasonId >= 20202021 and seasonId <= 20232024"
7 |
8 |
9 | def test_season_query_same_year():
10 | season_query = SeasonQuery(season_start="20202021", season_end="20202021")
11 | assert season_query.to_query() == "seasonId >= 20202021 and seasonId <= 20202021"
12 |
13 |
14 | def test_season_query_wrong_range():
15 | season_query = SeasonQuery(season_start="20232024", season_end="20202020")
16 | assert season_query.to_query() == "seasonId >= 20232024 and seasonId <= 20202020"
17 |
--------------------------------------------------------------------------------
/tests/query/filters/test_shoot_catch.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.shoot_catch import ShootCatchesQuery
2 |
3 |
4 | def test_shoot_catch_l():
5 | shoot_catch = ShootCatchesQuery(shoot_catch="L")
6 | assert shoot_catch.to_query() == "shootsCatches='L'"
7 |
8 |
9 | def test_shoot_catch_r():
10 | shoot_catch = ShootCatchesQuery(shoot_catch="R")
11 | assert shoot_catch.to_query() == "shootsCatches='R'"
12 |
--------------------------------------------------------------------------------
/tests/query/filters/test_status.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.filters.status import StatusQuery
2 |
3 |
4 | def test_active_player():
5 | status = StatusQuery(is_active=True)
6 | assert status.to_query() == "active=1"
7 |
8 |
9 | def test_hall_of_fame_player():
10 | status = StatusQuery(is_hall_of_fame=True)
11 | assert status.to_query() == "isInHallOfFame=1"
12 |
13 |
14 | def test_active_and_hof_should_return_hof():
15 | status = StatusQuery(is_active=True, is_hall_of_fame=True)
16 | assert status.to_query() == "isInHallOfFame=1"
17 |
18 |
19 | def test_inactive_not_hof_returns_empty():
20 | status = StatusQuery(is_active=False, is_hall_of_fame=False)
21 | assert status.to_query() == ""
22 |
--------------------------------------------------------------------------------
/tests/query/test_builder.py:
--------------------------------------------------------------------------------
1 | from nhlpy.api.query.builder import QueryBuilder, QueryContext
2 | from nhlpy.api.query.filters.decision import DecisionQuery
3 | from nhlpy.api.query.filters.draft import DraftQuery
4 | from nhlpy.api.query.filters.game_type import GameTypeQuery
5 | from nhlpy.api.query.filters.position import PositionQuery, PositionTypes
6 | from nhlpy.api.query.filters.season import SeasonQuery
7 |
8 |
9 | def test_query_builder_empty_filters():
10 | qb = QueryBuilder()
11 | context: QueryContext = qb.build(filters=[])
12 |
13 | assert context.query_str == ""
14 |
15 |
16 | def test_query_builder_invalid_filter():
17 | qb = QueryBuilder()
18 | context: QueryContext = qb.build(filters=["invalid"])
19 |
20 | assert context.query_str == ""
21 |
22 |
23 | def test_qb_draft_year():
24 | qb = QueryBuilder()
25 | filters = [DraftQuery(year="2020", draft_round="2")]
26 | context: QueryContext = qb.build(filters=filters)
27 |
28 | assert context.query_str == "draftYear=2020 and draftRound=2"
29 | assert len(context.filters) == 1
30 |
31 |
32 | def test_qb_multi_filter():
33 | qb = QueryBuilder()
34 | filters = [
35 | GameTypeQuery(game_type="2"),
36 | DraftQuery(year="2020", draft_round="2"),
37 | SeasonQuery(season_start="20202021", season_end="20232024"),
38 | ]
39 | context: QueryContext = qb.build(filters=filters)
40 |
41 | assert (
42 | context.query_str
43 | == "gameTypeId=2 and draftYear=2020 and draftRound=2 and seasonId >= 20202021 and seasonId <= 20232024"
44 | )
45 |
46 |
47 | def test_position_draft_query():
48 | qb = QueryBuilder()
49 | filters = [
50 | GameTypeQuery(game_type="2"),
51 | DraftQuery(year="2020", draft_round="1"),
52 | PositionQuery(position=PositionTypes.CENTER),
53 | ]
54 | context: QueryContext = qb.build(filters=filters)
55 |
56 | assert context.query_str == "gameTypeId=2 and draftYear=2020 and draftRound=1 and positionCode='C'"
57 | assert len(context.filters) == 3
58 |
59 |
60 | def test_all_forwards_playoffs_season_query():
61 | qb = QueryBuilder()
62 | filters = [
63 | GameTypeQuery(game_type="3"),
64 | SeasonQuery(season_start="20222023", season_end="20222023"),
65 | PositionQuery(position=PositionTypes.ALL_FORWARDS),
66 | ]
67 | context: QueryContext = qb.build(filters=filters)
68 |
69 | assert (
70 | context.query_str
71 | == "gameTypeId=3 and seasonId >= 20222023 and seasonId <= 20222023 and (positionCode='L' or positionCode='R' "
72 | "or positionCode='C')"
73 | )
74 | assert len(context.filters) == 3
75 |
76 |
77 | def test_query_with_invalid_filter_mixed_in():
78 | qb = QueryBuilder(verbose=True)
79 | filters = [
80 | GameTypeQuery(game_type="3"),
81 | SeasonQuery(season_start="20222023", season_end="20222023"),
82 | PositionQuery(position=PositionTypes.ALL_FORWARDS),
83 | DecisionQuery(decision="Win"),
84 | ]
85 | context: QueryContext = qb.build(filters=filters)
86 |
87 | assert context.is_valid() is False
88 |
89 | assert (
90 | context.query_str
91 | == "gameTypeId=3 and seasonId >= 20222023 and seasonId <= 20222023 and (positionCode='L' or positionCode='R' "
92 | "or positionCode='C')"
93 | )
94 |
--------------------------------------------------------------------------------
/tests/test_game_center.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 |
4 | @mock.patch("httpx.Client.get")
5 | def test_boxscore(h_m, nhl_client):
6 | nhl_client.game_center.boxscore(game_id="2020020001")
7 | h_m.assert_called_once()
8 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/gamecenter/2020020001/boxscore"
9 |
10 |
11 | @mock.patch("httpx.Client.get")
12 | def test_play_by_play(h_m, nhl_client):
13 | nhl_client.game_center.play_by_play(game_id="2020020001")
14 | h_m.assert_called_once()
15 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/gamecenter/2020020001/play-by-play"
16 |
17 |
18 | @mock.patch("httpx.Client.get")
19 | def test_landing_page(h_m, nhl_client):
20 | nhl_client.game_center.landing(game_id="2020020001")
21 | h_m.assert_called_once()
22 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/gamecenter/2020020001/landing"
23 |
24 |
25 | @mock.patch("httpx.Client.get")
26 | def test_score_now(h_m, nhl_client):
27 | nhl_client.game_center.score_now()
28 | h_m.assert_called_once()
29 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/score/now"
30 |
31 |
32 | @mock.patch("httpx.Client.get")
33 | def test_shift_chart_data(h_m, nhl_client):
34 | nhl_client.game_center.shift_chart_data(game_id="2020020001")
35 | h_m.assert_called_once()
36 | assert (
37 | h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/shiftcharts?cayenneExp=gameId=2020020001 and "
38 | "((duration != '00:00' and typeCode = 517) or typeCode != 517 )&exclude=eventDetails"
39 | )
40 |
--------------------------------------------------------------------------------
/tests/test_nhl_client.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest.mock import Mock, patch
3 | from nhlpy.nhl_client import NHLClient
4 | from nhlpy.api import teams, standings, schedule
5 | from nhlpy.http_client import (
6 | NHLApiException,
7 | ResourceNotFoundException,
8 | RateLimitExceededException,
9 | ServerErrorException,
10 | BadRequestException,
11 | UnauthorizedException,
12 | HttpClient,
13 | )
14 |
15 |
16 | class MockResponse:
17 | """Mock httpx.Response for testing"""
18 |
19 | def __init__(self, status_code, json_data=None):
20 | self.status_code = status_code
21 | self._json_data = json_data or {}
22 | self.url = "https://api.nhl.com/v1/test"
23 |
24 | def json(self):
25 | return self._json_data
26 |
27 | @property
28 | def is_success(self):
29 | return 200 <= self.status_code < 300
30 |
31 |
32 | @pytest.fixture
33 | def mock_config():
34 | """Fixture for config object"""
35 | config = Mock()
36 | config.verbose = False
37 | config.ssl_verify = True
38 | config.timeout = 30
39 | config.follow_redirects = True
40 | config.api_web_base_url = "https://api.nhl.com"
41 | config.api_web_api_ver = "/v1"
42 | return config
43 |
44 |
45 | @pytest.fixture
46 | def http_client(mock_config):
47 | """Fixture for HttpClient instance"""
48 | return HttpClient(mock_config)
49 |
50 |
51 | def test_nhl_client_responds_to_teams():
52 | c = NHLClient()
53 | assert c.teams is not None
54 | assert isinstance(c.teams, teams.Teams)
55 |
56 |
57 | def test_nhl_client_responds_to_standings():
58 | c = NHLClient()
59 | assert c.standings is not None
60 | assert isinstance(c.standings, standings.Standings)
61 |
62 |
63 | def test_nhl_client_responds_to_schedule():
64 | c = NHLClient()
65 | assert c.schedule is not None
66 | assert isinstance(c.schedule, schedule.Schedule)
67 |
68 |
69 | @pytest.mark.parametrize(
70 | "status_code,expected_exception",
71 | [
72 | (404, ResourceNotFoundException),
73 | (429, RateLimitExceededException),
74 | (400, BadRequestException),
75 | (401, UnauthorizedException),
76 | (500, ServerErrorException),
77 | (502, ServerErrorException),
78 | (599, NHLApiException),
79 | ],
80 | )
81 | def test_http_client_error_handling(http_client, status_code, expected_exception):
82 | """Test different HTTP error status codes raise appropriate exceptions"""
83 | mock_response = MockResponse(status_code=status_code, json_data={"message": "Test error message"})
84 |
85 | with patch("httpx.Client") as mock_client:
86 | mock_client.return_value.__enter__.return_value.get.return_value = mock_response
87 |
88 | with pytest.raises(expected_exception) as exc_info:
89 | http_client.get("/test")
90 |
91 | assert exc_info.value.status_code == status_code
92 | assert "Test error message" in str(exc_info.value)
93 |
94 |
95 | def test_http_client_success_response(http_client):
96 | """Test successful HTTP response"""
97 | mock_response = MockResponse(status_code=200, json_data={"data": "test"})
98 |
99 | with patch("httpx.Client") as mock_client:
100 | mock_client.return_value.__enter__.return_value.get.return_value = mock_response
101 | response = http_client.get("/test")
102 | assert response.status_code == 200
103 |
104 |
105 | def test_http_client_non_json_error_response(http_client):
106 | """Test error response with non-JSON body still works"""
107 | mock_response = MockResponse(status_code=500)
108 | mock_response.json = Mock(side_effect=ValueError) # Simulate JSON decode error
109 |
110 | with patch("httpx.Client") as mock_client:
111 | mock_client.return_value.__enter__.return_value.get.return_value = mock_response
112 |
113 | with pytest.raises(ServerErrorException) as exc_info:
114 | http_client.get("/test")
115 |
116 | assert exc_info.value.status_code == 500
117 | assert "Request to" in str(exc_info.value)
118 |
119 |
120 | def test_http_client_get_by_url_with_params(http_client):
121 | """Test get_by_url method with query parameters"""
122 | mock_response = MockResponse(status_code=200, json_data={"data": "test"})
123 | query_params = {"season": "20232024"}
124 |
125 | with patch("httpx.Client") as mock_client:
126 | mock_instance = mock_client.return_value.__enter__.return_value
127 | mock_instance.get.return_value = mock_response
128 |
129 | response = http_client.get_by_url("https://api.nhl.com/v1/test", query_params)
130 |
131 | mock_instance.get.assert_called_once_with(url="https://api.nhl.com/v1/test", params=query_params)
132 | assert response.status_code == 200
133 |
134 |
135 | def test_http_client_custom_error_message(http_client):
136 | """Test custom error message in JSON response"""
137 | custom_message = "Custom API error explanation"
138 | mock_response = MockResponse(status_code=400, json_data={"message": custom_message})
139 |
140 | with patch("httpx.Client") as mock_client:
141 | mock_client.return_value.__enter__.return_value.get.return_value = mock_response
142 |
143 | with pytest.raises(BadRequestException) as exc_info:
144 | http_client.get("/test")
145 |
146 | assert custom_message in str(exc_info.value)
147 |
--------------------------------------------------------------------------------
/tests/test_playoffs.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 |
4 | @mock.patch("httpx.Client.get")
5 | def test_carousel(h_m, nhl_client):
6 | nhl_client.playoffs.carousel(season="20232024")
7 | h_m.assert_called_once()
8 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/playoff-series/carousel/20232024"
9 |
10 |
11 | @mock.patch("httpx.Client.get")
12 | def test_schedule(h_m, nhl_client):
13 | nhl_client.playoffs.schedule(season="20232024", series="a")
14 | h_m.assert_called_once()
15 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/schedule/playoff-series/20232024/a"
16 |
17 |
18 | @mock.patch("httpx.Client.get")
19 | def test_bracket(h_m, nhl_client):
20 | nhl_client.playoffs.bracket(year="2024")
21 | h_m.assert_called_once()
22 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/playoff-bracket/2024"
23 |
--------------------------------------------------------------------------------
/tests/test_schedule.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 | import pytest
4 |
5 |
6 | @mock.patch("httpx.Client.get")
7 | def test_get_schedule_with_date(h_m, nhl_client):
8 | nhl_client.schedule.get_schedule(date="2021-01-01")
9 | h_m.assert_called_once()
10 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/schedule/2021-01-01"
11 |
12 |
13 | @mock.patch("httpx.Client.get")
14 | def test_get_schedule_with_fixable_date(h_m, nhl_client):
15 | nhl_client.schedule.get_schedule("2024-10-9")
16 | h_m.assert_called_once()
17 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/schedule/2024-10-09"
18 |
19 |
20 | @mock.patch("httpx.Client.get")
21 | def test_get_schedule_will_error_with_bad_date(h_m, nhl_client):
22 | with pytest.raises(ValueError):
23 | nhl_client.schedule.get_schedule("2024-10-09-")
24 |
25 |
26 | @mock.patch("httpx.Client.get")
27 | def test_get_weekly_schedule_with_date(h_m, nhl_client):
28 | nhl_client.schedule.get_weekly_schedule(date="2021-01-01")
29 | h_m.assert_called_once()
30 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/schedule/2021-01-01"
31 |
32 |
33 | @mock.patch("httpx.Client.get")
34 | def test_get_weekly_schedule_with_no_date(h_m, nhl_client):
35 | nhl_client.schedule.get_weekly_schedule()
36 | h_m.assert_called_once()
37 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/schedule/now"
38 |
39 |
40 | @mock.patch("httpx.Client.get")
41 | def test_get_schedule_by_team_by_month_with_month(h_m, nhl_client):
42 | nhl_client.schedule.get_schedule_by_team_by_month(team_abbr="BUF", month="2023-11")
43 | h_m.assert_called_once()
44 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-schedule/BUF/month/2023-11"
45 |
46 |
47 | @mock.patch("httpx.Client.get")
48 | def test_get_schedule_by_team_by_month_with_no_month(h_m, nhl_client):
49 | nhl_client.schedule.get_schedule_by_team_by_month(team_abbr="BUF")
50 | h_m.assert_called_once()
51 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-schedule/BUF/month/now"
52 |
53 |
54 | @mock.patch("httpx.Client.get")
55 | def test_get_schedule_by_team_by_week(h_m, nhl_client):
56 | nhl_client.schedule.get_schedule_by_team_by_week(team_abbr="BUF")
57 | h_m.assert_called_once()
58 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-schedule/BUF/week/now"
59 |
60 |
61 | @mock.patch("httpx.Client.get")
62 | def test_get_schedule_by_team_by_week_with_date(h_m, nhl_client):
63 | nhl_client.schedule.get_schedule_by_team_by_week(team_abbr="BUF", date="2024-02-10")
64 | h_m.assert_called_once()
65 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-schedule/BUF/week/2024-02-10"
66 |
67 |
68 | @mock.patch("httpx.Client.get")
69 | def test_get_season_schedule(h_m, nhl_client):
70 | nhl_client.schedule.get_season_schedule(team_abbr="BUF", season="20202021")
71 | h_m.assert_called_once()
72 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-schedule-season/BUF/20202021"
73 |
--------------------------------------------------------------------------------
/tests/test_standings.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 |
4 | @mock.patch("httpx.Client.get")
5 | def test_get_standings(h_m, nhl_client):
6 | nhl_client.standings.get_standings()
7 | h_m.assert_called_once()
8 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/standings/now"
9 |
10 |
11 | @mock.patch("httpx.Client.get")
12 | def test_get_standings_with_cache_load(h_m, nhl_client):
13 | nhl_client.standings.get_standings(season="20202021", cache=True)
14 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/standings/2021-05-19"
15 |
--------------------------------------------------------------------------------
/tests/test_stats.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 |
4 | @mock.patch("httpx.Client.get")
5 | def test_stats_season(h_m, nhl_client):
6 | nhl_client.stats.gametypes_per_season_directory_by_team(team_abbr="BUF")
7 | h_m.assert_called_once()
8 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/club-stats-season/BUF"
9 |
10 |
11 | @mock.patch("httpx.Client.get")
12 | def test_player_career_stats(h_m, nhl_client):
13 | nhl_client.stats.player_career_stats(player_id=8481528)
14 | h_m.assert_called_once()
15 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/player/8481528/landing"
16 |
17 |
18 | @mock.patch("httpx.Client.get")
19 | def test_team_summary_single_year(h_m, nhl_client):
20 | nhl_client.stats.team_summary(start_season="20232024", end_season="20232024")
21 | h_m.assert_called_once()
22 | assert h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/team/summary"
23 | assert h_m.call_args[1]["params"] == {
24 | "isAggregate": False,
25 | "isGame": False,
26 | "limit": 50,
27 | "start": 0,
28 | "factCayenneExp": "gamesPlayed>1",
29 | "sort": '[{"property": "points", "direction": "DESC"}, {"property": "wins", "direction": "DESC"}, '
30 | '{"property": "teamId", "direction": "ASC"}]',
31 | "cayenneExp": "gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024",
32 | }
33 |
34 |
35 | @mock.patch("httpx.Client.get")
36 | def team_test_summary_year_range(h_m, nhl_client):
37 | nhl_client.stats.team_summary(start_season="20202021", end_season="20232024")
38 | h_m.assert_called_once()
39 | assert h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/team/summary"
40 | assert h_m.call_args[1]["params"] == {
41 | "isAggregate": False,
42 | "isGame": False,
43 | "limit": 50,
44 | "start": 0,
45 | "factCayenneExp": "gamesPlayed>1",
46 | "sort": "%5B%7B%22property%22%3A%20%22points%22%2C%20%22direction%22%3A%20%22DESC%22%7D%2C%20%7B%22"
47 | "property%22%3A%20%22wins%22%2C%20%22direction%22%3A%20%22DESC%22%7D%2C%20%7B%22property%22"
48 | "%3A%20%22teamId%22%2C%20%22direction%22%3A%20%22ASC%22%7D%5D",
49 | "cayenneExp": "gameTypeId=2 and seasonId<=20232024 and seasonId>=20202021",
50 | }
51 |
52 |
53 | @mock.patch("httpx.Client.get")
54 | def team_test_summary_year_range_playoffs(h_m, nhl_client):
55 | nhl_client.stats.team_summary(start_season="20182019", end_season="20222023", game_type_id=3)
56 | h_m.assert_called_once()
57 | assert h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/team/summary"
58 | assert h_m.call_args[1]["params"] == {
59 | "isAggregate": False,
60 | "isGame": False,
61 | "limit": 50,
62 | "start": 0,
63 | "factCayenneExp": "gamesPlayed>1",
64 | "sort": "%5B%7B%22property%22%3A%20%22points%22%2C%20%22direction%22%3A%20%22DESC%22%7D%2C%20%7"
65 | "B%22property%22%3A%20%22wins%22%2C%20%22direction%22%3A%20%22DESC%22%7D%2C%20%7B%22pro"
66 | "perty%22%3A%20%22teamId%22%2C%20%22direction%22%3A%20%22ASC%22%7D%5D",
67 | "cayenneExp": "gameTypeId=3 and seasonId<=20222023 and seasonId>=20182019",
68 | }
69 |
70 |
71 | @mock.patch("httpx.Client.get")
72 | def test_skater_stats_summary(h_m, nhl_client):
73 | nhl_client.stats.skater_stats_summary_simple(start_season="20232024", end_season="20232024")
74 | h_m.assert_called_once()
75 | assert h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/skater/summary"
76 | assert h_m.call_args[1]["params"] == {
77 | "isAggregate": False,
78 | "isGame": False,
79 | "limit": 25,
80 | "start": 0,
81 | "factCayenneExp": "gamesPlayed>=1",
82 | "sort": '[{"property": "points", "direction": "DESC"}, {"property": '
83 | '"gamesPlayed", "direction": "ASC"}, {"property": "playerId", '
84 | '"direction": "ASC"}]',
85 | "cayenneExp": "gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024",
86 | }
87 |
88 |
89 | @mock.patch("httpx.Client.get")
90 | def test_skater_stats_summary_franchise(h_m, nhl_client):
91 | nhl_client.stats.skater_stats_summary_simple(start_season="20232024", end_season="20232024", franchise_id=19)
92 | h_m.assert_called_once()
93 | assert h_m.call_args[1]["url"] == "https://api.nhle.com/stats/rest/en/skater/summary"
94 | assert h_m.call_args[1]["params"] == {
95 | "isAggregate": False,
96 | "isGame": False,
97 | "limit": 25,
98 | "start": 0,
99 | "factCayenneExp": "gamesPlayed>=1",
100 | "sort": '[{"property": "points", "direction": "DESC"}, {"property": '
101 | '"gamesPlayed", "direction": "ASC"}, {"property": "playerId", '
102 | '"direction": "ASC"}]',
103 | "cayenneExp": "franchiseId=19 and gameTypeId=2 and seasonId<=20232024 and seasonId>=20232024",
104 | }
105 |
106 |
107 | @mock.patch("httpx.Client.get")
108 | def test_player_game_log(h_m, nhl_client):
109 | nhl_client.stats.player_game_log(player_id="8481528", season_id="20232024", game_type=2)
110 | h_m.assert_called_once()
111 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/player/8481528/game-log/20232024/2"
112 |
113 |
114 | @mock.patch("httpx.Client.get")
115 | def test_player_game_log_playoffs(h_m, nhl_client):
116 | nhl_client.stats.player_game_log(player_id="8481528", season_id="20232024", game_type=3)
117 | h_m.assert_called_once()
118 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/player/8481528/game-log/20232024/3"
119 |
--------------------------------------------------------------------------------
/tests/test_teams.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 |
4 | @mock.patch("httpx.Client.get")
5 | def test_roster(h_m, nhl_client):
6 | nhl_client.teams.roster(team_abbr="BUF", season="20202021")
7 | h_m.assert_called_once()
8 | assert h_m.call_args[1]["url"] == "https://api-web.nhle.com/v1/roster/BUF/20202021"
9 |
--------------------------------------------------------------------------------