sparql-client
THIS PACKAGE IS NO LONGER MAINTAINED
This package is currently unmaintained. If you would like to adopt this package, feel free to open an issue and get in touch with me!
A SPARQL 1.1 client for JavaScript.
const SparqlClient SPARQL = ;const client = 'http://dbpedia.org/sparql' ; { return client // Get the item we want. ;} ;
Table of Contents
- sparql-client
- Use
- License
Use
SPARQL
Tagged Template and Promises (ECMAScript 2015/ES 6)
Using You may use the SPARQL
template tag to interpolate variables into the
query. All values are automatically converted into their SPARQL literal
form, and any unsafe strings are escaped.
const SparqlClient = ;const SPARQL = SparqlClientSPARQL;const endpoint = 'http://dbpedia.org/sparql'; const city = 'Vienna'; // Get the leaderName(s) of the given cityconst query = SPARQL`PREFIX db: <http://dbpedia.org/resource/> PREFIX dbpedia: <http://dbpedia.org/property/> SELECT ?leaderName FROM <http://dbpedia.org> WHERE { dbpedia:leaderName ?leaderName } LIMIT 10`; const client = endpoint ; client ;
Results in:
head: link: vars: 'leaderName' results: distinct: false ordered: true bindings: leaderName: type: 'literal' 'xml:lang': 'en' value: 'Maria Vassilakou ,' leaderName: type: 'literal' 'xml:lang': 'en' value: 'Michael Häupl' leaderName: type: 'literal' 'xml:lang': 'en' value: 'Renate Brauner ;'
Using "Traditional" Node Callbacks
You are not forced to use promises; traditional (err, results)
callbacks work too. You may also use #bind()
to replace ?variables
in the query with sanitized values:
// Get the leaderName(s) of the 10 citiesvar query = "SELECT * FROM <http://dbpedia.org> WHERE { " + "?city <http://dbpedia.org/property/leaderName> ?leaderName " + "} LIMIT 10";var client = 'http://dbpedia.org/sparql' ; client ;
Registering URI Prefixes
Registering common prefixes
Often, SPARQL queries have many prefixes to register.
Common prefixes include:
You may register any of the above by passing them to
#registerCommon()
. This may be done per-query:
endpoint // Will have PREFIX xsd and sfn to this query only. ;
Or on the client, affecting every subsequent query:
client ;// Will add prefix rdfs and xsd.client;
Registering custom prefixes
Using #register()
on either the client or the query, you can register
any arbitrary prefix:
var client = endpoint // Can register one at a time: // Can register in bulk, as an object: // Can register a BASE (empty prefix): ;
Binding variables
#bind()
Explicitly, using It's inadvisable to concatenate strings in order to write a query,
especially if data is coming from untrusted sources. #bind()
allows
you to pass values to queries that will be converted into a safe SPARQL
term.
Say you have a statement like this:
var text = 'INSERT DATA {' + ' [] rdfs:label ?creature ;' + ' dbfr:paws ?paws ;' + ' dbfr:netWorth ?netWorth ;' + ' dbfr:weight ?weight ;' + ' dbfr:grumpy ?grumpy ;' + ' dbfr:derrivedFrom ?derrivedFrom .' + '}';
Each of the ?questionMarked
fields can be bound to JavaScript
values while querying using #bind()
:
client // Bind one at a time... // Use a third argument to provide options. // Or bind multiple values at once using an object: ;
SPARQL
template tag
Using the Any value that can be bound using #bind()
can equally be interpolated
using the SPARQL
template tag: URIs, strings, booleans, language
tagged strings, doubles, literals with custom typesanything! Note the
doubled curly-braces (${{value: ...}}
) when passing an object.
var text = SPARQL` INSERT DATA { ns:favouriteGame ; rdfs:label ; ns:prettyCheekyM8 ; rdfs:label ; ns:favoriteConstant ; ns:favoriteColor . }`;
Then text
would be the string:
INSERT DATA {
dc:eddieantonio ns:favouriteGame db:Super_Metroid ;
rdfs:label '@eddieantonio' ;
ns:prettyCheekyM8 true ;
rdfs:label 'エディ'@jp ;
ns:favoriteConstant 3.141592653589793e0 ;
ns:favoriteColor 'blue'^^ns:Color .
}
Updates
There's no need to specify anything special; LOAD
, CLEAR
, DROP
,
ADD
, MOVE
, COPY
, INSERT DATA
, and DELETE DATA
are
automatically requested as updates. Just write these statements like any
other:
endpoint ;
Specifying a different update endpoint
Some servers have different endpoints for queries and updates. Specify the alternate options when starting the client:
var client = 'http://example.org/query' updateEndpoint: 'http://example.org/update';
You may use the client subsequently:
// Will be sent to http://example.org/updateclient ; // Will be sent to http://example.org/queryclient ;
Overriding request defaults
You can override the request defaults by passing them in the options
object of the constructor. defaultParams
are the default parameters in
the request, and requestDefaults
are the default request options.
This distinction is a little confusing, so here are some examples:
For example, say you have a graph database that expects format: 'json'
as a param rather than the default format: 'application/sparql-results+json'
. You can override the default when
constructing your client like so:
var client = 'http://example.org/query' defaultParameters: format: 'json' ;
Similarly, let's say you want to specify your client's user agent
string. You can pass this, and other headers, as part of
a requestDefaults
option.
var client = 'http://example.org/query' requestDefaults: headers: 'Content-Type': 'application/x-www-form-urlencoded' 'Accept': 'application/sparql-results+json,application/json' 'User-Agent': 'My Totally Sweet App - 1.0' ;
Errors
If an error occurs, such as when submitting a query with a syntax error,
the first argument to execute()
will be an Error
object and have
the .httpStatus
attribute with the associated HTTP status code.
Usually this is 400
when there is a syntax error, or 500
when the
server refuses to process the request (such as when a timeout occurs).
This status code is defined by the particular SPARQL server used.
endpoint ;
This also works with promises:
endpoint ;
Result Formatting
We may want to execute the following query (to retrieve all books and their genres).
PREFIX dbpedia-owl: <http://dbpedia.org/owl/>SELECT ?book ?genre WHERE { ?book dbpedia-owl:literaryGenre ?genre}
The default formatting (when no options are provided) results, for the bindings (limited to two results in our example), in
book: type: 'uri' value: 'http://dbpedia.org/resource/A_Game_of_Thrones' genre: type: 'uri' value: 'http://dbpedia.org/resource/Fantasy' book: type: 'uri' value: 'http://dbpedia.org/resource/A_Game_of_Thrones' genre: type: 'uri' value: 'http://dbpedia.org/resource/Political_strategy'
Using the format option resource with the resource option set to book like so:
query;
Results in:
book: type: 'uri' value: 'http://dbpedia.org/resource/A_Game_of_Thrones' genre: type: 'uri' value: 'http://dbpedia.org/resource/Fantasy' type: 'uri' value: 'http://dbpedia.org/resource/Political_strategy'
This makes it easier to process the results later (in the callback), because all the genres are connected to one book (in one binding), and not spread over several bindings. Calling the execute function will look something like this
query;
License
The MIT License
Copyright © 2014 Thomas Fritz
Copyright © 2015, 2016 Eddie Antonio Santos
Contributors
- Martin Franke (@MtnFranke)
- Pieter Heyvaert (@PHaDventure)
- Eddie Antonio Santos (@eddieantonio)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.