How to Build an NBA Website with Python and Flask

You are going to build an NBA website in Python with Flask and the SportAPI basketball API. It has the standings of both conferences, the scores for any day, a box score for every game, and a page for each team and player. Pages are made when someone opens them, so live scores update while a game is on.

The whole example is about 150 lines of Python and six small templates. The full version of this idea is live at nba.sportapi.ai, with stat leaders, schedules and a page for every player in the league.

The standings page of the example app with the Eastern Conference table, team logos, wins, losses, percentage, games behind, last ten and streak
The standings page you will build. Screenshots show live data from 7 November 2026.

What you need

You need Python 3.11 or newer and a free SportAPI key. Sign up, confirm your e-mail address and copy the key from your dashboard. Install Flask and requests:

Terminal
pip install flask requests

The complete example has app.py, sportapi.py, a templates folder and a static folder. The app reads your key from the SPORTAPI_KEY environment variable, so the key never ends up in your code. Start it like this:

Terminal
export SPORTAPI_KEY="YOUR_API_KEY"   # on Windows: set SPORTAPI_KEY=YOUR_API_KEY
flask --app app run

Then open http://127.0.0.1:5000 in your browser.

Find the NBA in the API

The basketball API lives under /api/basketball. Send your key in the X-API-Key header. /api/basketball/leagues lists every league; the NBA has the slug nba, and you can use the slug everywhere instead of an ID.

Terminal
curl -H "X-API-Key: YOUR_API_KEY" https://sportapi.ai/api/basketball/leagues/nba
Response, shortened
{
  "success": true,
  "data": {
    "id": 1,
    "slug": "nba",
    "name": "NBA",
    "current_season": "2026-27",
    "seasons": [
      { "season": "2026-27", "games": 1273, "played": 199, "first_game": "2026-10-03T23:00:00Z", "last_game": "2027-04-12T00:30:00Z" }
    ],
    "teams": [
      { "id": 19, "slug": "atlanta-hawks", "name": "Atlanta Hawks", "abbreviation": "ATL", "conference": "Eastern Conference" }
    ]
  }
}

The answer has the current season, the number of games in it and all 30 teams with their conference.

Write one helper with a cache

All requests go through one function. It sends the key and keeps each answer in memory. The next call within ttl seconds gets the saved answer and doesn't touch the API.

sportapi.py
"""sportapi.py: calls the SportAPI basketball API and keeps each answer in memory for a while."""
import os
import time

import requests

API_KEY = os.environ.get("SPORTAPI_KEY", "YOUR_API_KEY")
BASE = "https://sportapi.ai/api/basketball"

session = requests.Session()
session.headers["X-API-Key"] = API_KEY
cache = {}   # path -> (time saved, answer)


def get(path, ttl=600, **params):
    """Returns the API answer for path, from the cache if it is younger than ttl seconds."""
    key = path + "?" + "&".join(f"{k}={v}" for k, v in sorted(params.items()))
    saved = cache.get(key)
    if saved and time.time() - saved[0] < ttl:
        return saved[1]
    try:
        response = session.get(BASE + path, params=params, timeout=20)
        response.raise_for_status()
        answer = response.json()
    except (requests.RequestException, ValueError):
        # Limit reached or a network problem: show the last answer if there is one
        return saved[1] if saved else None
    cache[key] = (time.time(), answer)
    return answer


logos = {}   # team id -> (image bytes, content type)


def logo(team_id):
    """A team logo, downloaded once. Your site serves it, so the browser never sees your key."""
    if team_id not in logos:
        try:
            response = session.get(f"{BASE}/teams/{team_id}/logo", timeout=20)
            response.raise_for_status()
        except requests.RequestException:
            return None
        logos[team_id] = (response.content, response.headers.get("Content-Type", "image/png"))
    return logos[team_id]

Each page decides how fresh its data must be. Standings change once a night, so they can wait ten minutes; a live score can wait one minute. If the API can't be reached or you hit your limit, get() returns the last answer it has, so the page still shows something.

The logo() helper downloads each team logo once. Your site serves the logos itself, so visitors never see your key.

Keep your API key on the server. Never call the API from JavaScript in the browser: the API does not allow calls from other sites, and every visitor would be able to see your key.

Start the Flask app

