SPARQLWrapper.Wrapper module
- SPARQLWrapper.Wrapper.XML = 'xml'
to be used to set the return format to
XML
(SPARQL Query Results XML
format orRDF/XML
, depending on the query type). This is the default.
- SPARQLWrapper.Wrapper.JSON = 'json'
to be used to set the return format to
JSON
.
- SPARQLWrapper.Wrapper.JSONLD = 'json-ld'
to be used to set the return format to
JSON-LD
.
- SPARQLWrapper.Wrapper.TURTLE = 'turtle'
to be used to set the return format to
Turtle
.
- SPARQLWrapper.Wrapper.N3 = 'n3'
to be used to set the return format to
N3
(for most of the SPARQL services this is equivalent to Turtle).
- SPARQLWrapper.Wrapper.RDF = 'rdf'
to be used to set the return
RDF Graph
.
- SPARQLWrapper.Wrapper.RDFXML = 'rdf+xml'
to be used to set the return format to
RDF/XML
explicitly.
- SPARQLWrapper.Wrapper.CSV = 'csv'
to be used to set the return format to
CSV
- SPARQLWrapper.Wrapper.TSV = 'tsv'
to be used to set the return format to
TSV
- SPARQLWrapper.Wrapper.GET = 'GET'
to be used to set HTTP method
GET
. This is the default.
- SPARQLWrapper.Wrapper.POST = 'POST'
to be used to set HTTP method
POST
.
- SPARQLWrapper.Wrapper.BASIC = 'BASIC'
to be used to set
BASIC
HTTP Authentication method.
- SPARQLWrapper.Wrapper.DIGEST = 'DIGEST'
to be used to set
DIGEST
HTTP Authentication method.
- SPARQLWrapper.Wrapper.SELECT = 'SELECT'
to be used to set the query type to
SELECT
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.CONSTRUCT = 'CONSTRUCT'
to be used to set the query type to
CONSTRUCT
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.ASK = 'ASK'
to be used to set the query type to
ASK
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.DESCRIBE = 'DESCRIBE'
to be used to set the query type to
DESCRIBE
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.INSERT = 'INSERT'
to be used to set the query type to
INSERT
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.DELETE = 'DELETE'
to be used to set the query type to
DELETE
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.CREATE = 'CREATE'
to be used to set the query type to
CREATE
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.CLEAR = 'CLEAR'
to be used to set the query type to
CLEAR
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.DROP = 'DROP'
to be used to set the query type to
DROP
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.LOAD = 'LOAD'
to be used to set the query type to
LOAD
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.COPY = 'COPY'
to be used to set the query type to
COPY
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.MOVE = 'MOVE'
to be used to set the query type to
MOVE
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.ADD = 'ADD'
to be used to set the query type to
ADD
. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.URLENCODED = 'urlencoded'
to be used to set URL encode as the encoding method for the request. This is, usually, determined automatically.
- SPARQLWrapper.Wrapper.POSTDIRECTLY = 'postdirectly'
to be used to set POST directly as the encoding method for the request. This is, usually, determined automatically.
- class SPARQLWrapper.Wrapper.SPARQLWrapper(endpoint: str, updateEndpoint: Optional[str] = None, returnFormat: str = 'xml', defaultGraph: Optional[str] = None, agent: str = 'sparqlwrapper 2.0.1a0 (rdflib.github.io/sparqlwrapper)')[source]
Wrapper around an online access to a SPARQL Web entry point.
The same class instance can be reused for subsequent queries. The values of the base Graph URI, return formats, etc, are retained from one query to the next (in other words, only the query string changes). The instance can also be reset to its initial values using the
resetQuery()
method.- Variables
endpoint (string) – SPARQL endpoint’s URI.
updateEndpoint – SPARQL endpoint’s URI for SPARQL Update operations (if it’s a different one).
The default value is
None
. :vartype updateEndpoint: string :ivar agent: The User-Agent for the HTTP request header. The default value is an autogenerated string using t he SPARQLWrapper version code. :vartype agent: string :ivar _defaultGraph: URI for the default graph. The value can be set either via an explicit calladdParameter("default-graph-uri", uri)
or as part of the query string. The default value isNone
. :vartype _defaultGraph: string :ivar user: The username of the credentials for querying the current endpoint. The value can be set an explicit callsetCredentials()
. The default value isNone
. :vartype user: string :ivar passwd: The password of the credentials for querying the current endpoint. The value can be set an explicit callsetCredentials()
. The default value isNone
. :vartype passwd: string :ivar http_auth: HTTP Authentication type. The default value isBASIC
. Possible values areBASIC
orDIGEST
. It is used only in case the credentials are set. :vartype http_auth: string :ivar onlyConneg: Option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters). The default value isFalse
. :vartype onlyConneg: boolean :ivar customHttpHeaders: Custom HTTP Headers to be included in the request. It is a dictionary where keys are the header field and values are the header values. Important: These headers override previous values (includingContent-Type
,User-Agent
,Accept
andAuthorization
if they are present). :vartype customHttpHeaders: dict :ivar timeout: The timeout (in seconds) to use for querying the endpoint. :vartype timeout: int :ivar queryString: The SPARQL query text. :vartype queryString: string :ivar queryType: The type of SPARQL query (aka SPARQL query form), likeCONSTRUCT
,SELECT
,ASK
,DESCRIBE
,INSERT
,DELETE
,CREATE
,CLEAR
,DROP
,LOAD
,COPY
,MOVE
orADD
(constants in this module). :vartype queryType: string :ivar returnFormat: The return format. No local check is done, so the parameter is simply sent to the endpoint. Eg, if the value is set toJSON
and a construct query is issued, it is up to the endpoint to react or not, this wrapper does not check. The possible values areJSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). The default value isXML
. :vartype returnFormat: string :ivar requestMethod: The request method for query or update operations. The possibles values are URL-encoded (URLENCODED
) or POST directly (POSTDIRECTLY
). :vartype requestMethod: string :ivar method: The invocation method (HTTP verb). The default value isGET
, but it can be set toPOST
. :vartype method: string :ivar parameters: The parameters of the request (key/value pairs in a dictionary). :vartype parameters: dict :ivar _defaultReturnFormat: The default return format. It is used in case the same class instance is reused for subsequent queries. :vartype _defaultReturnFormat: string- Variables
prefix_pattern (
re.RegexObject
, a compiled regular expression. See there
module of Python) – regular expression used to remove base/prefixes in the process of determining the query type.pattern – regular expression used to determine whether a query (without base/prefixes) is of type
CONSTRUCT
,SELECT
,ASK
,DESCRIBE
,INSERT
,DELETE
,CREATE
,CLEAR
,DROP
,LOAD
,COPY
,MOVE
orADD
. :vartype pattern:re.RegexObject
, a compiled regular expression. See there
module of Python :cvar comments_pattern: regular expression used to remove comments from a query. :vartype comments_pattern:re.RegexObject
, a compiled regular expression. See there
module of Python- __init__(endpoint: str, updateEndpoint: Optional[str] = None, returnFormat: str = 'xml', defaultGraph: Optional[str] = None, agent: str = 'sparqlwrapper 2.0.1a0 (rdflib.github.io/sparqlwrapper)') None [source]
Class encapsulating a full SPARQL call.
- Parameters
endpoint (string) – SPARQL endpoint’s URI.
updateEndpoint – SPARQL endpoint’s URI for update operations (if it’s a different one). The default
value is
None
. :type updateEndpoint: string :param returnFormat: The return format. No local check is done, so the parameter is simply sent to the endpoint. Eg, if the value is set toJSON
and a construct query is issued, it is up to the endpoint to react or not, this wrapper does not check. The possible values areJSON
,XML
,TURTLE
,N3
,RDF
,RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). The default value isXML
. :param defaultGraph: URI for the default graph. The value can be set either via an explicit calladdParameter("default-graph-uri", uri)
or as part of the query string. The default value isNone
. :type defaultGraph: string :param agent: The User-Agent for the HTTP request header. The default value is an autogenerated string using the SPARQLWrapper version number. :type agent: string
- resetQuery() None [source]
Reset the query, ie, return format, method, query, default or named graph settings, etc, are reset to their default values. This includes the default values for parameters, method, timeout or requestMethod.
- setReturnFormat(format: str) None [source]
Set the return format. If the one set is not an allowed value, the setting is ignored.
RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). All other cases are ignored. :type format: string :raises ValueError: IfJSONLD
is tried to set and the current instance does not supportJSON-LD
.
- supportsReturnFormat(format: str) bool [source]
Check if a return format is supported.
RDFXML
,CSV
,TSV
,JSONLD
(constants in this module). All other cases are ignored. :type format: string :return: ReturnsTrue
if the return format is supported, otherwiseFalse
. :rtype: bool
- setTimeout(timeout: int) None [source]
Set the timeout (in seconds) to use for querying the endpoint.
- Parameters
timeout (int) – Timeout in seconds.
- setOnlyConneg(onlyConneg: bool) None [source]
Set this option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters).
New in version 1.8.1.
- Parameters
onlyConneg –
True
if only HTTP Content Negotiation is allowed;False
if HTTP parameters
are used. :type onlyConneg: bool
- setRequestMethod(method: str) None [source]
Set the internal method to use to perform the request for query or update operations, either URL-encoded (
URLENCODED
) or POST directly (POSTDIRECTLY
). Further details at query operation in SPARQL and update operation in SPARQL Update.- Parameters
method – Possible values are
URLENCODED
(URL-encoded) orPOSTDIRECTLY
(POST directly).
All other cases are ignored. :type method: string
- addDefaultGraph(uri: str) None [source]
Add a default graph URI.
Deprecated since version 1.6.0: Use
addParameter("default-graph-uri", uri)
instead of thismethod.
- Parameters
uri (string) – URI of the default graph.
- addNamedGraph(uri: str) None [source]
Add a named graph URI.
Deprecated since version 1.6.0: Use
addParameter("named-graph-uri", uri)
instead of thismethod.
- Parameters
uri (string) – URI of the named graph.
- addExtraURITag(key: str, value: str) None [source]
Some SPARQL endpoints require extra key value pairs. E.g., in virtuoso, one would add
should-sponge=soft
to the query forcing virtuoso to retrieve graphs that are not stored in its local database. Alias ofaddParameter()
method.Deprecated since version 1.6.0: Use
addParameter(key, value)
instead of this method- Parameters
key (string) – key of the query part.
value (string) – value of the query part.
- addCustomParameter(name: str, value: str) bool [source]
Method is kept for backwards compatibility. Historically, it “replaces” parameters instead of adding.
Deprecated since version 1.6.0: Use
addParameter(key, value)
instead of this method- Parameters
name (string) – name.
value (string) – value.
- Returns
Returns
True
if the adding has been accomplished, otherwiseFalse
.- Return type
- addParameter(name: str, value: str) bool [source]
Some SPARQL endpoints allow extra key value pairs. E.g., in virtuoso, one would add
should-sponge=soft
to the query forcing virtuoso to retrieve graphs that are not stored in its local database. If the parameterquery
is tried to be set, this intent is dismissed. Returns a boolean indicating if the set has been accomplished.- Parameters
name (string) – name.
value (string) – value.
- Returns
Returns
True
if the adding has been accomplished, otherwiseFalse
.- Return type
- addCustomHttpHeader(httpHeaderName: str, httpHeaderValue: str) None [source]
Add a custom HTTP header (this method can override all HTTP headers).
Important: Take into account that each previous value for the header field names
Content-Type
,User-Agent
,Accept
andAuthorization
would be overriden if the header field name is present as value of the parameterhttpHeaderName
.New in version 1.8.2.
- Parameters
httpHeaderName (string) – The header field name.
httpHeaderValue (string) – The header field value.
- clearCustomHttpHeader(httpHeaderName: str) bool [source]
Clear the values of a custom HTTP Header previously set. Returns a boolean indicating if the clearing has been accomplished.
New in version 1.8.2.
- Parameters
httpHeaderName (string) – HTTP header name.
- Returns
Returns
True
if the clearing has been accomplished, otherwiseFalse
.- Return type
- clearParameter(name: str) bool [source]
Clear the values of a concrete parameter. Returns a boolean indicating if the clearing has been accomplished.
- Parameters
name (string) – name
- Returns
Returns
True
if the clearing has been accomplished, otherwiseFalse
.- Return type
- setCredentials(user: Optional[str], passwd: Optional[str], realm: str = 'SPARQL') None [source]
Set the credentials for querying the current endpoint.
- Parameters
user (string) – username.
passwd (string) – password.
realm (string) – realm. Only used for
DIGEST
authentication. The default value isSPARQL
Changed in version 1.8.3: Added
realm
parameter.
- setHTTPAuth(auth: str) None [source]
Set the HTTP Authentication type. Possible values are
BASIC
orDIGEST
.- Parameters
auth (string) – auth type.
- Raises
TypeError – If the
auth
parameter is not an string.ValueError – If the
auth
parameter has not one of the valid values:BASIC
or
- setQuery(query: Union[str, bytes]) None [source]
Set the SPARQL query text.
Note
No check is done on the validity of the query (syntax or otherwise) by this module, except for testing the query type (SELECT, ASK, etc). Syntax and validity checking is done by the SPARQL service itself.
- Parameters
query (string) – query text.
- Raises
TypeError – If the
query
parameter is not an unicode-string or utf-8 encoded byte-string.
- _parseQueryType(query: str) Optional[str] [source]
Internal method for parsing the SPARQL query and return its type (ie,
SELECT
,ASK
, etc).Note
The method returns
SELECT
if nothing is specified. This is just to get all other methods running; in fact, this means that the query is erroneous, because the query must be, according to the SPARQL specification. The SPARQL endpoint should raise an exception (viaurllib
) for such syntax error.- Parameters
query (string) – query text.
- Returns
the type of SPARQL query (aka SPARQL query form).
- Return type
string
- setMethod(method: str) None [source]
Set the invocation method. By default, this is
GET
, but can be set toPOST
.
- setUseKeepAlive() None [source]
Make
urllib2
use keep-alive.- Raises
ImportError – when could not be imported
keepalive.HTTPHandler
.
- isSparqlUpdateRequest() bool [source]
Returns
True
if SPARQLWrapper is configured for executing SPARQL Update request.- Returns
Returns
True
if SPARQLWrapper is configured for executing SPARQL Update request.- Return type
- isSparqlQueryRequest() bool [source]
Returns
True
if SPARQLWrapper is configured for executing SPARQL Query request.- Returns
Returns
True
if SPARQLWrapper is configured for executing SPARQL Query request.- Return type
- _cleanComments(query: str) str [source]
Internal method for returning the query after all occurrence of singleline comments are removed (issues #32 and #77).
- Parameters
query (string) – The query.
- Returns
the query after all occurrence of singleline comments are removed.
- Return type
string
- _getRequestEncodedParameters(query: Optional[Tuple[str, str]] = None) str [source]
Internal method for getting the request encoded parameters.
- Parameters
query – a tuple of two items. The first item can be the string
query
(forSELECT
,DESCRIBE
,ASK
,CONSTRUCT
query) or the string
update
(for SPARQL Update queries, likeDELETE
orINSERT
). The second item of the tuple is the query string itself. :type query: tuple :return: the request encoded parameters. :rtype: string
- _getAcceptHeader() str [source]
Internal method for getting the HTTP Accept Header.
See also
`Hypertext Transfer Protocol – HTTP/1.1 - Header Field Definitions
<https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1>`_
- _createRequest() urllib.request.Request [source]
Internal method to create request according a HTTP method. Returns a
urllib2.Request
object of theurllib2
Python library- Raises
NotImplementedError – If the HTTP authentification method is not one of the valid values:
BASIC
or
DIGEST
. :return: request aurllib2.Request
object of theurllib2
Python library
- _query() Tuple[http.client.HTTPResponse, str] [source]
Internal method to execute the query. Returns the output of the
urllib2.urlopen()
method of theurllib2
Python library- Returns
tuples with the raw request plus the expected format.
- Raises
QueryBadFormed – If the HTTP return code is
400
.Unauthorized – If the HTTP return code is
401
.EndPointNotFound – If the HTTP return code is
404
.URITooLong – If the HTTP return code is
414
.EndPointInternalError – If the HTTP return code is
500
.urllib2.HTTPError – If the HTTP return code is different to
400
,401
,404
,414
,500
.
- query() SPARQLWrapper.Wrapper.QueryResult [source]
Execute the query. Exceptions can be raised if either the URI is wrong or the HTTP sends back an error (this is also the case when the query is syntactically incorrect, leading to an HTTP error sent back by the SPARQL endpoint). The usual urllib2 exceptions are raised, which therefore cover possible SPARQL errors, too.
Note that some combinations of return formats and query types may not make sense. For example, a SELECT query with Turtle response is meaningless (the output of a SELECT is not a Graph), or a CONSTRUCT query with JSON output may be a problem because, at the moment, there is no accepted JSON serialization of RDF (let alone one implemented by SPARQL endpoints). In such cases the returned media type of the result is unpredictable and may differ from one SPARQL endpoint implementation to the other. (Endpoints usually fall back to one of the “meaningful” formats, but it is up to the specific implementation to choose which one that is.)
- Returns
query result
- Return type
QueryResult
instance
- class SPARQLWrapper.Wrapper.QueryResult(result: Union[http.client.HTTPResponse, Tuple[http.client.HTTPResponse, str]])[source]
Wrapper around an a query result. Users should not create instances of this class, it is generated by a
SPARQLWrapper.query()
call. The results can be converted to various formats, or used directly.If used directly: the class gives access to the direct HTTP request results
response
obtained from the call tourllib.urlopen()
. It is a file-like object with two additional methods:geturl()
to return the URL of the resource retrievedinfo()
that returns the meta-information of the HTTP result as a dictionary-like object.
For convenience, these methods are also available on the
QueryResult
instance.The
__iter__()
andnext()
methods are also implemented (by mapping them toresponse
). This means that the common idiomfor l in obj : do_something_with_line(l)
would work, too.- Variables
response – the direct HTTP response; a file-like object, as return by the
urllib2.urlopen()
library call.requestedFormat – The requested format. The possible values are:
JSON
,XML
,RDFXML
,
TURTLE
,N3
,RDF
,CSV
,TSV
,JSONLD
. :type requestedFormat: string- __init__(result: Union[http.client.HTTPResponse, Tuple[http.client.HTTPResponse, str]]) None [source]
- Parameters
result – HTTP response stemming from a
SPARQLWrapper.query()
call, or a tuple with the expected
format: (response, format).
- geturl() str [source]
Return the URL of the original call.
- Returns
URL of the original call.
- Return type
string
- info() SPARQLWrapper.KeyCaseInsensitiveDict.KeyCaseInsensitiveDict[str] [source]
Return the meta-information of the HTTP result.
- Returns
meta-information of the HTTP result.
- Return type
- _convertJSON() Dict[Any, Any] [source]
Convert a JSON result into a Python dict. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
- _convertXML() xml.dom.minidom.Document [source]
Convert an XML result into a Python dom tree. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
xml.dom.minidom.Document
- _convertRDF() Graph [source]
Convert a RDF/XML result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
rdflib.graph.Graph
- _convertN3() bytes [source]
Convert a RDF Turtle/N3 result into a string. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
string
- _convertCSV() bytes [source]
Convert a CSV result into a string. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
string
- _convertTSV() bytes [source]
Convert a TSV result into a string. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result.
- Return type
string
- _convertJSONLD() Graph [source]
Convert a RDF JSON-LD result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method.
- Returns
converted result
- Return type
rdflib.graph.Graph
- convert() Optional[Union[bytes, str, Dict[Any, Any], Graph, xml.dom.minidom.Document]] [source]
Encode the return value depending on the return format:
in the case of
XML
, a DOM top element is returnedin the case of
JSON
, a json conversion will return a dictionaryin the case of
RDF/XML
, the value is converted via RDFLib into aRDFLib Graph
instancein the case of
JSON-LD
, the value is converted via RDFLib into aRDFLib Graph
instanceIn all other cases the input simply returned.
- Returns
the converted query result. See the conversion methods for more details.