import requests
url = "https://en.wikipedia.org/w/api.php"
params = {
"action": "query", # we want to query for information
"titles": "University of Colorado Boulder", # about this article
"prop": "info", # specifically, basic info about the page
"format": "json", # return the response as JSON
}
# Define these once near the top of your script and reuse them everywhere
CLIENT = "WebDataScience/1.0 (your-email@colorado.edu)"
HEADERS = {"User-Agent": f"{CLIENT} python-requests/{requests.__version__}"}
response = requests.get(url, params=params, headers=HEADERS)
data = response.json()
print(data)
# {'batchcomplete': '', 'query': {'pages': {'289672': {'pageid': 289672, 'ns': 0, 'title': 'University of Colorado Boulder', 'contentmodel': 'wikitext', 'pagelanguage': 'en', 'pagelanguagehtmlcode': 'en', 'pagelanguagedir': 'ltr', 'touched': '2026-10-15T21:52:24Z', 'lastrevid': 1380246879, 'length': 95273}}}}10 Introduction to APIs: Wikipedia
- Explain what an API is and how it differs from web scraping as a data access method
- Find Wikipedia’s less-visible features (talk pages, revision histories, pageviews, links, categories, templates, user contributions) and the API endpoint that reads each one
- Read API documentation to identify endpoints, parameters, and response formats
- Construct parameterized API requests and handle pagination with continuation tokens
- Explain what a pageview counts, and what changed when automated traffic was reclassified
- Move from raw requests to a client library, and say what the library does for you
Run this chapter’s code as you read: open the companion notebook (see Appendix A for all of them).
10.1 What Is an API?
An API (Application Programming Interface) is a contract between a client and a server that specifies what data you can request, what parameters you can pass, and in what format you will receive the response. Unlike web scraping, where you reverse-engineer the HTML structure of a page designed for human readers, APIs provide structured, documented, and intentional access to data. They return clean JSON rather than cluttered HTML. They offer stable endpoints rather than fragile CSS selectors. And they come with documentation that tells you exactly what is available and how to ask for it.
The tradeoff is that APIs only expose what their operators choose to expose. You cannot query a field that the API does not provide. You cannot exceed the rate limits the server enforces. And as Chapter 3 describes, APIs can be restricted, repriced, or shut down entirely at the operator’s discretion. But when they are available, APIs are almost always preferable to scraping.
This chapter marks the transition from document scraping (Part II) to API-based data access (Part III). The skills you learn here — reading documentation, constructing parameterized URLs, handling pagination, parsing nested JSON responses — transfer directly to every API you will work with in subsequent chapters.
10.2 A Tour of Wikipedia
You have met Wikipedia’s article on the University of Colorado Boulder twice already. In Chapter 1, requests.get() fetched its HTML, and the pageviews API counted its readers. In Chapter 5, DevTools showed the requests a browser makes to draw it, and the Action API’s prop=info described it. This chapter returns to the same article, and to the city around it, Boulder, Colorado, to read Wikipedia the way its editors and researchers do.
Most readers see an article and nothing else. Behind every article sits a set of other pages and records that Wikipedia keeps in the open: who changed what and when, what editors argued about, how many people read it each day, what it links to and what links to it, and the same topic in other languages. Research on Wikipedia, including how it covers breaking news (Keegan et al. 2013; Keegan 2020) and how its editors make and change its rules (Keegan and Fiesler 2017), is built on these records. Each one has an API endpoint, so anything you can see in the interface, you can count. Wikipedia has kept these records open while commercial platforms closed theirs, which is why this book teaches APIs with it, as “Social History and Public Interest”, at the end of this chapter, describes.
10.2.1 The Article
The article itself is one page among several. The tabs above it lead to the others (Figure 10.1): the Article ①, its Talk page ②, and View history ③. The languages button ④ lists the editions that have an article on the same topic. Inside the text, each blue wikilink ⑤ points to another article. The box at the right is an infobox ⑥, filled in by a template: a reusable piece of wikitext that thousands of university articles share, so their infoboxes have the same fields in the same order.
10.2.2 Links In, Links Out, and Languages
A wikilink is a citation of another article, and the set of an article’s links is a small map of what its editors think it connects to. The reverse map is What links here (Figure 10.2): every page whose text links to this one ①, with filters for redirects, links, and transclusions ②. Interlanguage links (Figure 10.3) connect the same topic across Wikipedia’s editions: the menu’s search box ① and its list of editions ②. Each edition is written by its own community, so the articles are not translations of each other.
10.2.3 References
An article’s claims rest on its references (Figure 10.4): the References heading ① and the numbered citations under it ②. Each citation names a source, its publisher, and the date an editor retrieved it, and many add a link to an archived copy, the kind of capture Chapter 7 taught you to read. Wikipedia’s policy is that a claim someone might challenge needs a source a reader can check, so the references are the article’s evidence, and the links in them lead out of Wikipedia to the rest of the web.
In the API, the links in an article’s references, and anywhere else in its text, are prop=extlinks: one entry per external URL.
10.2.4 Categories and Templates
At the foot of the article, categories (Figure 10.5) ① file it with other pages: other universities founded in 1876, other flagship universities, other tourist attractions in Boulder. Each category is a page that lists its members, and categories sit inside larger categories, so together they make a rough map of what Wikipedia’s editors think belongs together. Templates are the reusable boxes you saw in the article: the infobox, the navigation boxes at the foot of the page, and the banners on the talk page below. An article that uses a template has the template’s text copied into it each time the page is drawn, which is why What links here can filter out “transclusions”. Both are kept by editors, so both are as consistent as the editors who maintain them.
In the API, an article’s categories are prop=categories and its templates are prop=templates. Some categories are hidden from readers, as “Getting Links, Categories, Templates, and Languages” shows.
10.2.5 The Talk Page
Every article has a talk page (Figure 10.6) where editors discuss changes before or after they make them. Its header ① says what the page is for and links the rules for discussing, such as assuming good faith, and the banners under it ② record the article’s quality rating and the WikiProjects that look after it. Below them are the discussions themselves, signed and dated, and older ones are moved to archives. Where an article’s revision history records what changed, its talk page often records why, and what editors disagreed about on the way.
A talk page is a page like any other, in the Talk namespace, so every request in this chapter works on it: ask for titles=Talk:University of Colorado Boulder.
10.2.6 The Revision History
The revision history (Figure 10.7) lists every edit ever made to the article, one row each: when ①, by whom ②, how many bytes it added or removed ③, and the editor’s summary ④. Editors’ usernames are public; many are pseudonyms, and edits without an account are listed under a temporary account name. Any past version can be opened, and any two compared, so the history is a complete record of how the article came to say what it says.
In the API, the history is prop=revisions, which “Getting Revisions”, below, pages through.
10.2.7 Pageviews
Wikipedia counts its readers, and publishes the counts. The Pageviews Analysis tool, linked from every article’s Page information, charts them (Figure 10.8): daily views ① and the period’s totals ②. The same numbers come from the REST pageviews API that “Getting Pageviews”, below, calls: the tool’s total for the quarter is the sum of the monthly counts for July, August, and September 2026 that the code in “What a Pageview Counts” prints.
10.2.8 User Pages and Contributions
Editors have pages too. A user page (Figure 10.9) is where an editor describes themself: here, Jimbo Wales, Wikipedia’s co-founder ① ②. Their contributions (Figure 10.10) list every edit they have made, across all of Wikipedia: when ①, to which page ②, by how many bytes ③, and with what summary ④.
10.2.9 From the Interface to the API
Each feature on the tour has an endpoint. Most are in the MediaWiki Action API, at https://en.wikipedia.org/w/api.php, and pageviews are in the Wikimedia REST API. The rest of the chapter calls them.
| What you see | Where | API request |
|---|---|---|
| The article’s basic facts | the article | action=query&prop=info |
| Wikilinks out | the article’s text | action=query&prop=links |
| What links here | Tools → What links here | action=query&list=backlinks |
| Templates | the infobox and other boxes | action=query&prop=templates |
| Categories | the foot of the article | action=query&prop=categories |
| References’ links | References | action=query&prop=extlinks |
| Other languages | the languages button | action=query&prop=langlinks |
| Talk page | the Talk tab | any of the above, for titles=Talk:… |
| Revision history | View history | action=query&prop=revisions |
| Pageviews | Page information → Page views | REST: /metrics/pageviews/per-article/… |
| User contributions | Special:Contributions | action=query&list=usercontribs |
10.3 The Anatomy of an API Call
Every request to the MediaWiki Action API follows the same structure: a base URL, an action parameter specifying what you want to do, additional parameters narrowing your request, and a format parameter specifying the response format. Here is the request from Chapter 5 again:
The HEADERS constant deserves a comment before we go further. The Wikimedia User-Agent policy asks every client to identify itself with a descriptive User-Agent string that includes contact information. Since 2026, Wikimedia’s rate limits also depend on it: a client that identifies itself gets far more requests a minute than one that doesn’t. Put your own email address in place of your-email@colorado.edu, keeping the policy’s form: a name and version, your contact information in parentheses, then the library that sends the request and its version, here python-requests/ and the number requests.__version__ gives. CLIENT holds the first two parts on their own, because mwclient, later in this chapter, adds its own name and version to whatever you give it.
The API’s address starts with /w/, and Wikipedia’s robots.txt, which Chapter 2 read, says Disallow: /w/ to every crawler. As that chapter explains, robots.txt addresses crawlers that find pages by following links; a documented API has rules of its own, which are the ones this chapter follows: the User-Agent policy, the rate limits in “Common Issues to Debug”, Wikimedia’s Terms of Use, and its API etiquette, which asks for one request at a time. The pageviews API, later in this chapter, is on wikimedia.org, which serves no robots.txt at all (checked 2026-11-18).
The same request works in a browser. Paste the address that requests builds into the address bar, with format=jsonfm in place of format=json, and the API lays its JSON out as a web page (Figure 10.11). Under pages is one key, the page’s ID ①, and under it the facts prop=info asks for, such as the article’s length in bytes ②. The API sandbox goes further: it builds a request from a form, with every module and parameter documented beside it, and shows the request it made, so you can copy it into Python.
format=jsonfm, October 2026. The page’s ID ① is the key under pages, and length ② is the article’s size in bytes.
The response is a nested JSON structure. You navigate it one level at a time:
# The data lives inside data > query > pages > {page_id}
pages = data["query"]["pages"]
# Page IDs are keys; take the first (and only) one
page_id = list(pages.keys())[0]
page_info = pages[page_id]
print(f"Title: {page_info['title']}")
print(f"Page ID: {page_info['pageid']}")
print(f"Length: {page_info['length']:,} bytes")
# Title: University of Colorado Boulder
# Page ID: 289672
# Length: 95,273 bytesThis nested navigation pattern — data["query"]["pages"][page_id] — is consistent across the MediaWiki API. Once you internalize it, every endpoint feels familiar.
For strategies on reading and navigating unfamiliar API documentation, see Missing Manual Chapter 5: Reading Official Documentation.
10.4 Getting Revisions
Every edit ever made to a Wikipedia article is recorded and accessible through the API. The revisions endpoint returns metadata about each edit: who made it, when, how much the article size changed, and what edit summary they left. One request returns at most 500 revisions, so the function asks again until the API says there are no more:
import time
import pandas as pd
def get_revisions(title, until="2026-09-30T23:59:59Z"):
url = "https://en.wikipedia.org/w/api.php"
params = {
"action": "query",
"titles": title,
"prop": "revisions",
"rvprop": "ids|timestamp|user|size|comment",
"rvlimit": "max", # 500 per request, the most the API allows
"rvstart": until, # newest edit to include, so the result doesn't change tomorrow
"format": "json",
}
all_revisions = []
while True:
response = requests.get(url, params=params, headers=HEADERS)
response.raise_for_status() # stop on HTTP errors
data = response.json()
pages = data["query"]["pages"]
page_id = list(pages.keys())[0]
all_revisions.extend(pages[page_id].get("revisions", []))
if "continue" in data:
params.update(data["continue"]) # ask for the next batch
time.sleep(1) # one request at a time, a second apart
else:
break
return pd.DataFrame(all_revisions)
cu_revisions = get_revisions("University of Colorado Boulder")
print(f"Total revisions: {len(cu_revisions):,}")
# Newest first, so the last three rows are the article's first edits
print(cu_revisions[["timestamp", "user", "size"]].tail(3).to_string(index=False))
# Total revisions: 2,988
# timestamp user size
# 2003-12-23T07:08:15Z Dale Arnett 1232
# 2003-08-20T20:03:52Z Dino 1171
# 2003-08-05T16:42:10Z Dino 1037The rvstart parameter fixes the newest edit the function will return, so running it next week gives the same answer as today. Fixing a time window is a habit worth keeping for any source that keeps changing.
10.4.1 Understanding Pagination
The MediaWiki API limits the number of results returned per request. When more results are available, the response includes a "continue" key with parameters you must add to your next request. This loop — request, extract, check for continuation, update parameters, repeat — is the standard pagination pattern for most APIs. You will see it again in Chapter 11 and Chapter 12. The EIA’s API in Chapter 11 pages the other common way: it reports how many rows match, and you ask for the next page by the number of rows to skip, offset, keeping count yourself instead of sending back a token.
The critical mistake newcomers make is forgetting to check for continuation. Without the while True loop and "continue" check, you only get the first batch of results — potentially a small fraction of the total dataset.
Three smaller details in get_revisions() are worth adopting as habits. The response.raise_for_status() call makes HTTP failures loud: if the server returns an error status, your code stops with an informative exception instead of failing confusingly when you try to parse the JSON. The time.sleep(1) waits a second before each next request, which keeps a long loop well inside the rate limits in “Common Issues to Debug”, even on a network that many people share. And for bulk jobs, API etiquette suggests adding "maxlag": 5 to your parameters, which tells overloaded Wikimedia servers to refuse your request with a retryable error so that automated traffic yields to human readers.
10.4.2 Analyzing Revision History
import matplotlib.pyplot as plt
cu_revisions["timestamp"] = pd.to_datetime(cu_revisions["timestamp"])
# Count edits per month
monthly_edits = cu_revisions.set_index("timestamp").resample("ME").size()
fig, ax = plt.subplots(figsize=(8, 4))
monthly_edits.plot(ax=ax)
ax.set_title("Monthly edits to 'University of Colorado Boulder'")
ax.set_ylabel("Edits")
ax.set_xlabel("")
fig.tight_layout()
plt.show()The article’s busiest years were 2006 and 2007, about 30 edits a month, when much of it was being written (Figure 10.12). Since 2012 it has averaged fewer than ten edits a month: upkeep, such as new enrollment figures, more than new writing. You can also analyze who edits the article:
# Editors with the most revisions
top_editors = cu_revisions["user"].value_counts().head(10)
print(top_editors)
# What share of all edits came from those ten?
top10_share = top_editors.sum() / len(cu_revisions)
print(f"Top 10 editors account for {top10_share:.1%} of all edits")
# user
# Kerowyn 92
# MECU 82
# ElKevbo 78
# Contributor321 49
# Kvng 40
# Wordbuilder 37
# Fleminra 27
# Levineps 24
# Corkythehornetfan 23
# Rookkey 22
# Name: count, dtype: int64
# Top 10 editors account for 15.9% of all edits10.5 Getting Pageviews
The Wikimedia REST API, separate from the MediaWiki Action API, counts how many times an article was viewed. Its address is built from parts, like a file path: the project, the access method (desktop, mobile web, mobile app, or all), the agent (who is reading), the article, the granularity, and the dates. The function builds the address and returns a DataFrame:
def get_pageviews(title, start, end, agent="user", granularity="daily"):
article = title.replace(" ", "_")
url = (
"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article"
f"/en.wikipedia/all-access/{agent}/{article}/{granularity}/{start}/{end}"
)
response = requests.get(url, headers=HEADERS)
response.raise_for_status() # stop on HTTP errors
views = pd.DataFrame(response.json()["items"])
views["timestamp"] = pd.to_datetime(views["timestamp"], format="%Y%m%d%H")
return views[["timestamp", "views"]]With the function defined, retrieving and plotting a series takes a few lines:
cu_views = get_pageviews("University of Colorado Boulder", "20210101", "20260930")
print(f"{len(cu_views):,} days, {cu_views['views'].sum():,} views")
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(cu_views["timestamp"], cu_views["views"], linewidth=0.8)
ax.set_title("Daily pageviews: University of Colorado Boulder")
ax.set_ylabel("Views by human readers")
fig.tight_layout()
plt.show()
# 2,099 days, 1,367,292 viewsMost days the article has about 600 human readers (Figure 10.13); the median from 2021 to September 2026 is 590. The spikes are events, and the tallest are football. Deion Sanders was hired as head coach on December 3, 2022, and the article had 5,042 views on December 5. The opening weeks of his first season, in September 2023, brought its busiest days: 16,767 views on September 17, after a double-overtime win over Colorado State that ended late on the night of the 16th in Colorado. That last date is a reminder that the API’s days are UTC days, so an evening in Colorado counts toward the next day.
10.5.1 What a Pageview Counts
A pageview is not a person. Wikimedia’s definition counts a request for a page’s content that succeeded, and leaves out edits, previews, and most special pages; one reader who reloads an article three times is three pageviews. The definition has also changed over time, and a long series crosses those changes:
- The REST API’s counts begin in July 2015, under the current definition, drafted in 2014–15.
- Before that, the hourly pagecounts-raw files, from December 2007 to 2016, counted every request for a page, reads and edits alike, including those from crawlers. They are a fallback for older history, and they are not comparable with the API’s counts.
- The agent splits who is reading.
useris meant to be people;spideris self-identified crawlers, such as search engines; andautomatedis traffic that Wikimedia’s analysts judged to be bots that don’t say so. The rules for that judgment change, as “Social History and Public Interest” describes, and when they do, past counts can be reclassified.
You can ask the API for each agent separately:
agents = []
for agent in ["user", "spider", "automated"]:
monthly = get_pageviews("University of Colorado Boulder", "20240101", "20260930",
agent=agent, granularity="monthly")
monthly["agent"] = agent
agents.append(monthly)
by_agent = pd.concat(agents).pivot(index="timestamp", columns="agent", values="views")
print(by_agent.tail(3))
# Human views in the same nine months of 2024 and 2026
human = by_agent["user"]
print(f"January-September 2024: {human.loc['2024-01':'2024-09'].sum():,}")
print(f"January-September 2026: {human.loc['2026-01':'2026-09'].sum():,}")
fig, ax = plt.subplots(figsize=(8, 4))
by_agent.plot(ax=ax)
ax.set_title("Monthly pageviews by agent: University of Colorado Boulder")
ax.set_ylabel("Views")
ax.set_xlabel("")
fig.tight_layout()
plt.show()
# agent automated spider user
# timestamp
# 2026-07-01 2334 2099 10155
# 2026-08-01 1855 9362 11890
# 2026-09-01 2196 2924 14000
# January-September 2024: 173,832
# January-September 2026: 105,264For this one article, human views from January to September 2026 were 39% lower than in the same months of 2024 (Figure 10.14). Automated views, under a thousand a month through most of 2024, have been about two thousand a month or more since May 2025, when the Foundation updated its bot detection. One article can’t say how much of the drop is fewer readers and how much is traffic the Foundation now counts as bots; “Social History and Public Interest”, below, gives its account for Wikipedia as a whole.
10.6 Getting Links, Categories, Templates, and Languages
The tour’s other features all come from the same endpoint, action=query, with a different prop or list, and they all paginate the same way. Rather than write one function per feature, write one function that runs any query and follows its continuation, and collects the pages it returns:
def query_all(params):
url = "https://en.wikipedia.org/w/api.php"
params = {"action": "query", "format": "json", **params}
results = []
while True:
response = requests.get(url, params=params, headers=HEADERS)
response.raise_for_status() # stop on HTTP errors
data = response.json()
results.append(data["query"])
if "continue" in data:
params.update(data["continue"])
time.sleep(1) # a second between requests, as in get_revisions()
else:
break
return results
def page_list(title, prop, limit_param):
# One prop (links, categories, templates, extlinks, langlinks) for one page, as a list
items = []
for batch in query_all({"titles": title, "prop": prop, limit_param: "max"}):
for page in batch["pages"].values():
items.extend(page.get(prop, []))
return itemsEach feature on the tour is then one call:
title = "University of Colorado Boulder"
links = page_list(title, "links", "pllimit")
categories = page_list(title, "categories", "cllimit")
templates = page_list(title, "templates", "tllimit")
extlinks = page_list(title, "extlinks", "ellimit")
langlinks = page_list(title, "langlinks", "lllimit")
print(f"Wikilinks out: {len(links)}")
print(f"Categories: {len(categories)}")
print(f"Templates used: {len(templates)}")
print(f"External links: {len(extlinks)}")
print(f"Language editions: {len(langlinks)}")
print("First categories:", [c["title"] for c in categories[:3]])
# Wikilinks out: 650
# Categories: 40
# Templates used: 230
# External links: 217
# Language editions: 38
# First categories: ['Category:1876 establishments in Colorado Territory', 'Category:All Wikipedia articles written in American English', 'Category:All articles containing potentially dated statements']The API counts 40 categories, more than the box at the foot of the article shows (Figure 10.5). The first ones it returns are why: “All Wikipedia articles written in American English” and “All articles containing potentially dated statements” are hidden categories, which editors use to track maintenance work and which readers don’t see. To leave them out, add "clshow": "!hidden" to the query.
What links here is a list, not a prop: it asks about all of Wikipedia rather than one page. Its results come under backlinks. They include the redirects to the article, each marked with a redirect key, because blfilterredir is all unless you set it; "blfilterredir": "nonredirects" leaves them out:
backlinks = []
for batch in query_all({"list": "backlinks", "bltitle": title, "bllimit": "max",
"blnamespace": 0}): # namespace 0: articles only
backlinks.extend(batch["backlinks"])
print(f"Pages that link to {title}, redirects included: {len(backlinks)}")
# Pages that link to University of Colorado Boulder, redirects included: 329410.6.1 Interlanguage Links
Which editions have an article on a topic is itself a measurement. Each langlinks entry gives the edition’s language code and the article’s title there:
langs = pd.DataFrame(langlinks)
print(f"{len(langs)} other editions")
print(langs[["lang", "*"]].head(8).to_string(index=False))
# 38 other editions
# lang *
# ar جامعة كولورادو بولدر
# arz جامعة كولورادو بولدر
# az Boulder Kolorado Universiteti
# azb کولورادو بولدر بیلیمیوردو
# be Каларадскі ўніверсітэт у Боўлдэры
# bn কলোরাডো বোল্ডার বিশ্ববিদ্যালয়
# ca Universitat de Colorado a Boulder
# cs University of Colorado at BoulderThe number of language editions an article appears in is a measure of global interest as perceived by Wikipedia’s volunteer editors. Articles about Western political leaders, major cities, and scientific concepts tend to appear in 100 or more language editions. Articles about topics primarily relevant to the Global South — local politicians, regional cultural practices, indigenous languages — may exist in only a handful. This asymmetry reflects the demographic composition of Wikipedia’s editor community, which skews heavily toward the Global North and toward speakers of European languages. When you use Wikipedia data for cross-cultural analysis, interlanguage link counts are a useful but imperfect proxy for a topic’s global visibility.
10.7 Getting User Contributions
list=usercontribs returns an editor’s edits across all of Wikipedia, newest first. Here are the latest edits by Jimbo Wales, whose user page and contributions were on the tour:
contribs = []
for batch in query_all({"list": "usercontribs", "ucuser": "Jimbo Wales",
"uclimit": "max", "ucend": "2026-01-01T00:00:00Z",
"ucstart": "2026-09-30T23:59:59Z",
"ucprop": "title|timestamp|sizediff|comment"}):
contribs.extend(batch["usercontribs"])
contribs = pd.DataFrame(contribs)
print(f"Edits from January to September 2026: {len(contribs)}")
print(contribs[["timestamp", "title", "sizediff"]].head().to_string(index=False))
# Edits from January to September 2026: 351
# timestamp title sizediff
# 2026-09-30T12:19:46Z User talk:Jimbo Wales 377
# 2026-09-28T19:50:09Z User talk:Jimbo Wales 143
# 2026-09-27T09:43:50Z User talk:Jimbo Wales 496
# 2026-09-25T16:35:53Z User talk:Jimbo Wales 218
# 2026-09-25T16:35:13Z User talk:Jimbo Wales 550ucstart and ucend bound the window, newest first, as rvstart did for the revisions.
10.8 From Raw Requests to a Client: mwclient
This chapter has written its requests by hand, so that you can see every parameter and every continuation. In practice, most people who use the MediaWiki API from Python use a client library that does those parts for them. mwclient (documentation) is one of the simplest. It isn’t in webdata, so install it once, from the same conda-forge channel as the rest of the environment:
Then check that Python can import it, and which version you have:
conda-forge has version 0.10.1. The Python Package Index has a newer one, 0.11, which renames one argument used below: limit, the number of results to ask for in each request, becomes api_chunk_size. With 0.11, write api_chunk_size=500 where the code says limit=500.
site = mwclient.Site("en.wikipedia.org",
clients_useragent=CLIENT)
page = site.pages["University of Colorado Boulder"]
print(page.name, page.pageid, page.length)
print("Categories:", len(list(page.categories())))
print("Language editions:", len(list(page.langlinks())))
# Revisions, newest first, from the same moment get_revisions() started,
# 500 to a request (in mwclient 0.11, api_chunk_size=500)
revisions = list(page.revisions(start="2026-09-30T23:59:59Z", limit=500,
prop="ids|timestamp|user|size"))
print("Revisions:", len(revisions))
# University of Colorado Boulder 289672 95273
# Categories: 40
# Language editions: 38
# Revisions: 2988Each line replaces one of this chapter’s functions. page.categories() and page.langlinks() are page_list(); page.revisions() is get_revisions(), continuation included; and site.usercontributions("Jimbo Wales") is the usercontribs query. mwclient also waits and retries when the servers ask it to (maxlag), and it can sign in, for scripts that edit. Its user guide has more examples, and Pywikibot is the larger library that Wikipedia’s bot operators use.
One thing mwclient doesn’t do, in version 0.10.1 or 0.11, is wait out a 429. When Wikimedia’s rate limit answers with status 429, mwclient raises an HTTPError, and the loop over page.revisions() stops partway. Wait for the number of seconds in the response’s retry-after header, then run it again; “Common Issues to Debug”, below, has more on the limits.
Two things stay raw. mwclient talks to the Action API only, so pageviews still come from get_pageviews(). And a client is a convenience, not a substitute for the documentation: when you need a parameter the library doesn’t expose, you are back to the Action API’s documentation and a request you write yourself.
10.9 A Second Case Study: Boulder, Colorado
The same functions work on any article. Boulder, Colorado is the city around the university, and its article answers to different events:
boulder = "Boulder, Colorado"
boulder_revisions = get_revisions(boulder)
boulder_views = get_pageviews(boulder, "20210101", "20260930")
boulder_langs = page_list(boulder, "langlinks", "lllimit")
print(f"{'':32}{'revisions':>10}{'views':>12}{'editions':>10}")
for name, revs, views, langs_ in [(title, cu_revisions, cu_views, langlinks),
(boulder, boulder_revisions, boulder_views, boulder_langs)]:
print(f"{name:32}{len(revs):>10,}{views['views'].sum():>12,}{len(langs_):>10}")
# revisions views editions
# University of Colorado Boulder 2,988 1,367,292 38
# Boulder, Colorado 4,304 1,818,309 7810.9.1 Combining Endpoints
The real analytical power of the API emerges when you combine endpoints. A natural question is whether editing and reading move together: do articles get edited more when more people are reading them?
boulder_revisions["timestamp"] = pd.to_datetime(boulder_revisions["timestamp"])
fig, axes = plt.subplots(2, 1, figsize=(8, 5), sharex=True)
for name, revs, views in [(title, cu_revisions, cu_views),
(boulder, boulder_revisions, boulder_views)]:
# Revision timestamps are in UTC; drop the time zone to match the pageviews.
# Revisions arrive newest first, so count by month before keeping 2021 on
edits = (revs.set_index(revs["timestamp"].dt.tz_localize(None))
.resample("ME").size().loc["2021":])
monthly_views = views.set_index("timestamp")["views"].resample("ME").sum()
axes[0].plot(monthly_views.index, monthly_views.values, label=name)
axes[1].plot(edits.index, edits.values, label=name)
print(f"{name}: monthly views and edits correlate at {monthly_views.corr(edits):.2f}")
axes[0].set_ylabel("Monthly views")
axes[1].set_ylabel("Monthly edits")
axes[0].legend()
fig.tight_layout()
plt.show()
# University of Colorado Boulder: monthly views and edits correlate at 0.21
# Boulder, Colorado: monthly views and edits correlate at 0.38The two articles answer to different events (Figure 10.15). The city’s busiest month, March 2021, had 120,790 views, five times its usual month: on March 22, a gunman killed ten people at a King Soopers grocery store in Boulder, and the article had 63,327 views the next day. Its edits rose too, to 35 that month. The university’s busiest month, September 2023, had 97,904 views, from football, but only seven edits. December 2022, when Sanders was hired, brought both: 40,174 views and 26 edits, the article’s most edited month since 2021. The city’s article also marks the Marshall Fire, which burned more than a thousand homes in Boulder County on December 30, 2021, and an attack on a demonstration in downtown Boulder on June 1, 2025.
Reading and editing move together only loosely: over the 69 months, monthly views and edits correlate at 0.21 for the university and 0.38 for the city. When news breaks, a burst of readers brings editors with it (Keegan et al. 2013). But many edits keep their own schedule, such as cleanups, reorganizations, and arguments no reader set off. The city’s most edited month, September 2021, with 45 edits, had an ordinary number of readers.
10.10 Recommended Exercises
This guided exercise is the chapter’s take-home assignment. Work through it in the companion notebook, filling in each empty code cell, and submit the completed notebook. The steps build on one another, so do them in order — everything you need appears in this chapter or an earlier one.
You will build a complete profile of one Wikipedia article: who reads it, who writes it, and what it connects to.
Setup. Run this cell first, whether or not you ran the chapter’s cells above: it defines HEADERS and the four functions the steps call, get_pageviews(), get_revisions(), query_all(), and page_list(), as this chapter wrote them. It sends no request.
# Setup: the libraries, your User-Agent, and the chapter's four functions; put your own address in CLIENT
import time
import matplotlib.pyplot as plt
import pandas as pd
import requests
CLIENT = "WebDataScience/1.0 (your-email@colorado.edu)"
HEADERS = {"User-Agent": f"{CLIENT} python-requests/{requests.__version__}"}
def get_pageviews(title, start, end, agent="user", granularity="daily"):
article = title.replace(" ", "_")
url = (
"https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article"
f"/en.wikipedia/all-access/{agent}/{article}/{granularity}/{start}/{end}"
)
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
views = pd.DataFrame(response.json()["items"])
views["timestamp"] = pd.to_datetime(views["timestamp"], format="%Y%m%d%H")
return views[["timestamp", "views"]]
def get_revisions(title, until="2026-09-30T23:59:59Z"):
url = "https://en.wikipedia.org/w/api.php"
params = {
"action": "query",
"titles": title,
"prop": "revisions",
"rvprop": "ids|timestamp|user|size|comment",
"rvlimit": "max",
"rvstart": until,
"format": "json",
}
all_revisions = []
while True:
response = requests.get(url, params=params, headers=HEADERS)
response.raise_for_status()
data = response.json()
pages = data["query"]["pages"]
page_id = list(pages.keys())[0]
all_revisions.extend(pages[page_id].get("revisions", []))
if "continue" in data:
params.update(data["continue"])
time.sleep(1)
else:
break
return pd.DataFrame(all_revisions)
def query_all(params):
url = "https://en.wikipedia.org/w/api.php"
params = {"action": "query", "format": "json", **params}
results = []
while True:
response = requests.get(url, params=params, headers=HEADERS)
response.raise_for_status()
data = response.json()
results.append(data["query"])
if "continue" in data:
params.update(data["continue"])
time.sleep(1)
else:
break
return results
def page_list(title, prop, limit_param):
items = []
for batch in query_all({"titles": title, "prop": prop, limit_param: "max"}):
for page in batch["pages"].values():
items.extend(page.get(prop, []))
return itemsStep 1 — Choose an article and get its pageviews. Pick an article about a place, institution, or event you know, with at least one newsworthy moment since 2021. With your own address in the setup cell’s CLIENT, use get_pageviews() to retrieve daily views by human readers for a fixed period that ends before today. Build the DataFrame and plot the series.
Step 2 — Find the spike. Identify the highest-traffic day with idxmax(), which gives the row label of the largest value, and print the date and view count. Note in a comment what real-world event you think explains it, and check the article’s revision history around that date for edits that mention it; if none does, write that down, since an event can bring readers without bringing editors. If the biggest day isn’t the news you chose the article for, say so, and check that the article already had its current title then (“Renamed articles” in “Common Issues to Debug”).
Step 3 — Get the revision history. Use the chapter’s get_revisions(), following continuation tokens so you page through the full history up to a fixed date. Print the total count and the date range.
Step 4 — Profile the editors. How many unique editors does the article have? Use value_counts() on the user column to see edits per editor, and print the top ten’s counts without their usernames: .values gives the counts alone, ranked 1 to 10. Look at the names yourself if you need to, but don’t paste them into the notebook you submit. The usernames are public on the article’s history, but the people behind them are private individuals. Some of the top ten may be bots, whose usernames usually include “bot”: count them. Is the editing concentrated in a few hands or spread out?
Step 5 — Align edits with attention. Resample the revisions by month, and plot monthly edits alongside the monthly pageview totals from Step 1. The revisions’ timestamps carry a time zone and the pageviews’ don’t, so drop it with tz_localize(None) before comparing them, as “Combining Endpoints” does. Do the two series move together around your spike?
Step 6 — Map the neighborhood. Use page_list() for the article’s wikilinks, categories, and language editions, and query_all() for what links here. Print each count and five examples of each. A language edition’s entry holds lang and * (its title there), not title, as “Interlanguage Links” shows.
Step 7 — Interpret. In four to six sentences: What does the alignment (or misalignment) of edits and views around your spike suggest about how Wikipedia responds to events? If you quote a correlation, compute it again without your busiest month and give both: for this chapter’s university article, 0.21 becomes 0.41 without September 2023. Is your article maintained by a dedicated few or a broad crowd, and why might that matter for how much you trust it? What kind of article do its links and categories suggest it is?
10.11 Additional Exercises
These are open-ended extensions — no scaffold, no fixed path. Use them for further practice or deeper exploration.
Comparative revision analysis. Retrieve the revision histories for two related Wikipedia articles (e.g., “Boulder, Colorado” and “Fort Collins, Colorado”). Compare the number of unique editors, the distribution of edits per editor (is editing concentrated or distributed?), and the pattern of monthly editing activity. Are there periods where editing spikes simultaneously on both articles?
Event detection with pageviews. Use the pageviews API to retrieve daily data for five related articles over a full year. Identify spikes in each article and map them to real-world events. Did all articles spike together (suggesting a common cause), or were there article-specific events? Create a multi-line plot with labeled annotations for the key events.
Link network. Retrieve the outgoing wikilinks from three articles on related topics. How much do their link sets overlap? What articles appear in all three link sets? This overlap analysis is a simple form of the network analysis described in Appendix C.
Raw API practice. Using only the MediaWiki API documentation at https://www.mediawiki.org/wiki/API:Main_page, construct a working request for an endpoint not covered in this chapter. Good candidates include
list=search(full-text search),list=recentchanges(the most recent edits across all of Wikipedia),prop=redirects(which alternative titles redirect to an article), orprop=pageviews(the Action API’s own view counts for the last 60 days — compare them against the REST endpoint you used earlier). Document your process: what parameters did you choose and why? Then make the same request with mwclient, if it has a method for it.Editor network. For a single article, identify the top 20 editors by revision count. Then use
list=usercontribsto find what other articles these editors work on. Do they share other editing interests, or is this article their only point of overlap?Graduate extension (INFO 5617). Read Mesgari et al. (2015), a systematic review of the first decade of scholarly research on Wikipedia. Choose one research stream from the review — collaboration inequality, for instance — and reproduce a miniature version of its core measurement using this chapter’s functions, such as computing a Gini coefficient of edits per editor across three articles of your choosing. Then write a short reflection on how your measurement choices (which articles, what time window, whether anonymous editors count, which pageview agent) would change your conclusions, and how the original studies in that stream handled the same choices.
10.13 Common Issues to Debug
- Pagination: The single most common mistake. Always check for
"continue"in the response. Without it, you get only the first batch (often 500 or fewer results out of thousands). - Nested JSON navigation: The MediaWiki API nests data several levels deep. Print
data.keys(), thendata["query"].keys(), thendata["query"]["pages"].keys()to navigate step by step. - Titles: The Action API accepts titles with spaces; the REST pageviews API wants underscores, which is why
get_pageviews()swaps them. For titles with other special characters (slashes, question marks), encode them withurllib.parse.quote(title, safe=""). - Rate limiting (status 429): Wikimedia counts requests per minute across the Action API and the REST APIs, pageviews included: 200 a minute for a client whose User-Agent follows the policy, and 10 a minute for one that doesn’t, shared with everyone else on its network address (Wikimedia APIs/Rate limits; the limits are new in 2026 and may change). Past the limit, the answer is status 429, with a
retry-afterheader that says how many seconds to wait; wait that long before trying again. The practical rule: serial requests, followcontinuetokens,maxlagfor bulk work, and always an informative User-Agent. - Renamed articles: Pageviews belong to a title, and edits to a page. When an article is moved to a new title, its revision history moves with it, but the pageviews counted before the move stay with the old title, which becomes a redirect. If your article is recent or was renamed, find when it got its current title (a “moved page” edit summary in its history says so) and check that your window and your peak come after that, or add the old title’s views.
- Missing pages: If you request an article that does not exist, the page ID will be negative (e.g.,
-1). Always check for this before trying to access revision data.
10.14 Key Takeaways
APIs provide structured, documented, intentional access to web data. Every feature Wikipedia shows a reader — talk pages, revision histories, pageviews, links, categories, templates, languages, user contributions — has an endpoint, so what you can see you can count. Learning one API well gives you a transferable skill: read the documentation, construct parameterized requests, handle pagination with continuation tokens, and parse nested JSON one level at a time. A client library such as mwclient does the repetitive parts once you know what they are. Know what your numbers count: a pageview’s definition has changed, and so has the traffic behind it. Wikipedia remains a model of open, mission-driven data access, and one now under pressure from the automated traffic that open access invites.
10.15 Further Reading
- MediaWiki API documentation: https://www.mediawiki.org/wiki/API:Main_page
- Wikimedia REST API (pageviews): https://wikimedia.org/api/rest_v1/
- Research:Page view, Wikimedia’s definition of a pageview: https://meta.wikimedia.org/wiki/Research:Page_view
- The MediaWiki Action API, every module and parameter: https://www.mediawiki.org/wiki/API:Action_API
- mwclient documentation: https://mwclient.readthedocs.io/
- Keegan et al. (2013) and Keegan (2020) — how Wikipedia covers breaking news
- Keegan and Fiesler (2017) — how Wikipedia’s rules are written and rewritten
- Ford (2022) — Wikipedia’s role in the survival of facts in the digital age
- Mesgari et al. (2015) — systematic review of scholarly research on Wikipedia content
- Salganik (2018) — Chapter 2: Observing Behavior, on using digital trace data for research















