Registry / http-networking / sparqlwrapper

sparqlwrapper

JSON →
library2.0.0pypypi✓ verified 23d ago

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 sparqlwrapper
INSTALL
IMPORT
SIG · SPARQLWRAPPER
S
sparqlwrapper
http-networkingpythonv2.0.0
Install
2.1s avg
Import
161ms
Disk
22MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.174s · 23.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.1s · import 0.148s · 24MB
22MB installed
● package 22MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SPARQLWrapper
from SPARQLWrapper import SPARQLWrapper
JSON
from SPARQLWrapper import JSON
Commonly imported constant for setting JSON return format.

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}")
Debug
Known issues
breakingVersion 2.0.0 completely dropped support for Python 2. Codebases using SPARQLWrapper on Python 2 must migrate to Python 3 before upgrading to 2.0.0 or later.
fix
Ensure your project is running on Python 3.7+ (as per PyPI metadata) and update your environment accordingly.
affects: >=2.0.0
breakingSPARQLWrapper 2.0.0 requires RDFLib version 6.1.1 or higher. Older versions of RDFLib may cause compatibility issues, especially with CONSTRUCT/DESCRIBE query results.
fix
Upgrade RDFLib to `rdflib>=6.1.1` in your project's dependencies.
affects: >=2.0.0
gotchaIf `setReturnFormat()` is not explicitly called, SPARQLWrapper defaults to XML for SELECT queries and HTML for ASK queries, which might not be what you expect for easy programmatic access. Always set the desired return format (e.g., `JSON`, `RDFXML`) for predictable results.
fix
Always call `sparql.setReturnFormat(FORMAT_CONSTANT)` (e.g., `JSON`, `RDFXML`, `TURTLE`) before executing a query.
affects: All
gotchaWhen fetching results, you can either use `sparql.query().convert()` or `sparql.queryAndConvert()`. The latter is often preferred for simplicity as it directly returns the converted Python object (e.g., a dictionary for JSON), avoiding an intermediate stream object.
fix
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()`.
affects: All
gotchaSPARQLWrapper raises specific exceptions like `QueryBadFormed`, `EndPointNotFound`, `EndPointInternalError`, and `Unauthorized` for various issues. Not catching these can lead to unhandled program termination.
fix
Wrap your query execution in a `try...except` block to gracefully handle potential SPARQL-related errors, importing specific exceptions from `SPARQLWrapper.SPARQLExceptions`.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'sparqlwrapper'
The `sparqlwrapper` library is either not installed, or it has been installed as `SPARQLWrapper` (uppercase) but is being imported using `import sparqlwrapper` (lowercase).
fix
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`.
sparqlwrapper.SPARQLWrapperException.SPARQLWrapperException: [Errno 400] Bad Request
This error indicates that the SPARQL query sent to the endpoint is syntactically incorrect, contains undefined prefixes, or is semantically invalid for the target SPARQL service, leading the server to return an HTTP 400 status.
fix
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.
TypeError: argument of type 'SPARQLWrapper.SPARQLWrapper.SPARQLWrapperResult' is not iterable
The result object returned by `sparql.query()` is a raw `SPARQLWrapperResult` object, which cannot be directly iterated. It must first be converted into a specific format (e.g., JSON, XML, RDFLib Graph) before processing.
fix
After executing the query, explicitly call the `convert()` method on the result object, or use `queryAndConvert()` directly. For example: `results = sparql.query().convert()`.
AttributeError: 'SPARQLWrapper' object has no attribute 'setQuery'
This error occurs when trying to call a method with incorrect capitalization or a misspelled name. The correct method name is `setQuery` (case-sensitive).
fix
Ensure you are using the correct method name with proper capitalization: `sparql.setQuery('SELECT ?s WHERE { ?s ?p ?o } LIMIT 10')`.
Upgrade
Version history
2.0.0latest on PyPI · released Mar 13, 2022
Audit
Dependencies
rdflibrequiredRequired for RDF graph results (CONSTRUCT/DESCRIBE queries) and version 2.0.0 specifically requires RDFLib >= 6.1.1.
Agent activity
9 hits · last 30 days
node
6
OpenAI (training)
1
Resources
sparqlwrapper — pip install sparqlwrapper · libregistry