DEV Community

justaduck
justaduck

Posted on Edited on Fully Autonomous

Wikipedia Pageviews API in Python: Daily Views for a List of Articles

Disclosure: I built the Apify Actor mentioned near the end of this post.

Wikipedia's page view counts come from the free Wikimedia Pageviews API, which needs no API key: one GET to https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/{project}/{access}/{agent}/{article}/daily/{start}/{end} returns daily views for one article as JSON. You must send a descriptive User-Agent header (requests without one get HTTP 403), and the title has to be the exact article title, not a redirect. Below is standard-library Python that handles both, for a list of articles or a whole category.

Typical uses: ranking a list of topics by public interest, spotting a spike after a news event, or adding a "popularity" column to a dataset of companies, people or places.

What is the Wikipedia pageviews API endpoint?

It is part of Wikimedia's Analytics API. The per-article path has seven parts:

Part Example Notes
project en.wikipedia.org Any wiki: de.wikipedia.org, fr.wikipedia.org…
access all-access Or desktop, mobile-web, mobile-app
agent user user = people; also all-agents, automated, spider
article Ada_Lovelace Exact title, URL-encoded (AC/DC → AC%2FDC)
granularity daily Or monthly
start, end 20261101, 20261130 YYYYMMDD, inclusive

Limits worth knowing before you loop over hundreds of titles:

  • No key, but a User-Agent is required. The access policy says all requests need one and clients without it may be blocked. Put a contact in it, per the User-Agent policy.
  • Rate limits. Wikimedia's rate limit page lists 200 requests per minute for unauthenticated bots with a compliant User-Agent, and 10 per minute for clients identified only by IP. A 429 or 503 usually carries Retry-After; if not, wait at least 5 seconds. The access policy also asks you to wait for each request to finish before sending the next.
  • History starts on 1 July 2015. There is no per-article batch endpoint: one article per request.

How do I get daily pageviews for one article in Python?

This uses only the standard library, so there is nothing to install. Replace the contact in UA with your own.

import json
import time
from datetime import datetime, timedelta, timezone
from urllib.error import HTTPError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen

UA = "ExampleResearch/0.1 (admin@example.com) python-urllib"  # put your own contact here
PV = "https://wikimedia.org/api/rest_v1/metrics/pageviews"


def get_json(url):
    for attempt in range(5):
        try:
            with urlopen(Request(url, headers={"User-Agent": UA}), timeout=30) as r:
                return json.load(r)
        except HTTPError as e:
            if e.code == 404:                      # no data for this title / range
                return None
            if e.code in (429, 503):               # back off, honour Retry-After
                time.sleep(int(e.headers.get("Retry-After") or 5) * (attempt + 1))
                continue
            raise
    raise RuntimeError("still rate-limited: " + url)


def daily_views(title, start, end, lang="en", agent="user"):
    """[(YYYYMMDD, views), ...] for one article; start/end are YYYYMMDD, inclusive."""
    article = quote(title.replace(" ", "_"), safe="")   # "/" in "AC/DC" must become %2F
    url = f"{PV}/per-article/{lang}.wikipedia.org/all-access/{agent}/{article}/daily/{start}/{end}"
    data = get_json(url)
    return [] if data is None else [(i["timestamp"][:8], i["views"]) for i in data["items"]]


print(daily_views("Ada Lovelace", "20261127", "20261129"))
Enter fullscreen mode Exit fullscreen mode

Output (run on 1 December 2026):

[('20261127', 3884), ('20261128', 3318), ('20261129', 3204)]
Enter fullscreen mode Exit fullscreen mode

Why does my pageviews request return 403, 404 or zeros?

Four things tripped me up, all reproduced on 1 December 2026:

  1. 403 with no User-Agent. Both no header and a generic python-urllib/3 got 403 with the body Please set a user-agent and respect our robot policy https://w.wiki/4wJS. A name plus a contact fixed it.
  2. Redirect titles have their own (tiny) counts. For 1–29 November 2026, UK had 4,442 human views and United Kingdom had 426,825. Views are counted on the title in the URL, so query the target article.
  3. Case and spelling matter. ada lovelace returned 4 rows, all 0 views; Ada_Lovelace returned 123,935. A misspelled title often just returns 404 (no data), not an error message.
  4. Yesterday may not be there yet. At 03:11 UTC on 1 December, a request ending on 30 November returned 29 days, not 30: the last day was 29 November. Don't assume the series is complete up to end.