app.py starts with the imports and two template filters. The API gives every tip-off time in UTC. NBA fans read the schedule in US Eastern time, so the filters turn 2026-11-07T00:00:00Z into 7:00 PM and Fri, Nov 6. Without this, an evening game would show up on the wrong day.

app.py, first part
"""app.py: an NBA website in Flask on the SportAPI basketball API."""
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo

from flask import Flask, Response, abort, render_template, request

from sportapi import get, logo

app = Flask(__name__)
ET = ZoneInfo("America/New_York")   # NBA days and tip-off times are US Eastern time
MINUTE, HOUR = 60, 3600


def eastern(start):
    """The API gives tip-off in UTC: '2026-11-08T00:30:00Z'."""
    return datetime.fromisoformat(start.replace("Z", "+00:00")).astimezone(ET)


@app.template_filter("et")
def et_time(start):
    return eastern(start).strftime("%I:%M %p").lstrip("0")   # '7:30 PM'


@app.template_filter("et_day")
def et_day(start):
    t = eastern(start)
    return f"{t:%a, %b} {t.day}"   # 'Sat, Nov 7': the game day in the US, not in UTC

Every page extends one base template with the menu and the footer:

templates/base.html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% if live %}<meta http-equiv="refresh" content="60">{% endif %}
<title>{% block title %}NBA{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<header><a class="brand" href="/">NBA</a>
<nav><a href="/">Standings</a><a href="/scores">Scores</a></nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
<footer>Data from <a href="https://sportapi.ai/">SportAPI</a>. Times are US Eastern time.</footer>
</body>
</html>

Show the conference standings

The standings come from /api/basketball/standings/nba. The answer has two groups, Eastern Conference and Western Conference, each with 15 rows:

GET /api/basketball/standings/nba, shortened
{
  "success": true,
  "season": "2026-27",
  "data": [
    {
      "group": "Eastern Conference",
      "table": [
        {
          "position": 1,
          "team": { "id": 2, "slug": "philadelphia-76ers", "name": "Philadelphia 76ers", "abbreviation": "PHI" },
          "played": 10,
          "won": 8,
          "lost": 2,
          "win_pct": 0.8,
          "games_behind": 0,
          "home_record": "4-1",
          "away_record": "4-1",
          "last10": "8-2",
          "streak": "L1"
        }
      ]
    }
  ]
}

The route makes one request and passes both groups to the template:

app.py, the standings
# --- standings
@app.route("/")
def standings():
    answer = get("/standings/nba", ttl=10 * MINUTE)
    if not answer:
        abort(503)
    return render_template("standings.html", season=answer["season"], conferences=answer["data"])

The template loops through the conferences and their rows. Teams 1 to 6 go straight to the playoffs and teams 7 to 10 play in the play-in tournament, so those rows get a colored edge.

templates/standings.html
{% extends "base.html" %}
{% block title %}NBA Standings {{ season }}{% endblock %}
{% block content %}
<h1>NBA standings {{ season }}</h1>
{% for conf in conferences %}
<h2>{{ conf.group }}</h2>
<div class="scroll">
<table>
<tr><th>#</th><th class="left">Team</th><th>W</th><th>L</th><th>Pct</th><th>GB</th><th>L10</th><th>Strk</th></tr>
{% for row in conf.table %}
<tr{% if row.position <= 6 %} class="playoffs"{% elif row.position <= 10 %} class="play-in"{% endif %}>
<td>{{ row.position }}</td>
<td class="team"><img src="/logos/{{ row.team.id }}" alt="" width="24" height="24">
<a href="/teams/{{ row.team.slug }}">{{ row.team.name }}</a></td>
<td>{{ row.won }}</td><td>{{ row.lost }}</td>
<td>{{ "%.3f"|format(row.win_pct) }}</td>
<td>{{ row.games_behind or "-" }}</td><td>{{ row.last10 }}</td><td>{{ row.streak }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endfor %}
<p class="note">1-6: playoffs. 7-10: play-in tournament.</p>
{% endblock %}

List the scores for any day

/api/basketball/games/date/{date} returns the games of one day. Add tz=America/New_York, so the day starts and ends at midnight in New York, the way the NBA counts it, and league=nba, so you get only NBA games. One game looks like this:

GET /api/basketball/games/date/2026-11-06?tz=America/New_York&league=nba, one game
{
  "id": 1592,
  "season": "2026-27",
  "stage": "regular",
  "round": "NBA Cup - Group Play",
  "start": "2026-11-07T00:00:00Z",
  "status": "FT",
  "live": false,
  "period": 4,
  "clock": null,
  "home": { "id": 19, "name": "Atlanta Hawks", "slug": "atlanta-hawks", "abbreviation": "ATL", "score": 139, "periods": [28, 38, 39, 34] },
  "away": { "id": 34, "name": "Washington Wizards", "slug": "washington-wizards", "abbreviation": "WSH", "score": 132, "periods": [32, 27, 35, 38] },
  "venue": "State Farm Arena",
  "attendance": 15538,
  "has_boxscore": true
}

status is NS before the game, Q1 to Q4, HT or OT while it's on, and FT or AOT (after overtime) when it's over. live is true while the game is on.

app.py, the scores
# --- scores
@app.route("/scores")
def scores():
    today = datetime.now(ET).date()
    try:
        day = date.fromisoformat(request.args.get("date", ""))
    except ValueError:
        day = today
    path = f"/games/date/{day}"
    # Older days don't change. A late game can still be on after midnight, so yesterday counts as recent
    ttl = 24 * HOUR if day < today - timedelta(days=1) else 10 * MINUTE
    answer = get(path, ttl=ttl, tz="America/New_York", league="nba")
    games = answer["data"] if answer else []
    live = any(g["live"] for g in games)
    if live:
        # During games the same request is repeated after one minute instead of ten
        answer = get(path, ttl=MINUTE, tz="America/New_York", league="nba") or answer
        games = answer["data"]
    return render_template("scores.html", day=day, games=games, live=live,
                           prev=day - timedelta(days=1), next=day + timedelta(days=1))

The cache time depends on the day. Older days don't change, so they're kept for 24 hours. Today and yesterday are kept for ten minutes. When a game is on, the same request is repeated after one minute instead, and the template adds a tag that reloads the page every 60 seconds.

templates/scores.html
{% extends "base.html" %}
{% block title %}NBA Scores {{ day.strftime("%B") }} {{ day.day }}, {{ day.year }}{% endblock %}
{% block content %}
<h1>NBA scores, {{ day.strftime("%A, %B") }} {{ day.day }}</h1>
<p class="days"><a href="/scores?date={{ prev }}">&larr; {{ prev.strftime("%b") }} {{ prev.day }}</a>
<a href="/scores?date={{ next }}">{{ next.strftime("%b") }} {{ next.day }} &rarr;</a></p>
{% for g in games %}
<a class="game{% if g.live %} live{% endif %}" href="/games/{{ g.id }}">
<span class="side"><img src="/logos/{{ g.away.id }}" alt="" width="28" height="28">{{ g.away.name }}</span>
<span class="mid">
{% if g.status == "NS" %}{{ g.start|et }}
{% else %}<b>{{ g.away.score }} &ndash; {{ g.home.score }}</b>
<small>{% if g.live %}{{ g.status }} {{ g.clock or "" }}{% else %}Final{% endif %}</small>{% endif %}
</span>
<span class="side home">{{ g.home.name }}<img src="/logos/{{ g.home.id }}" alt="" width="28" height="28"></span>
</a>
{% else %}
<p>No NBA games on this day.</p>
{% endfor %}
{% endblock %}
The scores page for 6 November 2026 with final scores and team logos
The scores for one day, with links to the previous and next day.

Show a box score

/api/basketball/games/{id}/players gives the game and a row for every player on both teams: minutes, points, rebounds, assists, shots and plus-minus. Players who didn't play have a reason in dnp.

GET /api/basketball/games/1592/players, shortened
{
  "success": true,
  "game": { "id": 1592, "status": "FT", "live": false, "home": { "name": "Atlanta Hawks", "score": 139 }, "away": { "name": "Washington Wizards", "score": 132 } },
  "data": {
    "away": [
      {
        "player": { "id": 507, "slug": "kyshawn-george", "name": "Kyshawn George", "position": "F" },
        "starter": true,
        "dnp": null,
        "minutes": 40,
        "pts": 33,
        "reb": 4,
        "ast": 7,
        "fgm": 10,
        "fga": 20,
        "tpm": 5,
        "tpa": 7,
        "plus_minus": -5
      }
    ],
    "home": []
  }
}

Team totals such as field goal percentage and points in the paint come from /api/basketball/games/{id}/stats.

app.py, the box score
# --- game
@app.route("/games/<int:game_id>")
def game(game_id):
    path = f"/games/{game_id}/players"
    box = get(path, ttl=HOUR)
    if not box:
        abort(404)
    # A finished game can wait an hour; a game that is on or about to start is read every minute
    ttl = HOUR if box["game"]["status"] in ("FT", "AOT") else MINUTE
    box = get(path, ttl=ttl) or box
    stats = get(f"/games/{game_id}/stats", ttl=ttl)
    return render_template("game.html", game=box["game"], box=box["data"], live=box["game"]["live"],
                           stats=stats["data"] if stats else None)

The template shows the score by quarter, one table per team and the team stats. Before tip-off it shows a short note instead.

templates/game.html
{% extends "base.html" %}
{% block title %}{{ game.away.name }} vs {{ game.home.name }} Box Score{% endblock %}
{% block content %}
{% if game.status == "NS" %}
<h1>{{ game.away.name }} at {{ game.home.name }}</h1>
{% else %}
<h1>{{ game.away.name }} {{ game.away.score }}, {{ game.home.name }} {{ game.home.score }}</h1>
{% endif %}
<p>{{ "Final" if game.status in ("FT", "AOT") else ("Scheduled" if game.status == "NS" else game.status) }} · {{ game.start|et_day }}, {{ game.start|et }} ET · {{ game.venue }}</p>

{% if game.status == "NS" %}
<p>The box score appears here when the game starts.</p>
{% else %}
<div class="scroll">
<table class="line">
<tr><th class="left">Team</th>{% for p in game.home.periods %}<th>{{ loop.index if loop.index <= 4 else "OT" }}</th>{% endfor %}<th>T</th></tr>
{% for side in (game.away, game.home) %}
<tr><td>{{ side.abbreviation }}</td>{% for p in side.periods %}<td>{{ p }}</td>{% endfor %}<td><b>{{ side.score }}</b></td></tr>
{% endfor %}
</table>
</div>

{% for side in ("away", "home") %}
<h2>{{ game[side].name }}</h2>
<div class="scroll">
<table>
<tr><th class="left">Player</th><th>Min</th><th>Pts</th><th>Reb</th><th>Ast</th><th>FG</th><th>3PT</th><th>+/-</th></tr>
{% for row in box[side] if not row.dnp %}
<tr{% if row.starter %} class="starter"{% endif %}>
<td><a href="/players/{{ row.player.slug }}">{{ row.player.name }}</a></td>
<td>{{ row.minutes }}</td><td><b>{{ row.pts }}</b></td><td>{{ row.reb }}</td><td>{{ row.ast }}</td>
<td>{{ row.fgm }}-{{ row.fga }}</td><td>{{ row.tpm }}-{{ row.tpa }}</td><td>{{ row.plus_minus }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endfor %}

{% if stats and stats.home %}
<h2>Team stats</h2>
<table>
<tr><th></th><th>{{ game.away.abbreviation }}</th><th>{{ game.home.abbreviation }}</th></tr>
{% for key, label in [("fg_pct", "Field goal %"), ("tp_pct", "3-point %"), ("reb", "Rebounds"), ("ast", "Assists"), ("tov", "Turnovers"), ("pts_paint", "Points in the paint")] %}
<tr><td>{{ label }}</td><td>{{ stats.away[key] }}</td><td>{{ stats.home[key] }}</td></tr>
{% endfor %}
</table>
{% endif %}
{% endif %}
{% endblock %}
The box score of Washington Wizards at Atlanta Hawks with the score by quarter and player stats
The box score of one game.

Build the team pages

/api/basketball/teams/slug/{slug} returns the team with its coach, its place in the standings and its last and next games. The roster is a separate request, /api/basketball/teams/{id}/roster.

GET /api/basketball/teams/slug/los-angeles-lakers, shortened
{
  "success": true,
  "data": {
    "id": 5,
    "slug": "los-angeles-lakers",
    "name": "Los Angeles Lakers",
    "abbreviation": "LAL",
    "coach_name": "JJ Redick",
    "standings": [
      { "season": "2026-27", "group": "Western Conference", "position": 1, "won": 8, "lost": 2, "streak": "W4" }
    ],
    "last_games": [ { "id": 1599, "start": "2026-11-07T03:00:00Z", "status": "FT" } ],
    "next_games": [ { "id": 1609, "start": "2026-11-08T23:00:00Z", "status": "NS" } ]
  }
}
app.py, the team pages
# --- team
@app.route("/teams/<slug>")
def team(slug):
    answer = get(f"/teams/slug/{slug}", ttl=HOUR)
    if not answer:
        abort(404)
    t = answer["data"]
    roster = get(f"/teams/{t['id']}/roster", ttl=6 * HOUR)
    return render_template("team.html", team=t, roster=roster["data"] if roster else [])

The roster changes rarely, so it's kept for six hours. The team.html template is in the example download.

The Los Angeles Lakers page with coach, record, next games, latest results and roster
The Los Angeles Lakers page.

Build the player pages

/api/basketball/players/slug/{slug} returns the player with averages for every season and the last ten games. A player's seasons can include other competitions, so the route keeps only the NBA ones.

GET /api/basketball/players/slug/luka-doncic, shortened
{
  "success": true,
  "data": {
    "id": 228,
    "slug": "luka-doncic",
    "name": "Luka Doncic",
    "position": "G",
    "jersey": "77",
    "height_cm": 203,
    "team": { "id": 5, "slug": "los-angeles-lakers", "name": "Los Angeles Lakers" },
    "seasons": [
      { "league": { "slug": "nba" }, "season": "2026-27", "stage": "regular", "games": 9, "minutes": 35.9, "pts": 40.1, "reb": 7.8, "ast": 7.7, "fg_pct": 49.8, "tp_pct": 41.9 }
    ],
    "last_games": [
      { "game_id": 1599, "start": "2026-11-07T03:00:00Z", "home": true, "opponent": { "abbreviation": "POR" }, "result": "W", "score": "124-118", "minutes": 38, "pts": 53, "reb": 5, "ast": 5 }
    ]
  }
}
app.py, the player pages
# --- player
@app.route("/players/<slug>")
def player(slug):
    answer = get(f"/players/slug/{slug}", ttl=HOUR)
    if not answer:
        abort(404)
    p = answer["data"]
    seasons = [s for s in p["seasons"] if s["league"]["slug"] == "nba"]
    return render_template("player.html", player=p, seasons=seasons)
The Luka Doncic page with NBA season averages and his last games
The Luka Doncic page.

Serve the team logos

The last route returns a logo from the logo() helper. The browser is told to keep it for a week, and the app downloads each logo only once.

app.py, the logos and the end
# --- logos
@app.route("/logos/<int:team_id>")
def team_logo(team_id):
    image = logo(team_id)
    if not image:
        abort(404)
    return Response(image[0], mimetype=image[1], headers={"Cache-Control": "public, max-age=604800"})


if __name__ == "__main__":
    app.run(debug=True)

Run it on a server

The Flask development server is for your own computer only. On a server, run the app with Gunicorn. Use one worker process with several threads: the cache lives in the memory of the process, and each extra process would keep its own copy and make its own requests.

Terminal
pip install gunicorn
SPORTAPI_KEY=YOUR_API_KEY gunicorn --workers 1 --threads 8 --bind 127.0.0.1:8000 app:app

Then let nginx pass the requests to it:

nginx
location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
}

