Creating Templates for SPARQL Queries

The Template Parameter

SPARQL lets you query exactly the data you want. Using the integration of a template engine you can get the data you want in the way you want it.

You can for example tell the server to return the results in any custom format that fits your needs and makes it easier for you to integrate the results in your application (e.g. HTML snippet, a custom XML schema, etc.).

If you pass a Velocity template to the endpoint, the endpoint will try to format the query results using this template with its internal Velocity engine.

To use the SPARQL endpoint with a local template file for example the local.vm you call:

http://<server-URL>/PoolParty/sparql/<projectId>?query=<query>&template=local.vm&content-type=<content type produced by template>

The following rules apply:

  • The template file has to be located in the data/resourceRoot directory of the PoolParty installation.

    • The second possibility is to pass a URL (e.g. to a remote Velocity template (which doesn't have to be on the same server). The service will fetch the template before using it for formatting the results.

  • The content type produced by the template has to be specified.

Formatting the Result

From within your template code you can access the following variables:

  • $result - result rows

  • $bindings - binding names (variable names used in your query)

You can access the binding sets (similar to SQL result rows) from within the velocity template using the $result variable:

The actual binding values of a binding set can be accessed through the methods of java.util.Map and will return at least a RDF Value or more specific interfaces (see below).

The values are retrieved using the Map.get() method with the key you used in your SPARQL query as variable name.


If your SPARQL query starts like this:

SELECT ?myLabel WHERE { ... 

you can access the ?myLabel variable in the template by calling get("myLabel"):

#foreach($bindingset in $result)

If your variable is a RDF literal, you can access its data through the Literal interface:

  • Getting only the label as string:


  • Getting the language of the literal:



Get language uses optional values that where introduced with Java 8.

So to access the optional value you have to either use .get(), .orElse(). Details find in Oracle's documentation.

If your variable is a RDF resource (a IRI), you can access its data through the IRI interface:

  • Getting only the namespace:


  • Getting the local part of the URI:


  • Printing the entire URI as string:


If your variable is a blank node, your can access its data through the BNode interface:

  • Getting the blank node id:



You can test if the binding value is set with the following Velocity snippet:

#if ($bindingset.get("myLabel"))
// print value