Disclosure: I built the Apify Actor mentioned near the end of this post.
To query Wikidata from Python, send a GET request to https://query.wikidata.org/sparql with your query in the query parameter, ask for JSON (format=json or the header Accept: application/sparql-results+json), and set a descriptive User-Agent, because the default python-requests one gets a 403. You do not need SPARQLWrapper or an API key. The part that actually bites is the data: wdt:P1082 (population) can return several values per city, and a reverse lookup on countries can return countries that no longer exist. Both give you duplicate rows.
Below: a small run_sparql() helper, a city population + country query, the two duplicate traps with real numbers, the fix, and what to use instead of SPARQL when you already know the Q-IDs.
How do I run a Wikidata SPARQL query from Python?
The Wikidata Query Service user manual documents the endpoint and its limits:
- GET or POST to
https://query.wikidata.org/sparql. - Results are XML by default, JSON with
format=jsonorAccept: application/sparql-results+json. - Every query has a hard deadline of 60 seconds.
- One client (user agent + IP) gets 60 seconds of processing time per 60 seconds, and 30 error queries per minute. Above that you get HTTP 429 with a
Retry-Afterheader. Clients that ignore 429s can be temporarily banned.
Here is the helper, followed by a query for the six cities I use as the example (Tokyo, Delhi, São Paulo, Lagos, Berlin, Toronto):
import time import requests ENDPOINT = "https://query.wikidata.org/sparql" HEADERS = { "User-Agent": "devto-example-script/1.0 (contact: you@example.com)", "Accept": "application/sparql-results+json", } def run_sparql(query, max_tries=4): """Run a SPARQL query on the Wikidata Query Service, return a list of dicts.""" for attempt in range(max_tries): r = requests.get(ENDPOINT, params={"query": query}, headers=HEADERS, timeout=70) if r.status_code == 429: # throttled: wait as long as the server says time.sleep(int(r.headers.get("Retry-After", 60))) continue r.raise_for_status() return [{k: v["value"] for k, v in b.items()} for b in r.json()["results"]["bindings"]] raise RuntimeError(f"still throttled after {max_tries} tries") CITIES = """ SELECT ?city ?cityLabel ?population ?countryLabel WHERE { VALUES ?city { wd:Q1490 wd:Q1353 wd:Q174 wd:Q8673 wd:Q64 wd:Q172 } ?city wdt:P1082 ?population ; wdt:P17 ?country . SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } ORDER BY DESC(?population) """ for row in run_sparql(CITIES): qid = row["city"].rsplit("/", 1)[-1] print(f'{qid:<6} {row["cityLabel"]:<10} {int(row["population"]):>12,} {row["countryLabel"]}') Output on 4 December 2026:
Q1353 Delhi 26,495,000 India Q8673 Lagos 15,070,000 Nigeria Q1490 Tokyo 14,264,798 Japan Q174 São Paulo 11,451,999 Brazil Q64 Berlin 3,700,577 Germany Q172 Toronto 2,794,356 Canada A few notes on the query:
-
P1082is population,P17is country.wdt:gives the "simple" value of a property; more on what that means in the next section. - The label service (
SERVICE wikibase:label) fills?cityLabeland?countryLabelfor any variable you name?xLabel. Without it you only get entity URIs. - The client timeout is 70 seconds, a little above the server's 60-second deadline, so a slow query fails on the server side with a real error message instead of a client timeout.
The User-Agent is not optional. The same request with requests' default user agent (python-requests/2.32.5) returned this:
403 Please set a user-agent and respect our robot policy https://w.wiki/4wJS. See also https://phabricator.wikimedia.org/T400119. Put a name for your script and a way to contact you in it, as the Wikimedia User-Agent policy asks.
I did not hit a 429 while writing this (each run was 4 requests), so the retry branch above is written from the manual and not tested against a real 429.
Why does my SPARQL query return the same city several times?
The six-city query looked clean because all six cities happen to have a population statement marked preferred. Run a broader query, every country's capital with its population, and the picture changes:
from collections import Counter CAPITALS = """ SELECT ?city ?cityLabel ?population ?countryLabel WHERE { ?country wdt:P31 wd:Q6256 ; wdt:P36 ?city . ?city wdt:P1082 ?population . SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } """ rows = run_sparql(CAPITALS) print(len(rows), "rows,", len(Counter(r["city"] for r in rows)), "distinct cities") for r in rows: if r["cityLabel"] in ("Hanoi", "Muscat"): print(f' {r["cityLabel"]:<7} {int(r["population"]):>10,} {r["countryLabel"]}') 251 rows, 218 distinct cities Hanoi 7,587,800 Vietnam Hanoi 7,785,000 Vietnam Hanoi 8,246,600 Vietnam Hanoi 8,330,800 Vietnam Hanoi 8,435,650 Vietnam Hanoi 8,717,600 Vietnam Muscat 1,421,409 Oman Muscat 1,421,409 Muscat and Oman Muscat 1,421,409 Sultanate of Muscat Two different causes:
1. Several population values, none preferred. wdt: returns "truthy" statements. The RDF dump format documentation defines them as the statements with the best non-deprecated rank: if a property has a preferred statement, only preferred ones count; if not, every normal-rank value is truthy. Hanoi has six population figures from different years and none is marked preferred, so you get six rows. This is the "preferred rank not working for population" question people keep asking: it works, the item just has no preferred value.
2. Countries that no longer exist. wdt:P31 wd:Q6256 ("instance of country") also matches historical states such as the Sultanate of Muscat, and their capital is still recorded. Muscat shows up three times with the same population.
How do I get only the most recent population value?
Switch from wdt: to the full statement form, p: (statement), ps: (its value) and pq: (a qualifier), so you can read each value's rank and its point-in-time qualifier P585. Then drop dissolved countries (those with P576, "dissolved, abolished or demolished date"):
CAPITALS_FULL = """ SELECT ?city ?cityLabel ?countryLabel ?population ?date ?rank WHERE { ?country wdt:P31 wd:Q6256 ; wdt:P36 ?city . FILTER NOT EXISTS { ?country wdt:P576 ?dissolved } ?city p:P1082 ?statement . ?statement ps:P1082 ?population ; wikibase:rank ?rank . FILTER(?rank != wikibase:DeprecatedRank) OPTIONAL { ?statement pq:P585 ?date } SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } """ def sort_key(row): preferred = row["rank"].endswith("#PreferredRank") return (preferred, row.get("date", "")) # preferred first, then newest date best = {} for row in run_sparql(CAPITALS_FULL): key = (row["city"], row["countryLabel"]) if key not in best or sort_key(row) > sort_key(best[key]): best[key] = row print(len(best), "city/country pairs,", len({k[0] for k in best}), "distinct cities") for row in sorted(best.values(), key=lambda r: r["cityLabel"]): if row["cityLabel"] in ("Hanoi", "Lomé", "Muscat", "Copenhagen"): print(f' {row["cityLabel"]:<10} {int(float(row["population"])):>10,} ' f'{row.get("date", "")[:10]:<10} {row["countryLabel"]}') 211 city/country pairs, 209 distinct cities Copenhagen 667,099 2025-01-01 Kingdom of Denmark Copenhagen 667,099 2025-01-01 Denmark Hanoi 8,717,600 2024-01-01 Vietnam Lomé 2,188,376 2023-01-01 Togo Muscat 1,421,409 2019-01-01 Oman What changed:
- One population per city: a preferred value wins; otherwise the value with the newest
P585date. Hanoi now has one row, the 2024 figure. - The 9 cities that were only listed as capitals of dissolved states are gone (for example Srinagar, recorded as the capital of the Kashmir Sultanate), which is why there are 209 cities instead of 218.
- Two cities still have two rows, and that is not an error: Wikidata models both "Denmark" and "Kingdom of Denmark" (and likewise the Netherlands and the Kingdom of the Netherlands) as current countries with the same capital. Decide which one you want and filter by Q-ID.
I pick the latest value in Python rather than in SPARQL because it is easier to debug: you can print every candidate row for one city. You can push the same logic into SPARQL with FILTER NOT EXISTS on a newer date, but the query gets harder to read and closer to the 60-second limit. The ISO date strings compare correctly as text for any year from 1 to 9999.
When should I skip SPARQL and use wbgetentities?
If you already have the Q-IDs, you do not need a query engine. The Wikidata Action API's wbgetentities returns whole items, up to 50 IDs per request (the documented limit for normal clients), and it is not subject to the 60-second query deadline. You apply the truthy rule yourself:
API = "https://www.wikidata.org/w/api.php" ids = ["Q1490", "Q1353", "Q174", "Q8673", "Q64", "Q172"] r = requests.get(API, headers=HEADERS, timeout=30, params={ "action": "wbgetentities", "ids": "|".join(ids), # up to 50 IDs per call "props": "labels|claims", "languages": "en", "format": "json", }) r.raise_for_status() def best_values(claims, prop): """Same rule as wdt: preferred statements if any, else normal ones.""" stmts = [s for s in claims.get(prop, []) if s["rank"] != "deprecated"] preferred = [s for s in stmts if s["rank"] == "preferred"] return [s["mainsnak"].get("datavalue", {}).get("value") for s in preferred or stmts] for qid, ent in r.json()["entities"].items(): pops = best_values(ent["claims"], "P1082") countries = best_values(ent["claims"], "P17") print(f'{ent["labels"]["en"]["value"]:<10} {len(ent["claims"]["P1082"]):>2} statements -> ' f'{[int(p["amount"]) for p in pops]} {[c["id"] for c in countries]}') Tokyo 6 statements -> [14264798] ['Q17'] Delhi 2 statements -> [26495000] ['Q668'] São Paulo 38 statements -> [11451999] ['Q155'] Lagos 13 statements -> [15070000] ['Q1033'] Berlin 67 statements -> [3700577] ['Q183'] Toronto 8 statements -> [2794356] ['Q16'] Same numbers as the SPARQL query, and the statement counts show how much history sits behind each figure (Berlin: 67 population statements). Countries come back as Q-IDs here; add them to a second wbgetentities call with props=labels if you need names.
Rule of thumb: SPARQL when you are searching ("all capitals", "every city over a million"), wbgetentities when you are looking up a list you already have.
What if I start from Wikipedia article titles, not Q-IDs?
That is the case I built a tool for. Wikipedia Scraper – Articles, Wikidata & Pageviews is an Apify Actor that takes Wikipedia titles, URLs, search keywords or categories, resolves each article to its Wikidata item, and returns the Wikidata properties you list next to the article's summary and coordinates. It is a client for the public Wikimedia APIs and is not affiliated with or endorsed by the Wikimedia Foundation.
There is a ready-made example with the same six cities, population (P1082) and country (P17): Population and country of world cities from Wikidata. Its input:
{ "titles": ["Tokyo", "Delhi", "São Paulo", "Lagos", "Berlin", "Toronto"], "language": "en", "wikidataProperties": ["P1082", "P17"], "includeFullText": false, "includePageviews": false, "maxItems": 50 } What to know before using it, from its README:
- It does not use SPARQL. It reads items with
wbgetentities, so it cannot answer "find all X" questions; you give it the articles. - Each property comes back as a list of every non-deprecated value with its
rank(preferredornormal). Picking the preferred one is still your job, and because qualifiers such asP585are not returned, you cannot pick "the newest" when an item has no preferred value. For Hanoi-type items, use the SPARQL query above. - Price: US$1.00 per 1,000 articles plus US$0.0005 per run start; Wikidata properties do not cost extra. Apify's free plan (US$5 of usage a month) covers about 5,000 articles.
- At most 2 requests per second across all Wikimedia sites, and one run lasts at most 20 minutes.
FAQ
Do I need SPARQLWrapper to query Wikidata from Python?
No. The endpoint https://query.wikidata.org/sparql accepts a plain GET with a query parameter and returns JSON when you send format=json or Accept: application/sparql-results+json. requests is enough. SPARQLWrapper works too, but you still have to set a custom User-Agent yourself.
Why does the Wikidata Query Service return 403?
Usually because of the User-Agent. A request with requests' default python-requests/x.y.z user agent got a 403 with the message "Please set a user-agent and respect our robot policy". Send a user agent that names your script and gives a contact.
How do I handle "429 Too Many Requests" on Wikidata?
Read the Retry-After header, sleep that many seconds, and retry. The service allows one client 60 seconds of query processing time per 60 seconds and 30 error queries per minute; clients that keep sending requests after a 429 can be temporarily banned. Running queries one at a time, not in parallel, avoids most 429s.
What is the difference between wdt: and p:/ps: in Wikidata SPARQL?
wdt:P1082 gives only the truthy values: preferred-rank values if the property has any, otherwise all normal-rank values. p:P1082 gives every statement node, from which ps:P1082 reads the value, pq:P585 the point-in-time qualifier and wikibase:rank the rank. Use p:/ps:/pq: when you need dates or want to choose between several values.
How do I get only the latest population from Wikidata?
Query p:P1082 with ps:P1082 and OPTIONAL { ?statement pq:P585 ?date }, drop deprecated statements, then per city keep the preferred value if there is one, otherwise the one with the newest date. In the capitals example this turned Hanoi's six rows into one (8,717,600, dated 2024-01-01).
How long can a Wikidata SPARQL query run?
60 seconds on the public endpoint. After that the query is cancelled. If you hit it, narrow the query (for example with VALUES for known items) or use wbgetentities when you already know the Q-IDs.
Do you pick the newest value in SPARQL or in your own code, and has either approach surprised you?
Disclosure: I built the Apify Actor mentioned in this post.