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:

Python
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:

Python
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.

Horizontal bar chart of the 2025-26 NBA per-game scoring leaders, led by Luka Dončić at 33.5 points, Shai Gilgeous-Alexander at 31.1, and Anthony Edwards at 28.8.
The output of the LeagueLeaders call above: the 2025-26 top ten scorers, per game. Source: NBA Stats API via nba_api · 2025-26 · retrieved June 2026.

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:

Python
# 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 a measure_type of Base, Advanced, Usage, or Scoring. 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? BoxScoreTraditionalV2 and ShotChartDetail; 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:

2025-26 per-game scoring leaders. Source: NBA Stats API via nba_api (LeagueLeaders, PerGame), retrieved June 2026.
RankPlayerTeamPPG
1Luka DončićLAL33.5
2Shai Gilgeous-AlexanderOKC31.1
3Anthony EdwardsMIN28.8
4Jaylen BrownBOS28.7
5Tyrese MaxeyPHI28.3
6Kawhi LeonardLAC27.9
7Donovan MitchellCLE27.9
8Nikola JokićDEN27.7
9Devin BookerPHX26.1
10Jalen BrunsonNYK26.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:

Python
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:

Python
import 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.

Python
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.

Shai Gilgeous-Alexander's 1,321 field-goal attempts on a drawn half-court, made shots as teal dots and misses as orange x's, clustered heavily at the rim and across the mid-range, with 731 makes for 55.3% from the field.
Every shot Shai Gilgeous-Alexander took in 2025-26, plotted as a scatter of makes and misses on a drawn half-court: 1,321 attempts, 731 made, 55.3% from the field. Source: NBA Stats API via nba_api (ShotChartDetail) · 2025-26 · retrieved June 2026, before the October 10 header change.

The zone table is where the season's shape shows:

Shai Gilgeous-Alexander: field goals by court zone, 2025-26. Source: NBA Stats API via nba_api (ShotChartDetail), retrieved June 2026.
ZoneFGAFGMFG%
Restricted Area36526071.2
Mid-Range35519554.9
In The Paint (Non-RA)30316153.1
Above the Break 328010938.9
Left Corner 313430.8
Right Corner 35240.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.

The endpoints our data layer calls, the files built from each, the last pull, and the November 2, 2026 result. "Not asked" means no request went to that endpoint that day; its files come from the saved copy.
EndpointHostFiles built from itLast pulledNovember 2, 2026
LeagueDashTeamStatsstats.nba.comteam_seasons_2000_2026.csv, team_box_2005_2026.csv, team_preseason_2021_2026.csvJune 2026Not asked
LeagueDashPlayerStatsstats.nba.complayer_seasons_2005_2026.csvSeptember 2026Not asked
DraftHistorystats.nba.comdraft_history.csvSeptember 2026Not asked
LeagueGameLogstats.nba.comnba_games_2025_26.csv, game_box_2025_26.csv, team_game_sequence_2024_2026.csvJune 2026Not asked
Season pages (/leagues/)basketball-reference.complayer_team_minutes_2005_2026.csvOctober 6, 2026Answered: 10 of 10 season totals pages (1999-00 to 2008-09), each with status 200
Franchise pages (/teams/)basketball-reference.comcoach_ledger.csv, rosters_2026_10_06_bref.csvAugust 31 and October 6, 2026Not asked
Team schedules and rosterssite.api.espn.comespn_games_2022_2027.csv, rosters_2026_10_06.csvOctober 6 and November 16, 2026Not 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:

Every request of November 2, 2026 (times in UTC), with the same descriptive User-Agent on each.
TimeRequestWhat came back
12:53:49stats.nba.com/robots.txtRedirected (301) to www.nba.com/stats/robots.txt, which answered 404: no rules set
12:54stats.nba.com/stats/leaguehustlestatsplayer (2024-25 season totals)No answer; the request timed out after 45 seconds
12:55:22stats.nba.com/stats/leaguedashptstats (defense tracking, 2024-25)No answer; the request timed out after 90 seconds
12:59:10basketball-reference.com/robots.txtAnswered (200): the rules for all crawlers allow the season pages and ask for 3 seconds between requests
12:59:29 to 12:59:56Ten season totals pages, 1999-00 to 2008-09All 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.

The requests of December 2, 2026 (times in UTC), each under the same descriptive User-Agent. The nba_api run read robots.txt again before its request, as every run of our scripts does.
TimeRequestWhat came back
14:52:51stats.nba.com/robots.txtRedirected (301) to www.nba.com/stats/robots.txt, which answered 404: no rules set
14:52:54stats.nba.com/stats/leagueleaders (2026-27, points, per game), one plain requestAnswered (200) in 0.8 seconds, 38,637 bytes
14:54:50The same request through nba_api, made by the code belowAnswered (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:

Python
leaders = 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:

Output
286 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
The 2026-27 scoring leaders on December 2, 2026, per game, from the LeagueLeaders response above (teams as the response lists them). TS% computed from the per-game columns. Last column: points per game and rank in the 2025-26 leaders table from the first call. Source: NBA Stats API via nba_api · 2026-27 · retrieved December 2, 2026, 14:54 UTC.
RankPlayerTeamGPMINPTSTS%2025-26 PTS (rank)
1Luka DončićLAL1936.435.860.4%33.5 (1)
2Shai Gilgeous-AlexanderOKC2034.132.058.0%31.1 (2)
3Victor WembanyamaSAS2030.830.962.0%25.0 (13)
4Giannis AntetokounmpoMIA1932.328.463.7%not listed
5Scottie BarnesTOR1534.927.556.6%18.1 (41)
6Jayson TatumBOS1934.526.456.0%not listed
7Jamal MurrayDEN1836.725.964.6%25.4 (12)
8Jalen BrunsonNYK2134.625.954.2%26.0 (10)
9Anthony DavisWAS1834.225.360.5%not listed
10Donovan MitchellCLE2033.625.259.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 scatter reference.

How this was made

Published by NBAAnalytic from public data and the sources named in this piece. How this site is made · the methodology