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.
pip install sparqlwrapperVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your project is running on Python 3.7+ (as per PyPI metadata) and update your environment accordingly.
Upgrade RDFLib to `rdflib>=6.1.1` in your project's dependencies.
Always call `sparql.setReturnFormat(FORMAT_CONSTANT)` (e.g., `JSON`, `RDFXML`, `TURTLE`) before executing a query.
For immediate conversion, use `results = sparql.queryAndConvert()`. If you need to access the raw HTTP response stream, use `raw_response = sparql.query()` and then `converted_results = raw_response.convert()`.
Wrap your query execution in a `try...except` block to gracefully handle potential SPARQL-related errors, importing specific exceptions from `SPARQLWrapper.SPARQLExceptions`.
First, ensure the library is installed with `pip install SPARQLWrapper`. Then, use the correct capitalization for the import statement, for example: `from SPARQLWrapper import SPARQLWrapper`.
Carefully review and debug your SPARQL query for syntax errors, ensure all required prefixes are defined using `sparql.addPrefix()`, and verify that the query is valid for the specific SPARQL endpoint you are targeting.
After executing the query, explicitly call the `convert()` method on the result object, or use `queryAndConvert()` directly. For example: `results = sparql.query().convert()`.
Ensure you are using the correct method name with proper capitalization: `sparql.setQuery('SELECT ?s WHERE { ?s ?p ?o } LIMIT 10')`.