10.12 Social History and Public Interest
Wikipedia is the counter-example to the enclosure story of Chapter 3. While commercial platforms restricted, repriced, or shut down their APIs, Wikipedia kept three things open: its API; its content, licensed for free reuse under CC BY-SA 4.0; and complete database dumps of every public wiki for anyone to download. That combination is why this book uses Wikipedia to teach API fundamentals. It follows from the mission of the Wikimedia Foundation, which hosts the site: to “collect and develop educational content under a free license or in the public domain, and to disseminate it effectively and globally” (Wikimedia Foundation). Since 2001 Wikipedia has grown into the world’s largest reference website, written by volunteers in more than 300 languages; in October 2026 the English edition alone counted about 269,000 contributors who had edited in the past month (Wikipedia:About, List of Wikipedias). Its open records have made it one of the most studied sites on the web: of how strangers coordinate when news breaks (Keegan et al. 2013; Keegan 2020), of how a community writes and rewrites its own rules (Keegan and Fiesler 2017), and of how facts written there travel to search engines and other platforms (Ford 2022).
But openness does not mean representativeness. Research has documented a demographic skew in who edits Wikipedia: editors are disproportionately male, from the Global North, and technically fluent. In the best-known survey of editors, from 2008, about one in six was a woman, even after correcting for who chose to answer (Hill and Shaw 2013). This translates into content gaps: articles about women, people of color, and the Global South are systematically shorter, less detailed, and less well-referenced than articles about men and Western topics (Mesgari et al. 2015), and biographies of women are written and linked differently from biographies of men (Wagner et al. 2016). WikiProject Women in Red has worked on the gender gap since July 2015, when it was founded after editors found that only 15.5% of English Wikipedia’s biographies were about women. It organizes edit-a-thons and keeps “redlists” of notable women who have no article; by its count, the share of biographies about women passed 20% in December 2024. Data retrieved from the API reflects these structural patterns: any Wikipedia-based analysis inherits the biases of its volunteer editor community.
Since 2024, a newer pressure has come from the same openness that makes Wikipedia useful. Its free content is training data and source material for generative AI, and three changes followed.
Crawlers. In April 2025, the Foundation reported that the bandwidth used to download images and other media had grown 50% since January 2024, and that the growth came from crawlers rather than human readers. Bots made up about 35% of pageviews but at least 65% of the traffic that was most expensive to serve. The Foundation’s summary: “our content is free, our infrastructure is not” (Mueller, Danis, and Lavagetto, 2025). A year later it reported that it was blocking or throttling about 30% of automated requests from crawlers that ignore its policies, and that it had begun rolling out the API rate limits in “Common Issues to Debug”, below, which reward a client that identifies itself (2026).
Readers. In 2025 the Foundation found that much of an unusual rise in apparent human traffic was bots built to evade detection. It updated its bot detection, reclassified its traffic data for March to August 2025, and reported that human pageviews over those months were roughly 8% lower than in the same months of 2024. It attributed the decline to “the impact of generative AI and social media on how people seek information”: answers that draw on Wikipedia without a visit (Miller, 2025). That reclassification is why “What a Pageview Counts”, above, warns that past counts can change. Fewer visits also means fewer readers who become editors or donors.
Writing. Editors have had to decide what to do with text that language models write. WikiProject AI Cleanup, formed in December 2023, works “to identify text written by AI, and scrutinize such text to make sure it follows Wikipedia’s policies” (WikiProject AI Cleanup). A speedy-deletion criterion, G15, lets administrators delete pages that could only plausibly have been generated by a language model without review. In March 2026, after a community request for comment, a new guideline, Writing articles with large language models, prohibited using them to generate or rewrite article content, with exceptions for basic copyediting of one’s own writing and for translation. The Foundation’s own AI strategy, published in April 2025, put its investment in tools for the volunteers, such as help for moderators and translation, rather than in machine-written articles (Albon and Zia, 2025).
For a data scientist, these changes are both a subject and a responsibility. The pageview series you retrieve now carries a definition that changed in 2025. The articles you read may have been written, in part, under new rules about machines. And your own code is part of the automated traffic the Foundation is managing: identify yourself, make requests one at a time, fix your time windows so you don’t fetch the same data twice, and use the database dumps for anything large.