SPARQLWrapper Documentation

repository·master·Indexed 20 days ago

https://github.com/rdflib/sparqlwrapper

A 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.

Tokens
5.3K
Snippets
11
Records
30
Agent score
69%

What's inside SPARQLWrapper

  1. What is SPARQLWrapper?

    master
    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.
  2. Automatic conversion of SPARQL results

    master

    SPARQLWrapper can automatically convert result streams into Python objects based on the return format:

    • XML: Converted to a xml.dom.minidom DOM tree.
    • JSON: Converted to a Python dict using the json package.
    • CSV/TSV: Converted to a simple string.
    • RDF/XML and JSON-LD: Converted to an RDFlib Graph instance.
    • RDF Turtle/N3: Converted to a simple string.

    You can trigger this via ret.convert() on the result of sparql.query(), or use sparql.queryAndConvert() to get the converted object directly.

  3. Understand RDFLib dependency requirements

    master
    The RDFLib package 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 require RDFLib, you do not need to install it.
  4. How SPARQLWrapper2 handles partial results and OPTIONAL patterns

    master

    When 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.
    • in operator: Check if a specific combination of variables exists in the results (useful for OPTIONAL clauses).
    • ret[var1, var2, ...]: Retrieve a subset of bindings that match specific variables.
    • ret.getValues(var): Returns an array of Value instances 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)
  5. Understand SPARQL endpoint output formats and negotiation

    master

    When querying a SPARQL endpoint, the response format depends on the query type (SELECT, ASK, CONSTRUCT, or DESCRIBE) and how the server handles format requests. There are two primary ways servers determine the output format:

    1. URL Parameters: The client provides a key (e.g., format, output, or results) in the query string.
    2. Content Negotiation: The client specifies the desired format via the HTTP Accept header.

    Different implementations use different parameter keys and support different MIME types. For example, Virtuoso uses format or output, while Fuseki uses format or output, and RASQAL uses results.

  6. Install SPARQLWrapper

    master

    You can install SPARQLWrapper using pip from 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-sparqlwrapper
  7. Configure HTTP methods (GET vs POST)

    master
    By default, SPARQLWrapper uses the HTTP GET verb. If your query is large, you can switch to POST using sparql.setMethod(POST). Note that some SPARQL endpoints may not support certain combinations, such as POST with a JSON return format.
  8. Execute ASK queries and get XML results

    master

    For ASK queries, you can set the return format to XML. Use query().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())
  9. Execute DESCRIBE queries and get JSON-LD

    master

    DESCRIBE queries also return RDF. You can use queryAndConvert() to get an RDFlib Graph and then serialize it to specific formats like json-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"))