Stay within your request limit

The free plan includes 1,000 requests a day and 7,000 a month. Thanks to the cache, a day of normal use costs far less than that. The standings cost at most 144 requests a day. Today's scores cost about 150, plus one a minute while games are on. A game, team or player page costs a request only when someone opens it and the saved copy is too old. On a site with visitors every day, the standings and scores alone come to about 9,000 requests a month, more than the free plan's 7,000, so raise the cache times or move to a paid plan.

Search engines are a different story. A crawler can open every game, team and player page in one go, which is close to 2,000 pages in the middle of the season. For a public site, either pick a bigger plan or make the pages in advance: nba.sportapi.ai refreshes its data on a schedule and serves ready HTML files, so visitors and crawlers never cause a request.

A box score page on nba.sportapi.ai with the score, quarters, top scorers and team stats
A box score on nba.sportapi.ai, made in advance from saved data.

Where to go next

  • Add the stat leaders from /api/basketball/leagues/nba/leaders?stat=pts,reb,ast, as on the leaders page of the full site.
  • Show the last meetings of two teams before a game with /api/basketball/games/h2h/{team1}/{team2}.
  • Use the same code for the WNBA or college basketball: change the league slug.

The full list of basketball endpoints is in the API documentation, and the Basketball API page shows which leagues and data are covered.