Getting Wikidata Query results in JSON

Method 2 - POST request API call from Python

Use a POST request to get the JSON, then convert the result into a Pandas Dataframe, a 2D data structure.

import requests
import pandas as pd

wikidata_api_url = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql'

query = '''
# Cats
SELECT ?item WHERE { 
  ?item wdt:P31 wd:Q146.
}
'''

data = requests.post(wikidata_api_url, data={'query': query, 'format': 'json'}).json()

resultarray = []
for item in data['results']['bindings']:
    resultarray.append({
        'qid': int(item['item']['value'].replace('http://www.wikidata.org/entity/Q',''))})

# Create a Pandas dataframe    
result_df = pd.DataFrame(resultarray)

result_df
qid
0 28114532
1 28114535
2 28665865
3 28792126
4 30600575
5 42442324
6 43260736
7 48895080
8 49581026
9 50378472
10 50824969
11 51596094
12 51827254
13 51841231
14 52150156
15 53216650
16 54087698
17 54257563
18 55632071
19 56427306
20 56471556
21 57251591
22 57271818
23 57623398
24 58310774
25 58311218
26 58621231
27 60213636
28 61133276
29 62128317
... ...
103 17115877
104 17537171
105 17576799
106 18945952
107 19850466
108 19880492
109 19906739
110 20080934
111 21002390
112 21041964
113 21050077
114 21426728
115 21641529
116 21652863
117 22774485
118 24084366
119 24298806
120 24705153
121 25171691
122 25393350
123 25471040
124 27190410
125 27739753
126 27744042
127 27745002
128 27745006
129 27745008
130 27745009
131 27745011
132 27926432

133 rows × 1 columns