Robert Alexander
Robert Alexander

Reputation: 1151

SPARQLWrapper query error with an f-string : QueryBadFormed

I am trying to lookup the names of Italian Senators in a public SPARQL endpoint.

Starting sample data is the following set:

longnames = ['Lars Danielsson', 'Giorgia Meloni', 'Ursula von der Leyen', 'Filippo Mannino', 'Matteo Piantedosi', 'Lamberto Giannini']

and here the relevant part of my code:

from SPARQLWrapper import SPARQLWrapper, JSON
endpoint = "http://dati.senato.it/sparql"
sparql = SPARQLWrapper(endpoint)
sparql.setReturnFormat(JSON)

for label in longnames:
    sparqlquery = f"""
    PREFIX osr:<http://dati.senato.it/osr/>
    SELECT * WHERE {{
        ?uri a osr:Senatore. 
        ?uri rdfs:label '{label}'^^xsd:string.
    }}
    """
    print(f"{endpoint} ---> {sparqlquery}")
    sparql.setQuery(sparqlquery)
    try:
        ret = sparql.queryAndConvert()
        for r in ret["results"]["bindings"]:
            print(r)
    except Exception as e:
        print(e)

Please note that I am building the SPARQL query using an f-string. Sadly this code gives an error I'm not understanding despite the line printing the endpoint and the query looks perfectly allright. Here's the error:

QueryBadFormed: A bad request has been sent to the endpoint: probably the SPARQL query is badly formed.

Response:
b"Virtuoso 37000 Error SP030: SPARQL compiler, line 0: Invalid character in SPARQL expression at '%'\n\nSPARQL query:\ndefine sql:big-data-const 0 \n#output-format:application/sparql-results+json\n%0A PREFIX osr%3A%3Chttp%3A//dati.senato.it/osr/%3E%0A SELECT %2A WHERE %7B%0A %3Furi a osr%3ASenatore. %0A %3Furi rdfs%3Alabel %27Ursula von der Leyen%27%5E%5Exsd%3Astring.%0A %7D%0A "

What am I doing wrong?

Upvotes: 0

Views: 101

Answers (0)

Related Questions