How to run a sparql query from Python over my GraphDB repository?

2k Views Asked by At

I'm trying to run a simple query:

"""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { ?a rdfs:label ?label }
""")

Over my GraphDB repository, but from Python. After some searching I found that SPARQL wrapper can be used for this, but I'm not sure how to make python connect to my GraphDB (endpoint?). I have no experience with API's. What I have so far:

from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("http://192.168.0.12:7200/repositories/MyRepository")
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { ?a rdfs:label ?label }
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
    print(result["label"]["value"])

print('---------------------------')

for result in results["results"]["bindings"]:
    print('%s: %s' % (result["label"]["xml:lang"], result["label"]["value"]))

I copied this example query from another stackoverflow, but only changed the subject of the where query so it works with my data, and it works with the repository they pointed to there (http://dbpedia.org/sparql), but not with the link that I get from the repository in graphDB.

Any ideas?

2

There are 2 best solutions below

1
On

The key is to make sure the link you are using to connect to your repository is not the version GraphDB gives you, but the localhost version of that link. GraphDB provides you with an ipadress link. You have to replace the ip adress with "localhost" and it will work. (at least locally).

0
On

Considering that the solution mentioned by Robin may not work for everyone, I'll introduce the formal method for this case:

  1. Open your GraphDB -> Right sidebars -> Setup -> Repositories
  2. Find the interested repository -> Click the "Copy repository URL to clipboard" button
  3. Enter the copied URL between the quotations sparql = SPARQLWrapper("")

Then it should work fine.