Add validation for SELECT query return formats
Overview
This PR adds validation to prevent semantically incorrect usage of RDF return formats with SELECT queries in SPARQLWrapper. SELECT queries return result sets, not RDF graphs, so requesting RDF formats like RDF/XML, Turtle, N3, or JSON-LD is semantically incorrect and can lead to confusing server errors.
This PR is a compilation of #220 #218 solutions for #190 issue
Changes Made
Core Changes
-
Added validation logic in
SPARQLWrapper/Wrapper.py:- Defined
unsupportedReturnTypesForSelectQueries = [RDF, RDFXML, TURTLE, N3, JSONLD] - Added validation in
_getAcceptHeader()method to raiseValueErrorwhen RDF formats are used with SELECT queries - Clear error message indicates the invalid format and lists supported formats
- Defined
Test Coverage
-
Added comprehensive test suite in
test/test_wrapper.py:-
testSelectQueryWithRDFFormatsRaisesValueError: Tests that all RDF formats raise appropriate ValueError -
testSelectQueryWithValidFormatsWorks: Ensures valid formats (XML, JSON, CSV, TSV) work correctly - Fixed existing test that was affected by the new validation
-
Motivation
- Prevents user confusion: Users often accidentally request RDF formats for SELECT queries, leading to server errors or unexpected behavior
- Semantic correctness: SELECT queries return result sets, not RDF graphs, so RDF formats are conceptually wrong
- Better error messages: Instead of cryptic server errors, users get clear, actionable error messages
Breaking Changes
⚠️ This is a breaking change for existing code that incorrectly uses RDF formats with SELECT queries. Such code will now raise a ValueError instead of sending invalid requests to the server.
Testing
- [x] Unit tests pass
- [x] All existing tests continue to pass
- [x] New validation tests cover both error and success cases
- [x] Manual testing completed
Example
# This will now raise a ValueError with a clear message:
wrapper = SPARQLWrapper("http://example.org/sparql")
wrapper.setQuery("SELECT * WHERE { ?s ?p ?o }")
wrapper.setReturnFormat(TURTLE) # Raises ValueError!
Error message: TURTLE is not a valid return format for SELECT queries. Supported formats include: json, xml, csv, tsv
Related Issues
This addresses the semantic issue where users could request inappropriate return formats for SELECT queries, which could lead to confusing server responses or errors.