pythonpython-requestssparqlwikidatawikidata-query-service

How to pass python variable to sparql query?


I would expect/hope something like this works:

import requests

my_variable = 'wd:Q1968435'

url = 'https://query.wikidata.org/sparql'
query = """
    SELECT ?item ?itemLabel 
        WHERE 
            {
            ?item wdt:P31 "+my_variable+".
            SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
            }
    """
r = requests.get(url, params= {'format': 'json', 'query': query})
data = r.json()

But this does not work. Is there a simple solution?

Thanks in advance!


Solution

  • Taking as example this answer, I modified your code for concatenating your multiline string as follows:

    import requests
    
    my_variable = 'wd:Q1968435'
    
    url = 'https://query.wikidata.org/sparql'
    query = (
        'SELECT ?item ?itemLabel ',
         '   WHERE ',
         '       {',
         '       ?item wdt:P31 '+my_variable+'.', 
         '       SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }'
         '       }'
    )
    
    # make request: 
    r = requests.get(url, params= {'format': 'json', 'query': "".join(query)})
    data = r.json()
    print("".join(query)) # Here I'm printing the string concatenated as single line.
    
    # Print the result of the request.
    print(data)
    

    The result of the previous string concatenation is:

    SELECT ?item ?itemLabel    WHERE        {       ?item wdt:P31 wd:Q1968435.       SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }