Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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". } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading