Setup Python to do a Wikidata Query API SPARQL request

import requests
import pandas as pd

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

Craft the query in a string, make request to API

How many Wikidata items have: collection->Met, subject has role->collection highlight?

The query example in WDQS

query = '''
SELECT (COUNT(?item) as ?count) WHERE { 
  BIND (wd:Q160236 AS ?institution)
  ?item wdt:P195 ?institution .
  ?item p:P195 [ ps:P195 ?id ; pq:P2868 wd:Q29188408 ]  .
}
'''
data = requests.post(wikidata_api_url, data={'query': query, 'format': 'json'}).json()

data
{'head': {'vars': ['count']},
 'results': {'bindings': [{'count': {'datatype': 'http://www.w3.org/2001/XMLSchema#integer',
     'type': 'literal',
     'value': '1597'}}]}}

Access the exact JSON field

int(data['results']['bindings'][0]['count']['value'])
1597
print ('Wikidata has', int(data['results']['bindings'][0]['count']['value']), 'items with collection->Met, subject has role->collection highlight')
Wikidata has 1597 items with collection->Met, subject has role->collection highlight