SPARQLWrapper

2.0.0 · active · verified Sat Apr 11

SPARQLWrapper is a Python library that provides a simple wrapper around a SPARQL service to remotely execute queries. It helps in creating the query invocation and, optionally, converting the result into a more manageable format like JSON or an RDFLib Graph. The current major version is 2.0.0, which was a significant update focusing on Python 3 compatibility. Releases occur periodically, with the last major release in March 2022.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize SPARQLWrapper with an endpoint, set a SPARQL SELECT query, specify JSON as the return format, and process the results. It retrieves 5 English labels from a generic SPARQL endpoint, defaulting to DBpedia if no `SPARQL_ENDPOINT` environment variable is set.

import os
from SPARQLWrapper import SPARQLWrapper, JSON

# Use a placeholder for the endpoint URL, expecting an environment variable
# or defaulting to a known public endpoint if available (e.g., DBpedia or a test endpoint)
SPARQL_ENDPOINT = os.environ.get('SPARQL_ENDPOINT', 'http://dbpedia.org/sparql')

sparql = SPARQLWrapper(SPARQL_ENDPOINT)

# Example: Query for the first 5 English labels of DBPedia resources
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?resource ?label
    WHERE {
        ?resource rdfs:label ?label .
        FILTER (lang(?label) = 'en')
    }
    LIMIT 5
""")

sparql.setReturnFormat(JSON)

try:
    # queryAndConvert() directly returns a Python object (e.g., dict for JSON)
    results = sparql.queryAndConvert()
    
    print("Query Results:")
    for result in results["results"]["bindings"]:
        resource_uri = result["resource"]["value"]
        label = result["label"]["value"]
        print(f"Resource: {resource_uri}, Label: {label}")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →