Many of the charts on this site start the same dull, glorious way: a Python script asks stats.nba.com a question and writes the answer to disk. The package that does the asking is nba_api, and it is the single fastest way to go from "I have an opinion about the scoring race" to "I have the actual numbers." This is the tutorial to start with: install it, make one real call, understand what comes back, and learn the etiquette of asking politely, under your own name.
Correction, October 29, 2026. The caption below called 2025-26 Dončić’s first year with the Lakers. He joined them from Dallas in a February 2025 trade (the site’s minutes file has him playing 22 games for Dallas and 28 for the Lakers in 2024-25), so 2025-26 was his first full season there. The 33.5 points per game is unchanged.
Correction, November 17, 2026. Earlier versions of this tutorial taught a block of browser-imitating headers (a desktop Chrome User-Agent with nba.com Referer, Origin and x-nba-stats headers) and said that habit was built into every script on this site. Since October 10, 2026 our scripts no longer imitate a browser: every request names the site's tooling in its User-Agent and sends no nba.com headers, and the code below now teaches the same. The June 2026 leaderboard on this page was pulled before that change, with the old headers; its figures are unchanged. The shot-chart walk-through that used to be a separate tutorial is now part of this page.
Install it (one line)
There is no account, no API key, no signup email that takes three business days. The NBA's stats site exposes a sprawling, undocumented JSON API, and nba_api is a community package that wraps the useful corners of it in tidy Python classes. You install it the way you install anything:
pip install nba_api
That pulls in pandas and requests as dependencies, which are the only other pieces you need until the shot chart near the end, which adds matplotlib. If you work in virtual environments (and you should), activate yours first so this doesn't land in your system Python. That's the entire setup. We can go ask the league a question now.
Your first call
Here's the question: who led the league in per-game scoring in 2025-26? That's the example season used throughout; swap any season string into the call and it works the same way. The endpoint that answers it is LeagueLeaders. You hand it a season, a season type, a stat category, and a "per mode," and it hands back a table. This snippet is the real thing: it's a faithful, paste-ready version of the script that generated the chart below:
from nba_api.stats.endpoints import leagueleaders
# Say who is asking (the etiquette section below explains why).
HEADERS = {"User-Agent": "my-nba-project/0.1 (+https://example.com/about)"}
# Ask stats.nba.com for the 2025-26 per-game scoring leaders.
leaders = leagueleaders.LeagueLeaders(
season="2025-26",
season_type_all_star="Regular Season",
stat_category_abbreviation="PTS",
per_mode48="PerGame",
headers=HEADERS,
timeout=30,
)
# Endpoints can return several tables; the leaderboard is the first one.
df = leaders.get_data_frames()[0]
# Sort by points and look at the top of the race.
top = df.sort_values("PTS", ascending=False).head(10)
print(top[["RANK", "PLAYER", "TEAM", "GP", "PTS"]])
Run that and the top line that prints is Luka Dončić, now in a Lakers uniform, at 33.5 points per game across 64 games. Shai Gilgeous-Alexander is right behind at 31.1, and Anthony Edwards rounds out the podium at 28.8. Ten lines of Python, a full season's scoring race. The per_mode48 argument name is a piece of NBA-API archaeology (it dates back to a 48-minute-pace option), but "PerGame" is what you want, and the awkward keyword is a good early lesson: this API was built for the NBA's own website, not for you, and the parameter names show it.

