SPARQLWrapper Documentation
repository·master·Indexed 20 days ago
https://github.com/rdflib/sparqlwrapperA Python client library for interfacing with SPARQL endpoints. It enables remote execution of SELECT, ASK, CONSTRUCT, DESCRIBE, and UPDATE queries, providing utilities for result format conversion into Python dictionaries, DOM trees, and RDFlib Graph objects. Includes the SPARQLWrapper2 class for simplified SELECT processing and the rqw command line script.
What's inside SPARQLWrapper
- SPARQLWrapper is a Python library that provides a simple interface to interact with SPARQL services. It allows you to remotely execute SPARQL queries against an endpoint and provides utilities to manage query invocation and convert the resulting data into more manageable formats.
Automatic conversion of SPARQL results
masterSPARQLWrapper can automatically convert result streams into Python objects based on the return format:
- XML: Converted to a
xml.dom.minidomDOM tree. - JSON: Converted to a Python
dictusing thejsonpackage. - CSV/TSV: Converted to a simple
string. - RDF/XML and JSON-LD: Converted to an RDFlib
Graphinstance. - RDF Turtle/N3: Converted to a simple
string.
You can trigger this via
ret.convert()on the result ofsparql.query(), or usesparql.queryAndConvert()to get the converted object directly.- XML: Converted to a
Understand RDFLib dependency requirements
masterTheRDFLibpackage is used for RDF parsing. It is imported lazily, meaning it is only loaded when needed. If your use case does not involve specific RDF formats that requireRDFLib, you do not need to install it.How SPARQLWrapper2 handles partial results and OPTIONAL patterns
masterWhen using
SPARQLWrapper2, the returned query object provides enhanced features for navigating JSON results:ret.variables: An array of the variable names in the query.ret.bindings: An array of dictionaries representing the rows.inoperator: Check if a specific combination of variables exists in the results (useful forOPTIONALclauses).ret[var1, var2, ...]: Retrieve a subset of bindings that match specific variables.ret.getValues(var): Returns an array ofValueinstances for a specific variable.
Example of checking for optional variables:
from SPARQLWrapper import SPARQLWrapper2 sparql = SPARQLWrapper2("http://example.org/sparql") sparql.setQuery(""" SELECT ?subj ?obj ?opt WHERE { ?subj <http://a.b.c> ?obj . OPTIONAL { ?subj <http://d.e.f> ?opt } } """) try: ret = sparql.query() if ("subj", "obj", "opt") in ret: bindings = ret["subj", "obj", "opt"] for b in bindings: print(b["subj"].value, b["obj"].value, b["opt"].value) except Exception as e: print(e)Understand SPARQL endpoint output formats and negotiation
masterWhen querying a SPARQL endpoint, the response format depends on the query type (
SELECT,ASK,CONSTRUCT, orDESCRIBE) and how the server handles format requests. There are two primary ways servers determine the output format:- URL Parameters: The client provides a key (e.g.,
format,output, orresults) in the query string. - Content Negotiation: The client specifies the desired format via the HTTP
Acceptheader.
Different implementations use different parameter keys and support different MIME types. For example, Virtuoso uses
formatoroutput, while Fuseki usesformatoroutput, and RASQAL usesresults.- URL Parameters: The client provides a key (e.g.,
Install SPARQLWrapper from source
masterYou can install the package using
distutilsscripts:python setup.py installAlternatively, you can manually copy the
SPARQLWrapperdirectory into yourPYTHONPATH.Install SPARQLWrapper
masterYou can install SPARQLWrapper using
pipfrom PyPI, directly from GitHub, or via the Debian package manager.# From PyPI $ pip install sparqlwrapper # From GitHub $ pip install git+https://github.com/rdflib/sparqlwrapper#egg=sparqlwrapper # From Debian $ sudo apt-get install python-sparqlwrapperUse SPARQLWrapper as a command line script
masterAfter installing the package, a command line script named
rqw(spaRQl Wrapper) is available in your Python environment. You can view all available options by running the help command.$ rqw -hInstall SPARQLWrapper for development
masterTo install the package and its development dependencies (required for running tests), use
pipwith the[dev]extra:pip install '.[dev]'Configure HTTP methods (GET vs POST)
masterBy default, SPARQLWrapper uses the HTTP GET verb. If your query is large, you can switch to POST usingsparql.setMethod(POST). Note that some SPARQL endpoints may not support certain combinations, such asPOSTwith aJSONreturn format.Execute ASK queries and get XML results
masterFor
ASKqueries, you can set the return format toXML. Usequery().convert()to transform the response into a DOM tree representation.from SPARQLWrapper import SPARQLWrapper, XML sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" ASK WHERE { <http://dbpedia.org/resource/Asturias> rdfs:label "Asturias"@es } """) sparql.setReturnFormat(XML) results = sparql.query().convert() print(results.toxml())Execute DESCRIBE queries and get JSON-LD
masterDESCRIBEqueries also return RDF. You can usequeryAndConvert()to get an RDFlibGraphand then serialize it to specific formats likejson-ld.from SPARQLWrapper import SPARQLWrapper sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery("DESCRIBE <http://dbpedia.org/resource/Asturias>") results = sparql.queryAndConvert() print(results.serialize(format="json-ld"))