{"id":4263,"library":"sparqlwrapper","title":"SPARQLWrapper","description":"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.","status":"active","version":"2.0.0","language":"en","source_language":"en","source_url":"https://github.com/RDFLib/sparqlwrapper","tags":["sparql","rdf","linked-data","query","semantic-web"],"install":[{"cmd":"pip install sparqlwrapper","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Required for RDF graph results (CONSTRUCT/DESCRIBE queries) and version 2.0.0 specifically requires RDFLib >= 6.1.1.","package":"rdflib","optional":false}],"imports":[{"symbol":"SPARQLWrapper","correct":"from SPARQLWrapper import SPARQLWrapper"},{"note":"Commonly imported constant for setting JSON return format.","symbol":"JSON","correct":"from SPARQLWrapper import JSON"}],"quickstart":{"code":"import os\nfrom SPARQLWrapper import SPARQLWrapper, JSON\n\n# Use a placeholder for the endpoint URL, expecting an environment variable\n# or defaulting to a known public endpoint if available (e.g., DBpedia or a test endpoint)\nSPARQL_ENDPOINT = os.environ.get('SPARQL_ENDPOINT', 'http://dbpedia.org/sparql')\n\nsparql = SPARQLWrapper(SPARQL_ENDPOINT)\n\n# Example: Query for the first 5 English labels of DBPedia resources\nsparql.setQuery(\"\"\"\n    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n    SELECT ?resource ?label\n    WHERE {\n        ?resource rdfs:label ?label .\n        FILTER (lang(?label) = 'en')\n    }\n    LIMIT 5\n\"\"\")\n\nsparql.setReturnFormat(JSON)\n\ntry:\n    # queryAndConvert() directly returns a Python object (e.g., dict for JSON)\n    results = sparql.queryAndConvert()\n    \n    print(\"Query Results:\")\n    for result in results[\"results\"][\"bindings\"]:\n        resource_uri = result[\"resource\"][\"value\"]\n        label = result[\"label\"][\"value\"]\n        print(f\"Resource: {resource_uri}, Label: {label}\")\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\n","lang":"python","description":"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."},"warnings":[{"fix":"Ensure your project is running on Python 3.7+ (as per PyPI metadata) and update your environment accordingly.","message":"Version 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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Upgrade RDFLib to `rdflib>=6.1.1` in your project's dependencies.","message":"SPARQLWrapper 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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always call `sparql.setReturnFormat(FORMAT_CONSTANT)` (e.g., `JSON`, `RDFXML`, `TURTLE`) before executing a query.","message":"If `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.","severity":"gotcha","affected_versions":"All"},{"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()`.","message":"When 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.","severity":"gotcha","affected_versions":"All"},{"fix":"Wrap your query execution in a `try...except` block to gracefully handle potential SPARQL-related errors, importing specific exceptions from `SPARQLWrapper.SPARQLExceptions`.","message":"SPARQLWrapper raises specific exceptions like `QueryBadFormed`, `EndPointNotFound`, `EndPointInternalError`, and `Unauthorized` for various issues. Not catching these can lead to unhandled program termination.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}