What a DataFrame is
Notice that the call ends in .get_data_frames()[0], and that what we sorted was a thing called df. That object is a pandas DataFrame, and if you're new to data work in Python it's the one concept worth slowing down for. A DataFrame is a spreadsheet that lives in memory: labeled columns (PLAYER, TEAM, PTS, GP) and one row per record (here, one row per player). Everything you'd do in Excel, you do with a method call instead.
The reason this matters is that almost every nba_api endpoint returns a DataFrame, so the handful of moves you learn here transfer everywhere. A few you'll use constantly:
# Pick columns:
df[["PLAYER", "PTS"]]
# Filter rows — only players averaging 25+:
df[df["PTS"] >= 25]
# Sort, then take the top of the list:
df.sort_values("PTS", ascending=False).head(10)
# Compute a new column from existing ones (total points scored):
df["TOTAL_PTS"] = df["PTS"] * df["GP"]
An endpoint can return more than one table, which is why get_data_frames() gives you a list and we index [0]. For LeagueLeaders the first table is the leaderboard and that's all there is; for richer endpoints, index 1, 2, and 3 might hold splits, summaries, or supporting rows. When in doubt, print len(leaders.get_data_frames()) and inspect each one.
Picking the right endpoint
The hard part of nba_api isn't writing the call; it's knowing which of the dozens of endpoints answers your question. The mental model that helps us: ask whether you want a leaderboard, a full-league table, or one entity's detail.
- One ranked stat, league-wide?
LeagueLeaders, exactly what we used. Great for "top scorers / rebounders / assisters." - Every player, many stats at once?
LeagueDashPlayerStats, with ameasure_typeofBase,Advanced,Usage, orScoring. This is the workhorse behind most of the efficiency pieces here. - Every team?
LeagueDashTeamStats: same idea, team level. It's where the Four Factors numbers come from. - One game's box score, or one player's shot locations?
BoxScoreTraditionalV2andShotChartDetail; the latter powers the shot chart below.
Every one of these returns DataFrames, so the skills from the last section carry straight over; you're really only learning new parameter names. The package's GitHub README lists all of them, and if you'd rather not learn the NBA's API at all, our roundup of free basketball data sources covers the friendlier alternatives.
The numbers it returns
To make the leaderboard concrete, here is the exact top ten the call above produces, copied straight from the DataFrame. This is also a tidy demonstration of what "one row per player, labeled columns" looks like once it's on a page:
| Rank | Player | Team | PPG |
|---|---|---|---|
| 1 | Luka Dončić | LAL | 33.5 |
| 2 | Shai Gilgeous-Alexander | OKC | 31.1 |
| 3 | Anthony Edwards | MIN | 28.8 |
| 4 | Jaylen Brown | BOS | 28.7 |
| 5 | Tyrese Maxey | PHI | 28.3 |
| 6 | Kawhi Leonard | LAC | 27.9 |
| 7 | Donovan Mitchell | CLE | 27.9 |
| 8 | Nikola Jokić | DEN | 27.7 |
| 9 | Devin Booker | PHX | 26.1 |
| 10 | Jalen Brunson | NYK | 26.0 |
Mitchell and Leonard are tied at 27.9 to the tenth of a point, which is the kind of thing you only notice when you have the table instead of a vibe. That's the entire pitch for learning this: opinions about the scoring race are cheap, and the data is now ten lines away.
Rate-limit etiquette (read this part)
Here is where most first-time nba_api users get themselves in trouble. The stats endpoints are not a public, supported API; they're the NBA's own website plumbing, and they will time out, hang, or temporarily stop answering you if you're rude. Three habits keep you on the polite side. Our own scripts that call these endpoints import one shared helper that does all three:
1. Say who you are, and set a timeout. The package's built-in default headers (version 1.11.4) imitate a desktop Chrome browser visiting nba.com. Don't send them as your own. Pass a headers= dictionary on every call; it replaces the defaults entirely. Give a User-Agent that names your project and a page where people can reach you, plain Accept headers, and nothing that poses as a browser or the nba.com web app. Ours is NBAAnalytic-data/1.0 (+https://nbaanalytic.com/contact.html). Always set a timeout too, so a stalled call fails fast instead of freezing your script:
from nba_api.stats.endpoints import leagueleaders
# Name your project and a page where people can reach you.
HONEST_HEADERS = {
"User-Agent": "my-nba-project/0.1 (+https://example.com/about)",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9",
}
# headers= replaces the package's browser-style defaults on this call;
# timeout=30 means "give up after 30 seconds," not "wait 30 seconds."
leaders = leagueleaders.LeagueLeaders(
season="2025-26",
headers=HONEST_HEADERS,
timeout=30,
)
An honest request will not always get an answer, and that is information too. On October 10, 2026 the stats endpoints answered our honest headers for LeagueLeaders (2024-25, 569 rows). On November 2, 2026 two other endpoints, the hustle-stats table and a player-tracking table, never answered: the requests timed out after 45 and 90 seconds, and we did not retry them as a browser. The host's robots.txt address redirects to a page that answers 404, so it sets no crawling rules; read it before a large pull anyway, because rules change.
2. Don't hammer the server. If you're looping over players or games, put a short pause (half a second to a second) between calls, and wrap each call in a retry with exponential backoff so a single hiccup doesn't crash a long pull. A loop that fires a hundred requests as fast as Python can manage is exactly what gets you a temporary block. Sleep is cheap; getting rate-limited in the middle of a run is not.
3. Cache everything. This is the most important habit and the one people skip. The scoring leaders don't change between 2:00 and 2:05, so there is no reason to ask twice. Pull once, write the raw response to disk, and on every subsequent run read from the file instead of the network:
Pythonimport io, time
from pathlib import Path
import pandas as pd
CACHE = Path("data/raw")
CACHE.mkdir(parents=True, exist_ok=True)
def cached_df(key, producer, sleep_after=0.7):
"""Pull a DataFrame once, then serve it from disk forever after.
Delete the cached file to force a fresh pull."""
path = CACHE / f"{key}.json"
if path.exists():
return pd.read_json(io.StringIO(path.read_text(encoding="utf-8")),
orient="records")
df = producer() # the only line that hits the network
path.write_text(df.to_json(orient="records"), encoding="utf-8")
time.sleep(sleep_after) # be polite on the way out
return df
leaders = cached_df(
"leagueleaders_PTS_2025-26",
lambda: leagueleaders.LeagueLeaders(
season="2025-26", season_type_all_star="Regular Season",
stat_category_abbreviation="PTS", per_mode48="PerGame",
headers=HONEST_HEADERS, timeout=30,
).get_data_frames()[0],
)
Caching does three good things at once: it makes your work reproducible (the numbers don't shift under you between runs), it makes development fast (no waiting on the network every time you tweak a chart), and it makes you a good citizen (one request instead of a thousand). The full version of this pattern (honest headers, a robots.txt check before the first request to a host, retries with backoff, on-disk caching, and a manifest that records where every number came from) is the shared helper our NBA Stats pull scripts import. The specific script behind this article does nothing more exotic than what you've read here.
One player’s shots: ShotChartDetail
A leaderboard is one table for the whole league. ShotChartDetail goes the other way: one row per shot, with where it was taken and whether it went in. The API identifies players by number, so look up the ID first; the package ships a local copy of the player list, so that lookup costs no request. team_id=0 means any team, and context_measure_simple="FGA" asks for every field-goal attempt rather than only the makes.
from nba_api.stats.static import players
from nba_api.stats.endpoints import shotchartdetail
pid = players.find_players_by_full_name("Shai Gilgeous-Alexander")[0]["id"]
shots = shotchartdetail.ShotChartDetail(
team_id=0,
player_id=pid,
season_nullable="2025-26",
season_type_all_star="Regular Season",
context_measure_simple="FGA",
headers=HONEST_HEADERS,
timeout=30,
).get_data_frames()[0]
# One pandas aggregation turns 1,321 rows into a zone table.
zones = shots.groupby("SHOT_ZONE_BASIC")["SHOT_MADE_FLAG"].agg(["count", "sum"])
zones["FG%"] = (zones["sum"] / zones["count"] * 100).round(1)
print(zones.sort_values("count", ascending=False))
LOC_X and LOC_Y place each shot in tenths of a foot with the hoop at (0, 0), and SHOT_MADE_FLAG is 1 or 0. Two matplotlib scatter calls, misses then makes, over a half-court drawn from a few Circle, Rectangle and Arc patches give the chart below; set ax.set_aspect("equal") or the court stretches.

The zone table is where the season's shape shows:
| Zone | FGA | FGM | FG% |
|---|---|---|---|
| Restricted Area | 365 | 260 | 71.2 |
| Mid-Range | 355 | 195 | 54.9 |
| In The Paint (Non-RA) | 303 | 161 | 53.1 |
| Above the Break 3 | 280 | 109 | 38.9 |
| Left Corner 3 | 13 | 4 | 30.8 |
| Right Corner 3 | 5 | 2 | 40.0 |
He took 365 shots in the restricted area and made 71.2% of them. His busiest zone was the mid-range: 355 attempts at 54.9%, in a league that has spent a decade moving away from the shot. The corners hardly appear, 18 attempts all season, because he is the player creating the kick-out rather than the one waiting for it. None of that is visible in a 55.3% field-goal percentage. All of it is in the table.
What our data layer calls, and what answered on November 2, 2026
The tutorial above is the small version of what this site runs. The tables behind our data pieces come from a short list of endpoints, and the files they produce sit in our public data layer. Here is each endpoint, the files built from it, when we last pulled it, and what happened on November 2, 2026, the first day for which we kept a full record of every request. Each request that day named the site's tooling in its User-Agent (NBAAnalytic-data/1.0, with a contact page) and sent only Accept headers: no browser imitation, no nba.com Referer or Origin.
| Endpoint | Host | Files built from it | Last pulled | November 2, 2026 |
|---|---|---|---|---|
LeagueDashTeamStats | stats.nba.com | team_seasons_2000_2026.csv, team_box_2005_2026.csv, team_preseason_2021_2026.csv | June 2026 | Not asked |
LeagueDashPlayerStats | stats.nba.com | player_seasons_2005_2026.csv | September 2026 | Not asked |
DraftHistory | stats.nba.com | draft_history.csv | September 2026 | Not asked |
LeagueGameLog | stats.nba.com | nba_games_2025_26.csv, game_box_2025_26.csv, team_game_sequence_2024_2026.csv | June 2026 | Not asked |
Season pages (/leagues/) | basketball-reference.com | player_team_minutes_2005_2026.csv | October 6, 2026 | Answered: 10 of 10 season totals pages (1999-00 to 2008-09), each with status 200 |
Franchise pages (/teams/) | basketball-reference.com | coach_ledger.csv, rosters_2026_10_06_bref.csv | August 31 and October 6, 2026 | Not asked |
| Team schedules and rosters | site.api.espn.com | espn_games_2022_2027.csv, rosters_2026_10_06.csv | October 6 and November 16, 2026 | Not asked |
That day we also asked stats.nba.com for two tables our data layer does not hold yet, the hustle stats (screen assists, deflections) and player tracking. In time order, every request of the day:
| Time | Request | What came back |
|---|---|---|
| 12:53:49 | stats.nba.com/robots.txt | Redirected (301) to www.nba.com/stats/robots.txt, which answered 404: no rules set |
| 12:54 | stats.nba.com/stats/leaguehustlestatsplayer (2024-25 season totals) | No answer; the request timed out after 45 seconds |
| 12:55:22 | stats.nba.com/stats/leaguedashptstats (defense tracking, 2024-25) | No answer; the request timed out after 90 seconds |
| 12:59:10 | basketball-reference.com/robots.txt | Answered (200): the rules for all crawlers allow the season pages and ask for 3 seconds between requests |
| 12:59:29 to 12:59:56 | Ten season totals pages, 1999-00 to 2008-09 | All ten answered (200), 14.6 MB in all, sent exactly 3 seconds apart |
Three things follow. First, the two new stats.nba.com tables never answered, so neither is in our files; we did not retry them under a browser's name. Second, the four stats.nba.com endpoints our files depend on were not asked that day, which is exactly what the cache in the etiquette section is for: the files were pulled once (June and September 2026) and every build since reads the saved copy. Third, Basketball-Reference answered every request, at the pace its robots.txt asks for. The practical lesson for your own scripts is the same one as above: identify yourself, keep a copy of everything you pull, and treat a host that stops answering as an answer.
The same call on December 2, 2026: the 2026-27 race so far
The first call on this page is a June 2026 pull of a finished season. To check that the tutorial still works as printed, we ran it again on December 2, 2026, about six weeks into the 2026-27 season, with the season string changed and nothing else that matters: nba_api 1.11.4, our own User-Agent (NBAAnalytic-data/1.0 with this site's contact page), and no browser headers. The league's stats host answered at once.
| Time | Request | What came back |
|---|---|---|
| 14:52:51 | stats.nba.com/robots.txt | Redirected (301) to www.nba.com/stats/robots.txt, which answered 404: no rules set |
| 14:52:54 | stats.nba.com/stats/leagueleaders (2026-27, points, per game), one plain request | Answered (200) in 0.8 seconds, 38,637 bytes |
| 14:54:50 | The same request through nba_api, made by the code below | Answered (200) in 1.2 seconds |
On November 2 two other endpoints never answered (the table above); this time the host answered in about a second. Nothing about the request changed: the same User-Agent and no nba.com headers. A timeout is worth one polite try on another day, not a disguise. Here is the call, with one new column added the way the DataFrame section showed, true shooting from the per-game points, field-goal attempts and free-throw attempts:
Pythonleaders = leagueleaders.LeagueLeaders(
season="2026-27", # was "2025-26" in the first call
season_type_all_star="Regular Season",
stat_category_abbreviation="PTS",
per_mode48="PerGame",
headers=HEADERS,
timeout=60,
)
df = leaders.get_data_frames()[0]
df["TS_PCT"] = df["PTS"] / (2 * (df["FGA"] + 0.44 * df["FTA"]))
print(len(df), "players,", df["GP"].min(), "to", df["GP"].max(), "games")
print(df.head(10)[["RANK", "PLAYER", "TEAM", "GP", "PTS", "TS_PCT"]].round(3).to_string(index=False))
And what it printed at 14:54 UTC:
Output286 players, 14 to 22 games
RANK PLAYER TEAM GP PTS TS_PCT
1 Luka Dončić LAL 19 35.8 0.604
2 Shai Gilgeous-Alexander OKC 20 32.0 0.580
3 Victor Wembanyama SAS 20 30.9 0.620
4 Giannis Antetokounmpo MIA 19 28.4 0.637
5 Scottie Barnes TOR 15 27.5 0.566
6 Jayson Tatum BOS 19 26.4 0.560
7 Jamal Murray DEN 18 25.9 0.646
8 Jalen Brunson NYK 21 25.9 0.542
9 Anthony Davis WAS 18 25.3 0.605
10 Donovan Mitchell CLE 20 25.2 0.593
| Rank | Player | Team | GP | MIN | PTS | TS% | 2025-26 PTS (rank) |
|---|---|---|---|---|---|---|---|
| 1 | Luka Dončić | LAL | 19 | 36.4 | 35.8 | 60.4% | 33.5 (1) |
| 2 | Shai Gilgeous-Alexander | OKC | 20 | 34.1 | 32.0 | 58.0% | 31.1 (2) |
| 3 | Victor Wembanyama | SAS | 20 | 30.8 | 30.9 | 62.0% | 25.0 (13) |
| 4 | Giannis Antetokounmpo | MIA | 19 | 32.3 | 28.4 | 63.7% | not listed |
| 5 | Scottie Barnes | TOR | 15 | 34.9 | 27.5 | 56.6% | 18.1 (41) |
| 6 | Jayson Tatum | BOS | 19 | 34.5 | 26.4 | 56.0% | not listed |
| 7 | Jamal Murray | DEN | 18 | 36.7 | 25.9 | 64.6% | 25.4 (12) |
| 8 | Jalen Brunson | NYK | 21 | 34.6 | 25.9 | 54.2% | 26.0 (10) |
| 9 | Anthony Davis | WAS | 18 | 34.2 | 25.3 | 60.5% | not listed |
| 10 | Donovan Mitchell | CLE | 20 | 33.6 | 25.2 | 59.3% | 27.9 (7) |
Luka Dončić leads again, at 35.8 points a game over 19 games against 33.5 over 64 last season, and Shai Gilgeous-Alexander is second again at 32.0. Three players average 30 or more, one more than in all of 2025-26 (2 of 234 qualified players), and 12 average 25 or more, against 13 last season. The largest rise in the top ten is Scottie Barnes, from 18.1 (41st) to 27.5 (5th) in 15 games; Victor Wembanyama has gone from 25.0 (13th) to 30.9 (3rd) with the best true shooting of the top three, 62.0%. Twenty games is about a quarter of a season, and averages this early move with every game: read the table as a dated snapshot, not a forecast.
The more useful lesson is in the empty cells. Three of the top ten have no 2025-26 line because LeagueLeaders lists only players who clear a games-played bar, and the response does not say where the bar sits. The 2025-26 table has 234 players, none with fewer than 58 games, while LeagueDashPlayerStats, the endpoint behind our player-season file, holds 582 players for the same season. Giannis Antetokounmpo (36 games), Jayson Tatum (16) and Anthony Davis (20) played in 2025-26 and fell short of the bar. It moves with the calendar, too: on December 2 the shortest line in the table is 14 games, and Anthony Edwards, third in 2025-26 at 28.8, is not among the 286 rows. If you need every player, ask LeagueDashPlayerStats; LeagueLeaders is the qualified list.
Two notes on the numbers. The endpoint returns per-game averages rounded to one decimal, so a TS% computed from them can differ in the last digit from one computed from season totals; our true-shooting explainer has the formula and the season-total version. And the league's terms of use (as we read them on October 10, 2026) limit its stats to news or private, non-commercial use, so this section shows ten rows of one response as a dated look at the scoring race; the full response is not republished here.
Where to go next
You now have the whole loop: install the package, call an endpoint, get a DataFrame, sort it, and do it without annoying the server. That's genuinely 80% of what we do to build the data pieces on this site; the other 20% is knowing which stat to ask for, which is a basketball question, not a Python one. Swap "PTS" for "REB" or "AST" in the call above and you've got the rebounding or assist leaders; reach for LeagueDashPlayerStats with measure_type="Advanced" and you've got the raw material for an efficiency study. The API is undocumented and a little cranky, but it's free, it's complete, and it's ten lines away. Go ask it something.
Sources & Further Reading
- Data source: NBA.com/stats, the (undocumented) stats endpoints this whole tutorial talks to.
- The Python package: nba_api on GitHub, whose README is the closest thing to a full endpoint reference.
- The runnable code for this article is our own build-side script (LeagueLeaders, PTS, PerGame; ShotChartDetail for Shai Gilgeous-Alexander; 2025-26, retrieved June 2026).
- The data-layer endpoint table and the November 2, 2026 request record (added November 17, 2026): our saved request records for that day (status, time and User-Agent of each request) and the file list in SOURCE.txt.
- The December 2, 2026 re-run (added that day): one plain request at 14:52:54 UTC and one nba_api 1.11.4 request at 14:54:50 UTC to LeagueLeaders (2026-27, PTS, PerGame), each after a robots.txt read and under our descriptive User-Agent; the 2025-26 comparison from the June 2026 copy of the first call and our player-season file (
LeagueDashPlayerStats, September 2026), listed in SOURCE.txt. - Plotting: matplotlib's
scatterreference.