Skip to main content

10  Introduction to APIs: Wikipedia

TipLearning Objectives
  • 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
TipCompanion Notebook

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.

Screenshot of the English Wikipedia article University of Colorado Boulder. Marker 1: the Article tab. Marker 2: the Talk tab. Marker 3: View history. Marker 4: the languages button at the top right. Marker 5: a blue wikilink in the article's first paragraph. Marker 6: the infobox at the right, with the university's seal and facts such as its founding date.
Figure 10.1: The University of Colorado Boulder article, October 2026, signed out. Tabs lead to the Article ① and its Talk page ②, and View history ③ to every past version. The languages button ④ lists other editions. A wikilink in the lead ⑤ points to another article, and the infobox ⑥ comes from a template.

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.

Screenshot of the References section of the article. Marker 1: the heading References. Marker 2: a bracket beside the first five numbered citations, each giving a source's title, publisher, and date, several with links to archived copies.
Figure 10.4: The article’s references, October 2026: the References heading ① and its first citations ②.

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.

Screenshot of the box at the foot of the article headed Categories. Marker 1: the first category link in a list of categories the article belongs to.
Figure 10.5: The article’s categories, October 2026 ①: each is a link to a page that lists its members.

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:

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}}}}

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.

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 bytes

This nested navigation pattern — data["query"]["pages"][page_id] — is consistent across the MediaWiki API. Once you internalize it, every endpoint feels familiar.

TipMissing Manual Reference

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  1037

The 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 edits

10.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 views

Most 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. user is meant to be people; spider is self-identified crawlers, such as search engines; and automated is 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,264

For 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.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       550

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

%conda install -y -c conda-forge mwclient

Then check that Python can import it, and which version you have:

import mwclient
print(mwclient.__version__)
# 0.10.1

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

Each 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        78

10.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.38

The 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.11 Additional Exercises

These are open-ended extensions — no scaffold, no fixed path. Use them for further practice or deeper exploration.

  1. 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?

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

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

  4. 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), or prop=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.

  5. Editor network. For a single article, identify the top 20 editors by revision count. Then use list=usercontribs to find what other articles these editors work on. Do they share other editing interests, or is this article their only point of overlap?

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

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(), then data["query"].keys(), then data["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 with urllib.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-after header that says how many seconds to wait; wait that long before trying again. The practical rule: serial requests, follow continue tokens, maxlag for 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

Ford, Heather. 2022. Writing the Revolution: Wikipedia and the Survival of Facts in the Digital Age. MIT Press.
Hill, Benjamin Mako, and Aaron Shaw. 2013. “The Wikipedia Gender Gap Revisited: Characterizing Survey Response Bias with Propensity Score Estimation.” PLOS ONE 8 (6): e65782. https://doi.org/10.1371/journal.pone.0065782.
Keegan, Brian C. 2020. “An Encyclopedia with Breaking News.” In Wikipedia @ 20: Stories of an Incomplete Revolution, edited by Joseph Reagle and Jackie Koerner. MIT Press. https://doi.org/10.7551/mitpress/12366.003.0007.
Keegan, Brian C., and Casey Fiesler. 2017. “The Evolution and Consequences of Peer Producing Wikipedia’s Rules.” Proceedings of the International AAAI Conference on Web and Social Media 11. https://doi.org/10.1609/icwsm.v11i1.14899.
Keegan, Brian, Darren Gergle, and Noshir Contractor. 2013. “Hot Off the Wiki: Structures and Dynamics of Wikipedia’s Coverage of Breaking News Events.” American Behavioral Scientist 57 (5): 595–622. https://doi.org/10.1177/0002764212469367.
Mesgari, Mostafa, Chitu Okoli, Mohamad Mehdi, Finn Årup Nielsen, and Arto Lanamäki. 2015. “‘The Sum of All Human Knowledge’: A Systematic Review of Scholarly Research on the Content of Wikipedia.” Journal of the Association for Information Science and Technology 66 (2): 219–45. https://doi.org/10.1002/asi.23172.
Salganik, Matthew J. 2018. Bit by Bit: Social Research in the Digital Age. Princeton University Press. https://www.bitbybitbook.com/.
Wagner, Claudia, Eduardo Graells-Garrido, David Garcia, and Filippo Menczer. 2016. “Women Through the Glass Ceiling: Gender Asymmetries in Wikipedia.” EPJ Data Science 5 (1). https://doi.org/10.1140/epjds/s13688-016-0066-4.