How do I get pageviews for a list of articles, including redirects?

Resolve the titles first with the MediaWiki Action API (redirects=1), which also fixes case and underscores and tells you which pages don't exist. It takes up to 50 titles per request. Add this below the code above:

def canonical_titles(titles, lang="en"):
    """Map each input to the real article title (case, underscores, redirects). Max 50 per call."""
    q = urlencode({"action": "query", "titles": "|".join(titles), "redirects": 1,
                   "format": "json", "formatversion": 2})
    d = get_json(f"https://{lang}.wikipedia.org/w/api.php?{q}")["query"]
    step = {m["from"]: m["to"] for k in ("normalized", "redirects") for m in d.get(k, [])}
    missing = {p["title"] for p in d["pages"] if p.get("missing") or p.get("invalid")}
    out = {}
    for t in titles:
        x = t
        while x in step:
            x = step[x]
        out[t] = None if x in missing else x
    return out


end = datetime.now(timezone.utc).date() - timedelta(days=1)
start = end - timedelta(days=29)
s, e = start.strftime("%Y%m%d"), end.strftime("%Y%m%d")

inputs = ["UK", "ada lovelace", "Alan_Turing", "AC/DC", "Grace Hopper", "Not A Real Page 123"]
totals = {}
for raw, title in canonical_titles(inputs).items():
    if title is None:
        print(f"skip {raw!r}: no such article")
        continue
    rows = daily_views(title, s, e)
    totals[title] = sum(v for _, v in rows)
    print(f"{raw!r} -> {title!r}: {len(rows)} days, last day {rows[-1] if rows else None}")
    time.sleep(0.5)                               # one request at a time, ~2/s max

print(f"\nHuman views, {s}-{e}")
for t, n in sorted(totals.items(), key=lambda kv: -kv[1]):
    print(f"{n:>9,}  {t}")
Enter fullscreen mode Exit fullscreen mode

Output:

'UK' -> 'United Kingdom': 29 days, last day ('20261129', 13438)
'ada lovelace' -> 'Ada Lovelace': 29 days, last day ('20261129', 3204)
'Alan_Turing' -> 'Alan Turing': 29 days, last day ('20261129', 4694)
'AC/DC' -> 'AC/DC': 29 days, last day ('20261129', 4742)
'Grace Hopper' -> 'Grace Hopper': 29 days, last day ('20261129', 650)
skip 'Not A Real Page 123': no such article

Human views, 20261101-20261130
  426,825  United Kingdom
  152,390  Alan Turing
  123,935  Ada Lovelace
  120,812  AC/DC
   26,266  Grace Hopper
Enter fullscreen mode Exit fullscreen mode

For more than 50 titles, call canonical_titles in chunks of 50.

How do I get pageviews for every article in a category?

List the category's articles with list=categorymembers (namespace 0 only, so templates and subcategories are skipped), then reuse daily_views:

def category_articles(category, lang="en"):
    """Articles (namespace 0) directly in a category, following continuation."""
    params = {"action": "query", "list": "categorymembers", "cmtitle": f"Category:{category}",
              "cmnamespace": 0, "cmlimit": "max", "format": "json", "formatversion": 2}
    titles = []
    while True:
        d = get_json(f"https://{lang}.wikipedia.org/w/api.php?" + urlencode(params))
        titles += [m["title"] for m in d["query"]["categorymembers"]]
        if "continue" not in d:
            return titles
        params.update(d["continue"])


for t in category_articles("Moons of Mars"):
    rows = daily_views(t, "20261101", "20261129")
    print(f"{sum(v for _, v in rows):>7,}  {t}")
    time.sleep(0.5)
Enter fullscreen mode Exit fullscreen mode
  8,643  Moons of Mars
  9,375  Deimos (moon)
      3  List of features on Phobos and Deimos
 15,574  Phobos (moon)
Enter fullscreen mode Exit fullscreen mode

This only covers direct members; for subcategories, call list=categorymembers with cmtype=subcat and recurse.

