Disclosure: I built the Apify Actor mentioned near the end of this post.
The Wikipedia search API is the MediaWiki Action API at https://en.wikipedia.org/w/api.php with action=query&list=search&srsearch=<your words>. It is free, needs no key, and returns titles, page IDs, word counts and HTML snippets, up to 500 per request and 10,000 per query. If you also want each result's URL, short description, intro text and image in the same call, use generator=search instead. If you only want title suggestions while someone types, use action=opensearch.
Below is a standard-library Python script that does all three, plus the details that tripped me up: HTML in snippets, results that come back out of order, the 20-intro cap, and paging past 500.
Which Wikipedia search endpoint should I use?
| You want | Endpoint | What it matches | Per request |
|---|---|---|---|
| Full-text search results with snippets |
list=search (docs) |
words anywhere in the article | up to 500 |
| Results plus URL, description, intro, thumbnail |
generator=search + prop=...
|
same search, same ranking | intros for up to 20 |
| Autocomplete / "search by title" suggestions |
action=opensearch (docs) |
the start of the title |
limit up to 500 |
All three run on the same search engine (CirrusSearch), so the search syntax in Help:CirrusSearch works in srsearch and gsrsearch, including intitle: and incategory:.
One thing every Wikimedia API needs: a descriptive User-Agent header with a way to contact you. Without one, requests can be blocked.
How do I search Wikipedia from Python?
No packages to install; tested with Python 3.9.
import html
import json
import re
import time
import urllib.parse
import urllib.request
API = "https://en.wikipedia.org/w/api.php"
# Wikimedia blocks requests without a descriptive User-Agent. Put your own contact in it.
UA = "devto-example-script/1.0 (contact: you@example.com)"
def api(params):
params = {**params, "format": "json", "formatversion": "2"}
url = API + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"User-Agent": UA})
with urllib.request.urlopen(req, timeout=20) as resp:
data = json.load(resp)
time.sleep(1) # one request at a time, about one per second
if "error" in data:
raise RuntimeError(data["error"]["code"] + ": " + data["error"]["info"])
return data
def clean(snippet):
"""Search snippets are HTML: <span class="searchmatch"> plus entities."""
return html.unescape(re.sub(r"<[^>]+>", "", snippet))
def article_url(title):
return "https://en.wikipedia.org/wiki/" + urllib.parse.quote(title.replace(" ", "_"))
def search(query, limit=10, offset=0):
"""Full-text search: list=search. Returns (total_hits, rows)."""
data = api({
"action": "query", "list": "search", "srsearch": query,
"srlimit": limit, "sroffset": offset,
"srprop": "snippet|wordcount|timestamp",
})
rows = []
for i, hit in enumerate(data["query"]["search"], start=offset + 1):
rows.append({
"rank": i,
"title": hit["title"],
"url": article_url(hit["title"]),
"words": hit["wordcount"],
"snippet": clean(hit["snippet"]),
})
return data["query"]["searchinfo"]["totalhits"], rows
def search_with_details(query, limit=10):
"""generator=search: search + URL + description + intro + thumbnail in one call."""
data = api({
"action": "query", "generator": "search", "gsrsearch": query,
"gsrlimit": limit, # extracts are capped at 20 pages per request
"prop": "info|description|extracts|pageimages",
"inprop": "url",
"exintro": 1, "explaintext": 1, "exsentences": 1, "exlimit": "max",
"piprop": "thumbnail", "pithumbsize": 200, "pilimit": "max",
})
pages = sorted(data["query"]["pages"], key=lambda p: p["index"]) # pages come unordered
return [{
"rank": p["index"],
"title": p["title"],
"url": p["fullurl"],
"description": p.get("description"),
"intro": p.get("extract"),
"thumbnail": p.get("thumbnail", {}).get("source"),
} for p in pages]
def suggest(prefix, limit=5):
"""Title autocomplete: action=opensearch (prefix match on titles, not full text)."""
data = api({"action": "opensearch", "search": prefix, "limit": limit})
return list(zip(data[1], data[3])) # [query, titles, descriptions, urls]
if __name__ == "__main__":
q = "electric vehicle battery"
total, rows = search(q, limit=5)
print(f"list=search: {total} hits for {q!r}")
for r in rows:
print(r["rank"], r["title"], "|", r["words"], "words")
print(" ", r["url"])
print(" ", r["snippet"][:90])
print("\ngenerator=search:")
for r in search_with_details(q, limit=3):
print(r["rank"], r["title"], "|", r["description"])
print(" ", r["intro"][:90])
print(" ", (r["thumbnail"] or "no image")[:90])
print("\nopensearch:")
for title, url in suggest("electric vehicle bat"):
print(title, "|", url)
print("\nincategory:")
total, rows = search('battery incategory:"Electric vehicles"', limit=5)
print(total, "hits")
for r in rows:
print(r["rank"], r["title"])
Output on 3 December 2026:
list=search: 8808 hits for 'electric vehicle battery'
1 Electric vehicle battery | 9759 words
https://en.wikipedia.org/wiki/Electric_vehicle_battery
electric vehicle battery (also known as a traction battery) is a rechargeable battery used
2 Battery electric vehicle | 7550 words
https://en.wikipedia.org/wiki/Battery_electric_vehicle
A battery electric vehicle (BEV), pure electric vehicle, only-electric vehicle, fully elec
3 List of battery electric vehicles | 2256 words
https://en.wikipedia.org/wiki/List_of_battery_electric_vehicles
Battery electric vehicles are vehicles exclusively using chemical energy stored in recharg
4 Extended-range electric vehicle | 7466 words
https://en.wikipedia.org/wiki/Extended-range_electric_vehicle
generator to recharge the traction battery when it is depleted. Unlike a conventional plug
5 List of electric vehicle battery manufacturers | 775 words
https://en.wikipedia.org/wiki/List_of_electric_vehicle_battery_manufacturers
Electric vehicle battery List of production battery electric vehicles Electric vehicle ind
generator=search:
1 Electric vehicle battery | Rechargeable battery used for vehicles
An electric vehicle battery (also known as a traction battery) is a rechargeable battery u
https://thumb.wikimedia.org/wikipedia/commons/thumb/4/40/Nissan_Leaf_012.JPG/250px-Nissan_
2 Battery electric vehicle | Type of electric vehicle
A battery electric vehicle (BEV), pure electric vehicle, only-electric vehicle, fully elec
https://thumb.wikimedia.org/wikipedia/commons/thumb/f/f2/Nissan_Leaf_and_Tesla_Model_S_in_
3 List of battery electric vehicles | Battery powered cars
Battery electric vehicles are vehicles exclusively using chemical energy stored in recharg
https://thumb.wikimedia.org/wikipedia/commons/thumb/b/b0/2020_Tesla_Model_Y%2C_front_5.16.
opensearch:
Electric vehicle battery | https://en.wikipedia.org/wiki/Electric_vehicle_battery
Electric vehicle battery supply chain | https://en.wikipedia.org/wiki/Electric_vehicle_battery_supply_chain
Electric vehicle warning sounds | https://en.wikipedia.org/wiki/Electric_vehicle_warning_sounds
Electric vehicle motors | https://en.wikipedia.org/wiki/Electric_vehicle_motors
Electric Vehicle Association | https://en.wikipedia.org/wiki/Electric_Vehicle_Association
(The incategory: part of the output is in its own section below.)
Why does list=search not return the article URL, and why is the snippet full of HTML?
list=search returns title, pageid, size, wordcount, snippet and timestamp, but no URL. Two ways to get one:
- Build it from the title, as
article_url()does: spaces become underscores, then URL-encode. That covers ordinary titles. - Use
generator=searchwithprop=info&inprop=url, and Wikipedia gives youfullurlitself.
The snippet is HTML. A raw one looks like this:
<span class="searchmatch">electric</span> <span class="searchmatch">vehicle</span> <span class="searchmatch">battery</span> (also known as a traction ...
Strip the tags and unescape entities (clean() above), or keep the searchmatch spans if you want to highlight the matched words in your own page. The snippet is a fragment around the match, not a summary: result 4 starts mid-sentence ("generator to recharge the traction battery..."). For a clean first sentence, ask for prop=extracts instead.
How do I get the URL, description and image of each search result in one request?
That is what generator=search is for. The generator runs the search, and every prop you add is filled in for those pages: info (with inprop=url), description (the short description shown under the title), extracts (exintro + explaintext for plain-text intro, exsentences=1 for just the first sentence) and pageimages (piprop=thumbnail, pithumbsize=200).
Two traps:
Results come back unordered. In my raw response the first page in the list was "List of battery electric vehicles", which is rank 3. Each page carries an index field with its search rank; sort by it, as search_with_details() does.
Intros are capped at 20 per request. When I asked for 50 results with gsrlimit=50, I got 50 pages but only 20 had an intro (50 pages, 20 with an intro in the paging run below). The TextExtracts module limits intro extracts to 20 pages per request and puts the rest behind a continue token. Keep gsrlimit at 20 or less when you need intros, or follow continue.
Not every article has a lead image, so thumbnail can be missing; the script prints no image in that case. Images live on Wikimedia Commons and each one has its own licence.
What are the limits of the Wikipedia search API, and how do I page past 500?
From the responses I got:
-
srlimitmaximum is 500. Ask for 1,000 and the API answers with a warning,The value "1000" for parameter "srlimit" must be between 1 and 500., and gives you 500. -
10,000 results per query, total.
sroffset=10000returns an error, not an empty page. -
Paging uses the
continueobject:{"sroffset": 500, "continue": "-||"}. Send thatsroffsetback for the next page.
from wiki_search import api, search, search_with_details
def search_all(query, max_results=1000):
"""Page through list=search with sroffset. Wikipedia stops at 10,000."""
seen, rows, offset = set(), [], 0
while offset < min(max_results, 10000):
data = api({"action": "query", "list": "search", "srsearch": query,
"srlimit": 500, "sroffset": offset, "srprop": ""})
for hit in data["query"]["search"]:
if hit["pageid"] not in seen: # ranking can shift between pages
seen.add(hit["pageid"])
rows.append(hit["title"])
if "continue" not in data:
break
offset = data["continue"]["sroffset"]
return rows
titles = search_all("electric vehicle battery", max_results=1000)
print(len(titles), "unique titles from 2 pages of 500")
rows = search_with_details("electric vehicle battery", limit=50)
print(len(rows), "pages,", sum(1 for r in rows if r["intro"]), "with an intro")
try:
search("electric vehicle battery", limit=10, offset=10000)
except RuntimeError as e:
print(e)
First run:
993 unique titles from 2 pages of 500
50 pages, 20 with an intro
cirrussearch-offset-too-large: Could not retrieve results. Up to 10000 search results are supported, but results starting at 10000 were requested.
Two earlier runs, seconds apart, printed 996 unique titles and 990 unique titles on the first line; the other two lines were the same each time. Two pages of 500 should give 1,000 titles. They did not, because the ranking moved between the request for page 1 and the request for page 2: some articles showed up on both pages (dropped by the seen check) and, by the same logic, some others were never returned. Search results are not a fixed list. If you need the same set every time, keep each result to 500 or fewer, or narrow the query.
How do I search for a term in a specific category?
Put incategory: in the search string:
search('battery incategory:"Electric vehicles"', limit=5)
Output from the same run as above:
incategory:
95 hits
1 Battery swapping
2 Battery electric bus
3 List of battery electric vehicles
4 Electric locomotive
5 Charging station
incategory: only looks at pages placed directly in that category. Help:CirrusSearch says it "no longer searches any subcategory automatically". On 1 December 2026, Category:Electric vehicles listed 141 pages and 39 subcategories, and incategory:"Electric vehicles" alone matched 129, so the articles in those 39 subcategories were not counted. You can list several categories (incategory:"A"|"B"), or use deepcat:, which searches up to 5 levels of subcategories through the Wikidata Query Service. I did not test deepcat: for this post.
Searching Wikipedia in another language means changing the host: https://de.wikipedia.org/w/api.php, https://ja.wikipedia.org/w/api.php, and so on. article_url() would need the same change.
What if I need search results on a schedule, or with Wikidata facts attached?
I built an Apify Actor, Wikipedia Scraper – Articles, Wikidata & Pageviews, that takes keywords (as well as titles, URLs and categories) and returns one row per article. There is a ready-made example, Top Wikipedia articles for a keyword search, which searches "electric vehicle battery" and keeps the top 20.
Input for a search run (field names from the README):
{
"searchQueries": ["electric vehicle battery"],
"maxResultsPerSearch": 20,
"language": "en",
"maxItems": 1000
}
What the README says about search runs:
- Each keyword returns up to
maxResultsPerSearcharticles (default 100, max 10,000) in Wikipedia's own order, withsearchRank(1 = first) andwordCounton each row, plus the same fields as any other article:sourceUrl,description, plain-textextract(intro),imageUrl,categories,lastEditedAt, and licence and attribution fields. - Up to 500 results per keyword come from a single request. Above 500 it pages, and the README states the same caveat as the run above: a few articles may repeat (repeats are dropped) or be missed, and the same keyword can return a slightly different set or order from one run to the next.
- Optional Wikidata properties, 30-day pageviews and full text at no extra charge.
- US$1.00 per 1,000 articles plus US$0.0005 per run start. Searches with no results cost nothing. Apify's free plan includes US$5 of usage a month, about 5,000 articles.
- At most 2 requests per second across all Wikimedia sites, and one run lasts at most 20 minutes. It does not remember earlier runs: each scheduled run returns all matching articles again.
It uses the official Wikimedia APIs and is not affiliated with or endorsed by the Wikimedia Foundation.
FAQ
Do I need an API key to use the Wikipedia search API?
No. Read requests to https://<language>.wikipedia.org/w/api.php work without a key or an account. You do need a descriptive User-Agent header with contact details; Wikimedia can block requests without one. Send one request at a time.
What is the difference between list=search and action=opensearch?
list=search is full-text search: it matches words anywhere in the article and returns ranked results with snippets and word counts. action=opensearch is title autocomplete: it matches the beginning of article titles and returns titles and URLs, which is what a search box suggestion list needs.
How many results can the Wikipedia search API return?
Up to 500 per request (srlimit) and 10,000 per query in total. Requesting sroffset=10000 returns the error cirrussearch-offset-too-large. For more articles on a topic, split it into narrower queries or use categories.
Why do I get different results when I run the same search twice?
The ranking is not fully fixed. In my test, two pages of 500 results for the same query gave 996, 990 and 993 unique titles on three runs, because articles moved between pages while I was paging. Deduplicate by pageid, and expect small differences between runs.
How do I get an image for each search result?
Use generator=search with prop=pageimages&piprop=thumbnail&pithumbsize=200. Each result that has a lead image gets a thumbnail.source URL. Articles without a lead image have no thumbnail field. Check the image's licence on its Wikimedia Commons file page before reusing it.
Can I search inside one Wikipedia category?
Yes. Add incategory:"Category name" to srsearch. It matches only pages placed directly in that category, not in its subcategories. deepcat: covers subcategories up to 5 levels deep.
Do you build URLs from titles yourself, or always ask the API for fullurl?
Disclosure: I built the Apify Actor mentioned in this post.
Top comments (0)