nba_api

swarMIT活跃维护

Python 客户端库,封装 NBA.com 官方接口,方便抓取球员和球队的统计数据,用于篮球数据分析与可视化。

An API Client package to access the APIs for NBA.com

v1.12.0发布于 2026-10-24 05:33 UTC3,876star +2 / 7 天725fork同步于 2026-11-10 11:39 UTC

怎么上手

从 README 代码块原样提取,可能是其中一种安装方式
pip install nba_api
硬件要求

README 没有说明硬件要求。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

这个项目的说明还在生成中,先参考下面「最近发版」和 README。

最近发版

5 个版本v1.12.0
  1. v1.12.0最新正式版2026-10-24 · 2026-10-24 05:33 UTC

    Date: 2026-10-24

    Added

    • NBA Cup Round Filter - 34 dashboard, league, shot chart and video endpoints take a new ist_round_nullable argument that sends the ISTRound filter (Group, East/West Group A-C, Knockout, Championship), with ISTRound / ISTRoundNullable added to parameters.py. It defaults to None, so existing requests are unchanged (PR #719)
    • V3 Box Scores - Every dataset of the ten nested box score endpoints (BoxScoreAdvancedV3, BoxScoreDefensiveV2, BoxScoreFourFactorsV3, BoxScoreHustleV2, BoxScoreMatchupsV3, BoxScoreMiscV3, BoxScorePlayerTrackV3, BoxScoreScoringV3, BoxScoreTraditionalV3, BoxScoreUsageV3) now has homeTeamId and awayTeamId columns, so home and away rows no longer have to be told apart by row order. The columns are appended at the end, so existing column positions stay the same (PR #717)
    • Proxy Settings - The proxy is now resolved on every request (explicit proxy=, then NBA_API_PROXY, then the legacy debug.PROXY), so setting NBA_API_PROXY after import takes effect. Setting NBA_API_REQUIRE_PROXY=1 makes a request raise ProxyRequiredError before any connection opens when no proxy is configured, and proxy credentials are masked in request errors (PR #720)
    • Python 3.14 and 3.15 - Added support for Python 3.14 and 3.15, with numpy and pandas floors on those versions set to the first releases that ship wheels for them (PR #729)
    • Documentation - Added an endpoint guide that maps the data you want to the endpoint, parameters and datasets to use, a guide for AI coding agents writing code with nba_api, and a list of endpoints stats.nba.com currently fails or no longer serves (PR #737, PR #736, PR #715)

    Changed

    • Dependencies - numpy is no longer a direct dependency; it is still installed through pandas, so environments are unchanged, and the per-Python numpy pins that conflicted with numpy 2 (for example on Colab, see #509 and #523) are gone. Column labels in multi-level get_data_frame() frames are now str instead of numpy.str_ (equal values) (PR #741)
    • Dependencies - The pandas floor is now 2.2.2 on Python 3.10 to 3.12 and 2.2.3 on Python 3.13. Older pandas releases either fail to import next to numpy 2 (numpy.dtype size changed) or, on 3.13, have no wheels and must be built from source (PR #741, PR #744, PR #740)
    • Import Time - pandas is imported only when get_data_frame() is first called, so import nba_api.stats.endpoints drops from about 185 ms to about 62 ms and code that only uses get_dict() / get_json() never loads pandas. nba_api.__version__ is looked up on first access. If pandas is missing, get_data_frame() raises ModuleNotFoundError (PR #743, PR #746, PR #742)
    • Static Players - find_player_by_id uses an id index instead of scanning every player, and name searches cache the accent-stripped names (about 5.9 ms to 0.4 ms per search). The caches rebuild if data.players changes length (PR #743)

    Deprecated

    • Endpoints No Longer Served - LeagueLeaders, AssistLeaders, AssistTracker and PlayoffPicture (stats.nba.com returns its homepage) and BoxScoreAdvancedV2, BoxScoreFourFactorsV2, BoxScoreMiscV2, BoxScoreScoringV2, BoxScoreUsageV2 and PlayByPlay (empty JSON) now emit a DeprecationWarning naming the r
  2. v1.11.6v.1.11.62026-10-22 · 2026-10-22 04:44 UTC
    查看更新说明

    v1.11.6

    Date: 2026-10-22

    Fixed

    • Live Endpoints - ScoreBoard, BoxScore, PlayByPlay and Odds work again with default settings. cdn.nba.com had started rejecting the default request headers with 403 Access Denied, which surfaced as a JSONDecodeError; the live client now sends a current Firefox User-Agent and a Referer: https://www.nba.com/ header (PR #716)

    Infrastructure

    • CI - Removed the CircleCI config and the Snyk dependency scan; GitHub Actions now runs lint, tests and releases (PR #714, PR #718)
  3. v1.11.52026-10-22 · 2026-10-22 04:03 UTC
    查看更新说明

    Changed

    • Static WNBA Teams Data - Added the Portland Fire and Toronto Tempo expansion teams, so get_wnba_teams() and the find_wnba_team* helpers return them (PR #693)
    • Static Players Data - Refreshed players and wnba_players from stats.nba.com: added the 2025 draft class and newly listed players, updated active-roster flags for the current season, applied upstream name corrections, and dropped inactive entries the API no longer returns (PR #687, PR #698)

    Fixed

    • V3 Normalized Output - Fixed get_normalized_dict() / get_normalized_json() returning empty payloads for V3 endpoints by persisting endpoint context and normalizing parser-generated data sets (PR #606, fixes #602)
    • DunkScoreLeaders Parsing - Fixed response parsing by adding a dedicated parser, registering it in parser dispatch, and aligning expected data keys with the endpoint's nested V3 camelCase payload fields (PR #598)
    • ScheduleLeagueV2 - League schedules now parse correctly regardless of the order of keys in the NBA.com response (PR #692)
    • Static Teams Data - Added the Boston Celtics' 2024 championship, so find_teams_by_championship_year(2024) returns them (PR #695)
    • Win-Loss Example Notebook - Replaced the DataFrame.append call removed in pandas 2 in the Home Team Win-Loss data-prep notebook (PR #684)

    Infrastructure

    • GitHub Actions CI - Added GitHub Actions running lint plus unit and VCR tests on Python 3.10–3.13 alongside CircleCI, with a single CI passed status check, Conventional Commit PR-title validation, network-blocked test runs, and a lockfile sync check (PR #704, PR #706)
    • Release Pipeline - Releases are now published to PyPI from a GitHub Actions workflow using Trusted Publishing, and scripts/gen-release.sh was rewritten to prepare release PRs safely, including agent-written notes and a --bump override (PR #705, PR #710, PR #711)
    • Static Teams Generator - Added scripts/static_teams_update/generate_static_teams.py to refresh championship years and new teams in the static data, with a --check mode (PR #699)
    • Integration Season Pinning - Cassette-backed integration tests now pin season defaults to the recorded season, so they no longer break when the season rolls over each October (PR #700)
    • Live Endpoint Unit Tests - Mocked the HTTP layer in the live boxscore/odds get_request_url tests, which were making real network calls (PR #686)
    • Ruff Tooling - Replaced flake8, isort, and pylint with ruff for linting and formatting; added pre-commit hooks to auto-fix on commit (PR #639)
    • Pytest Recording Stack - Added pytest-recording (and vcrpy) to dev dependencies; introduced pytest markers for integration test modes (live, vcr, canary, deprecated_endpoint) (PR #640)
    • Integration Conftest - Added tests/integration/conftest.py with shared request pacing, cassette directory configuration, and automatic skipping for deprecated endpoint smoke cases (PR #640)
    • VCR Query Matcher - Updated query matching to ignore dynamic GameDate params so cassette playback remains stable in CI (PR [#644](
  4. v1.11.42026-02-20 · 2026-02-20 06:53 UTC
    查看更新说明

    v1.11.4

    Date: 2026-02-20

    Added

    • GravityLeaders - New endpoint added (#626)
    • __version__ attribute - Package now exposes a __version__ attribute using importlib.metadata with pyproject.toml as the single source of truth (#612)

    Fixed

    • HTTP Headers - Updated request headers to fix broken NBA.com API requests caused by an outdated user agent (#636)
    • ContextMeasureSimple - Removed deprecated PF (Personal Fouls) parameter; NBA.com API no longer returns data for this context measure on the shotchartdetail endpoint (#608, fixes #600)

    Deprecated

    • PlayByPlayV2 - Added deprecation warning; NBA.com API returns empty JSON for this endpoint. Use PlayByPlayV3 instead (#613, fixes #591)
    • ScoreboardV2 - Added deprecation warning; returns empty line scores for 2025-26 season games. Use ScoreboardV3 instead, which is 100% backward compatible (#609, fixes #596)

    Contributor

    • Added type hints and docstrings to the Endpoint base class and PlayerCareerStats endpoint for improved code clarity and IDE support (#628)
    • Added CODEOWNERS file (#627)
    • Corrected typos in contributing guide and README (#604)
  5. v1.11.32025-11-14 · 2025-11-14 13:29 UTC
    查看更新说明

    Removed

    • BoxScorePlayerTrackV2 - Endpoint removed due to NBA API returning HTTP 500 errors

      • The NBA.com API no longer supports this endpoint
      • Users should migrate to BoxScorePlayerTrackV3 instead
      • Removed endpoint class, documentation, tests, and all references
    • PlayerFantasyProfile - Endpoint removed due to NBA API discontinuation

      • The NBA.com API no longer supports this endpoint
      • No direct replacement available
      • Removed endpoint class, documentation, tests, and all references

    Added

    • TeamGameLog - Endpoint restored after confirming NBA API is working again

      • Retired in v1.11.0 due to reported NBA API deprecation, but now confirmed to be operational
      • Returns game-by-game statistics for a specific team
      • Required parameter: team_id
      • Optional filtering: season, season type, date range
      • Comprehensive unit tests (6 tests) and integration tests (4 tests) added
    • TeamGameLogs - Endpoint restored after confirming NBA API is working again

      • Retired in v1.11.0 due to reported NBA API deprecation, but now confirmed to be operational
      • Returns game-by-game statistics for one or more teams
      • All parameters optional (can query all teams)
      • Includes rank fields for all statistics (_RANK suffix)
      • Advanced filtering: location, outcome, conference, division, measure type
      • Comprehensive unit tests (8 tests) and integration tests (5 tests) added
    • Integration Test Validation Infrastructure - Enhanced validation to prevent false endpoint retirements

      • Root Cause: TeamGameLog/TeamGameLogs were incorrectly retired in v1.11.0 because integration test framework didn't exist yet (created 3 days later)
      • New Validation Features:
        • validate_dataset_structure() - Validates dataset names and column structure match expected_data definitions
        • Per-dataset row count validation and logging (instead of just total rows)
        • Opt-in strict validation mode via validate_structure: True flag (default: False to preserve compatibility)
        • Helper functions to reduce code complexity: _count_dataset_rows(), _validate_status(), _validate_row_counts()
      • Benefits:
        • Catches API response structure changes early
        • Detects expected_data definition errors
        • Prevents false endpoint retirements
        • Provides detailed per-dataset diagnostics
      • Documentation: Comprehensive guide in tests/integration/data/README.md with examples and best practices
      • Test Results: All 37 integration tests passing, all 460 unit tests passing

    Fixed

    • LeagueIDNullable Parameter - Fixed default value to prevent empty responses (#562)

      • Root Cause: LeagueIDNullable.default was inheriting "" (empty string) from _NotRequired instead of "00" (NBA) from LeagueID
      • NBA API Change: Starting around the 2023-24 season (IST introduction), the NBA.com API became stricter and now requires an explicit LeagueID value rather than accepting empty strings
      • Impact: Endpoints using LeagueIDNullable (e.g., PlayerProfileV2, CommonTeamRoster) returned empty datasets when called without explicitly specifying league_id_nullable
      • Fix: Override LeagueIDNullable.default to explicitly use LeagueID.nba ("00")
      • Affected Endpoints: All endpoints with league_id_nullable parameter now default to NBA league instead of empty string
      • Possible Breaking Change: This fixes broken behavior but changes the API semantics - empty LeagueID is no longer sent to NBA.com (which was causing failures)
    • LeagueGameFinder - Documented and added warning for game_id_nullable parameter limitation (#446)

      • NBA API Limitation: The game_id_nullable parameter is ignored by the NBA Stats API and does not filter results
      • Impact: Users passing game_id_nullable rec

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    The NBA's stats, in Python. nba_api wraps 130+ stats.nba.com endpoints and the live game feeds behind NBA.com, no API key required, and hands stats back as pandas DataFrames.

    • Every corner of NBA.com stats: player and team stats, box scores, game logs, shot charts, play-by-play, standings, and more, with each endpoint's parameters and data sets documented
    • Live game data: scoreboard, box scores, play-by-play, and odds, updated during games
    • pandas built in: stats come back as DataFrames, dicts, or JSON
    • Player and team IDs offline: reference data ships with the package, so lookups need no request
    • More than the NBA: many endpoints also cover the WNBA and G League through league_id

    Installation

    pip install nba_api
    

    Requires Python 3.10+. Installs requests and pandas.

    Quick start

    Look up a player or team

    Player and team reference data ships with the package, so lookups are instant and work offline.

    from nba_api.stats.static import players, teams
    
    players.find_players_by_full_name("donovan mitchell")
    # [{'id': 1628378, 'full_name': 'Donovan Mitchell', 'first_name': 'Donovan',
    #   'last_name': 'Mitchell', 'is_active': True}]
    
    teams.find_team_by_abbreviation("cle")
    # {'id': 1610612739, 'full_name': 'Cleveland Cavaliers', 'abbreviation': 'CLE', ...}
    

    Searches take case-insensitive regular expressions, and player name searches ignore accents ("žydrūnas" finds "Zydrunas Ilgauskas").

    Get stats from stats.nba.com

    from nba_api.stats.endpoints import playercareerstats
    
    career = playercareerstats.PlayerCareerStats(player_id=1628378)  # sends the request
    
    df = career.season_totals_regular_season.get_data_frame()
    df[["SEASON_ID", "TEAM_ABBREVIATION", "PTS"]].tail(3)
    #   SEASON_ID TEAM_ABBREVIATION   PTS
    # 6   2023-24               CLE  1463
    # 7   2024-25               CLE  1701
    # 8   2025-26               CLE  1952
    

    Every stats endpoint works the same way: constructing it sends the request, and each data set it returns is an attribute with get_data_frame(), get_dict(), and get_json(). To grab everything at once, use career.get_data_frames() or career.get_dict(). To find the endpoint that has the data you want, see the endpoint guide. The endpoint reference lists every endpoint's parameters and data sets.

    Follow live games from cdn.nba.com

    from nba_api.live.nba.endpoints import scoreboard
    
    games = scoreboard.ScoreBoard()  # today's games
    cavs = [
        g for g in games.games.get_dict()
        if "CLE" in (g["homeTeam"]["teamTricode"], g["awayTeam"]["teamTricode"])
    ]  # tonight's Cavs game, if they play
    

    Live endpoints: ScoreBoard, BoxScore(game_id), PlayByPlay(game_id), and Odds. They return dicts and JSON.

    Request options

    Every endpoint, stats or live, accepts the same request options:

    career = playercareerstats.PlayerCareerStats(
        player_id=1628378,
        timeout=60,                       # seconds; default 30
        proxy="http://127.0.0.1:8080",    # or a list of proxies to pick from at random
        headers={"User-Agent": "..."},    # replaces the default headers entirely
        get_request=False,                # build the request without sending it
    )
    career.get_request()                  # send it later
    

    Rate limits and hosting

    Requests hanging or timing out? stats.nba.com throttles rapid requests and does not respond to many cloud-hosting IP ranges (AWS, GCP, Azure, Colab, and others).

    • Pause between requests when fetching in a loop, for example time.sleep(1).
    • Increase timeout.
    • Route requests through a proxy, or set the NBA_API_PROXY environment variable.

    More detail is in the stats examples.

    Documentation

    Community

    • Slack: join the workspace to get help, help others, share projects, and discuss the API.
    • Stack Overflow: ask questions tagged nba-api.

    Contributing

    Contributions of all sizes are welcome, from fixing a typo to adding an endpoint. See CONTRIBUTING.md to set up a development environment and open a pull request.

    NBA.com does not announce new, changed, or removed endpoints. If you find one, or hit a bug, open an issue.

    License and terms of use

    nba_api is open source under the MIT License.

    Data retrieved with this package comes from NBA.com and is subject to the NBA.com Terms of Use.

    nba_api is an independent, community-maintained project and is not affiliated with, endorsed by, or sponsored by the NBA.