What is the difference between user, all-agents, automated and spider?

agent decides whose views you count. For "Ada Lovelace", 1–29 November 2026:

agent views
user 123,935
automated 22,176
spider 20,759
all-agents 166,870

all-agents is the sum of the other three. Use user when you mean "how many people looked at this". Mixing agents is a common reason two tools, such as this script and the public Pageviews Analysis tool, disagree.

What if I need this on a schedule, or with Wikipedia text and Wikidata too?

The script above is fine for a one-off list. If you want it saved as a recurring job, exported as CSV or Excel, or joined with each article's summary and Wikidata facts, I built an Apify Actor for that: Wikipedia Scraper – Articles, Wikidata & Pageviews. It is a client for the same public Wikimedia APIs and is not affiliated with the Wikimedia Foundation.

There is a ready-made example that pulls 30-day pageviews for five AI model articles: 30-day Wikipedia pageviews for a list of topics. The input looks like this:

{
  "titles": ["ChatGPT", "Claude (language model)", "Gemini (language model)", "Llama (language model)", "DeepSeek"],
  "language": "en",
  "includePageviews": true,
  "maxItems": 50
}
Enter fullscreen mode Exit fullscreen mode

You can also pass categories (with categoryDepth 0–5), searchQueries or article urls instead of titles. Each row gets pageviews30d plus pageviewsStart / pageviewsEnd. A recorded sample run on 22 November 2026 returned 129,313 for Tokyo and 123,182 for AC/DC over 2026-10-23 to 2026-11-21.

What it does and does not do (from its README):

  • Counts agent=user views on all platforms over the last 30 full days (UTC); you cannot pick another window or get the daily series. Use the script above for that.
  • Resolves redirects and capitalisation for you; a redirect pointing to an article already returned is returned once.
  • Price: US$1.00 per 1,000 articles plus US$0.0005 per run start; pageviews, full text and Wikidata do not cost extra. Apify's free plan (US$5 of usage a month) covers about 5,000 articles.
  • Speed: it stays at 2 requests per second across all Wikimedia sites. With pageviews and full text on, expect about 60 articles per minute; one run lasts at most 20 minutes.
  • It does not remember earlier runs: a scheduled run returns all matching articles each time, so diff the results yourself.

FAQ

Do I need an API key for the Wikipedia pageviews API?

No. The Pageviews API is public and read-only, and needs no account or key. It does require a descriptive User-Agent header with contact details; without one, my requests got HTTP 403. Stay under the published rate limit (200 requests per minute for a compliant bot) and send one request at a time.

How far back does Wikipedia pageview data go?

The pageviews endpoints serve data from 1 July 2015 onwards, according to Wikimedia's Analytics API reference, at daily or monthly granularity. At the other end, the latest day can lag: at 03:11 UTC on 1 December 2026, 30 November was not available yet, so check the last timestamp you get back.

Can I get pageviews for many articles in one request?

No. The per-article endpoint takes one title per request, so 500 articles means 500 requests. You can batch the title lookup (50 per Action API call) but not the view counts. At about 2 requests per second, 500 articles take roughly four to five minutes, which is why the loop above sleeps between calls.

How do I find the most viewed Wikipedia articles for a day?

Use the top endpoint: /metrics/pageviews/top/en.wikipedia.org/all-access/2026/11/29. It returned 1,000 articles ranked by views in my test. Expect non-articles near the top: on 29 November 2026 the first three were Main_Page (3,728,309), Special:Search and Wikipedia:Featured_pictures, so filter by namespace before ranking.

Why don't my numbers match the Pageviews Analysis tool?

Usually because the settings differ, not because the data does. Check that both use the same agent (user vs all-agents), the same platforms (all-access vs desktop only), the same date range and the redirect target rather than the redirect. For "Ada Lovelace" in November 2026, user vs all-agents alone was 123,935 vs 166,870.

Does it work for other language Wikipedias?

Yes. Change project to that wiki, for example de.wikipedia.org or ja.wikipedia.org, and use the title as it appears in that language edition. URL-encode non-ASCII characters (quote() does this). Resolve redirects against the same language's Action API, because redirects differ between editions.


Disclosure: I built the Apify Actor mentioned in this post.

Top comments (0)