Chapter 1 of ?
python 22 min read

Python for Data Science — Chapter 18: Simple APIs

APIs — Software's Universal Language

An API (Application Program Interface) is a contract between two pieces of software — one exposes capabilities, the other consumes them. You don't need to know how an API works internally, only its inputs and outputs. In this chapter we cover three levels: local library APIs (like Pandas), internet REST APIs, and a real-world NBA data example.

📦
18.1 What is an API?
The black-box principle
🌐
18.2 REST APIs
HTTP, JSON, Request / Response
🏀
18.3 NBA API
Real data. Live endpoints.

18.1 What Is an API?

Think of an API like a restaurant menu. The kitchen (service) is complex — but the menu (API) tells you exactly what you can order (inputs) and what you'll get back (outputs). You never need to walk into the kitchen.

import pandas as pd

# Create a dictionary — your "order"
data = {
    "Artist": ["MJ", "AC/DC", "Pink Floyd"],
    "Album":  ["Thriller", "Back in Black", "Dark Side"],
    "Year":   [1982, 1980, 1973]
}

# Pass it to the Pandas API
df = pd.DataFrame(data)   # ← API call

# Use the API — you don't know how it
# renders a table, you just call .head()
print(df.head())
print(df.mean(numeric_only=True))

The Black-Box Principle: When you write pd.DataFrame(data), you're making an API call. Pandas is implemented partly in C and Cython — you don't need to know that. You provide data in, get a DataFrame out. The same is true for .head(), .mean(), and every other method.

Key insight: APIs are simply functions with a published contract. The implementation is hidden; the interface is public.
Interactive API Bridge Diagram

Click each step to animate the data flow through the Pandas API. Watch how your code (the client) never touches the internals.

🧑‍💻
Your Code
(Client)
Input / Request
🔌
API Interface
(Contract)
Internal Call
⚙️
Implementation
(Hidden internals)
Output / Response
📊
Result
(DataFrame / Value)
API Bridge LogReady
>>> Click Step 1 to begin the animation.
Pandas API — Step-by-Step Walkthrough

Click each step to see how your Python code translates into API calls and what each one returns.

1
Create a Dictionary
data = {"Artist": [...], "Year": [...]}
2
Build DataFrame (API call)
df = pd.DataFrame(data)
3
Call .head() method
df.head() # First 5 rows
4
Call .mean() method
df.mean(numeric_only=True)
Step OutputClick a step →
>>> Click a step on the left to see what the Pandas API returns.
Try It Yourself »

18.2 REST APIs — Talking Over the Internet

REST stands for Representational State Transfer. A REST API lets your program communicate with a web service over the internet using standard HTTP messages. Your code becomes the client, the web service is the resource, and the location of the service is the endpoint.

🧑‍💻
Client
Your Python program
📍
Endpoint
URL the client calls
📨
Request
HTTP message sent
📬
Response
JSON data returned
REST Request/Response Simulator

Select an HTTP method, then click Send Request to animate the full client → endpoint → server → response flow.

🧑‍💻
CLIENT
Your Code
🔗
ENDPOINT
api.example.com
🖥️
SERVER
Web Resource
HTTP Methods Reference
GETRead / Retrieve data
POSTCreate new resource
PUTUpdate existing resource
DELETERemove a resource
Status Codes
200 OK 201 Created 400 Bad Request 404 Not Found 500 Server Error
HTTP Transaction LogReady
>>> Select a method and click "Send Request" to simulate an HTTP transaction.
JSON — The Language of REST APIs

REST APIs usually send and receive JSON (JavaScript Object Notation). It maps directly to Python dictionaries and lists. Click a field to highlight its role.

"team": { "id": 1610612744, "name": "Golden State Warriors", "city": "San Francisco", "wins": 57, "losses": 25, "playoffs": true }
Python EquivalentDict Access
>>> Click a JSON field to see how to access it in Python.
Python — Making Real HTTP Requests
import requests

# 1. Send a GET request to a REST endpoint
url = "https://api.example.com/teams/1610612744"
response = requests.get(url)

# 2. Check the status code
print("Status:", response.status_code)  # 200

# 3. Parse the JSON response into a Python dict
data = response.json()

# 4. Access fields just like a dictionary
print("Team:", data["team"]["name"])
print("Wins:", data["team"]["wins"])

# 5. Loop through a list response
teams = requests.get("https://api.example.com/teams").json()
for team in teams["results"]:
    print(team["name"], "-", team["city"])
requests.get(url) — sends an HTTP GET message. Python's requests library handles TCP connections, headers, and encoding automatically.
response.json() — converts the JSON string response into a native Python dictionary or list. Zero parsing code required.
status_code — always check this first. 200 = success; 404 = not found; 401 = unauthorized.
Try It Yourself »

18.3 Real World: NBA API Case Study

Sports data changes constantly — new games, new stats, new standings. This makes it a perfect real-world API use case. The NBA API (by Swar Patel) wraps NBA.com endpoints so you can pull any team's game log, stats, and standings with a single Python call.

from nba_api.stats.static import teams
from nba_api.stats.endpoints import leaguegamefinder
import pandas as pd

# Step 1 — Get all teams as a list of dicts
nba_teams = teams.get_teams()

# Step 2 — Convert to DataFrame for easy lookup
teams_df = pd.DataFrame(nba_teams)

# Step 3 — Find the Warriors' unique ID
warriors_row = teams_df[teams_df["nickname"] == "Warriors"]
warriors_id  = warriors_row["id"].values[0]
print("Warriors ID:", warriors_id)

# Step 4 — Make the API call
gamefinder = leaguegamefinder.LeagueGameFinder(
    team_id_nullable=warriors_id
)
games_df = gamefinder.get_data_frames()[0]
print(games_df[["GAME_DATE","MATCHUP","PLUS_MINUS"]].head())

What's happening under the hood? When you call LeagueGameFinder(), the nba_api library builds an HTTP GET request, sends it to an NBA.com endpoint, receives a JSON payload, and converts it to a DataFrame — all automatically.

PLUS_MINUS column: If positive → Warriors won by that margin. If negative → they lost by that margin. This one column tells the entire story of every game.
MATCHUP: GSW vs. TOR = home game | GSW @ TOR = away game. The vs. / @ symbols encode home/away.
NBA API Data Explorer

This simulates the Warriors' game log from the NBA API. Filter by game type and see the PLUS_MINUS chart update in real time.

GAME_DATEMATCHUPWLPTSOPP_PTSPLUS_MINUS
PLUS_MINUS Chart — All Games
Win Loss
API Response (simulated)
>>> Click a filter to load game data.
NBA API — Full Request Pipeline

Click Trace Request to step through every layer — from your Python line, through the nba_api library, to NBA.com servers, and back as a DataFrame.

Try It Yourself »

Chapter 18 Quiz

1. What is the core purpose of an API?

2. In REST, what does the client send to the server — and what does the server return?

3. In the NBA game log, a MATCHUP shows "GSW @ TOR". What does the @ symbol indicate?

4. Which Python method parses a REST API's JSON response into a native Python dictionary?

Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *