Documentation

How to run BASIL, use its REST API, and use it as a Java library. This page refers to BASIL 1.0.0.

Concepts

An API in BASIL is a stored specification: a SPARQL endpoint and a SPARQL query (SELECT, CONSTRUCT, DESCRIBE, ASK, or Update). Input parameters are variables of the query that follow the BASIL variables convention. Each time the API is invoked, the parameters are bound, the query is executed on the endpoint, and the result is returned in the requested format.

An API can have views (templates or scripts that post-process the result), a name and description, and aliases (readable names used in place of the identifier). Every API is owned by the user who created it; reading is public, modifying requires authentication.

BASIL has no graphical interface: it is controlled through its HTTP API. All the examples below use curl.

Quick start

Requirements: Java 21 or later.

1. Download and start

# from https://github.com/basilapi/basil/releases/latest
java -jar -Dbasil.configurationFile=./basil-server.ini \
     -Dlog4j.configurationFile=./log4j2.xml \
     basil-server-1.0.0.jar -p 8080

2. Create a user

curl -X POST http://localhost:8080/basil/users \
  -H "Content-Type: application/json" \
  -d '{"username":"penelope","password":"mypassword","password2":"mypassword","email":"penelope@example.org"}'

3. Write a query (query.rq)

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label WHERE {
  ?_entity_iri rdfs:label ?label .
  FILTER(lang(?label) = "en")
}

4. Store it as an API

curl -u penelope:mypassword -X PUT http://localhost:8080/basil \
  -H "X-Basil-Endpoint: https://dbpedia.org/sparql" -T query.rq
{"message":"Created","location":"http://localhost:8080/basil/s50nwb9679dd"}

5. Use it

curl "http://localhost:8080/basil/s50nwb9679dd/api.json?entity=http://dbpedia.org/resource/Rome"

Running the server

The runnable jar basil-server-VERSION.jar is attached to each release, together with an example configuration basil-server.ini and a logging configuration log4j2.xml.

TDB2 backend (default)

APIs, views and users are stored in an Apache Jena TDB2 database. The example configuration:

basil = io.github.basilapi.basil.server.BasilConfiguration
# Namespace for the URIs of APIs, users and views stored by BASIL
basil.namespace = http://basilapi.github.io/data/ns/
# Folder where BASIL stores its data (created if missing)
basil.tdbLocation = ./basil-data

tdb2Realm = io.github.basilapi.basil.server.ShiroRealm
tdb2Realm.basilConfiguration = $basil
# ... Shiro settings, do not change

Change basil.tdbLocation to keep the data elsewhere. To back up an instance, stop the server and copy that folder.

MySQL backend (deprecated)

Earlier versions stored data in MySQL. This backend is still available but deprecated. Create a database with db.sql, prepare the connection parameters following basil.ini.default, and pass that file as basil.configurationFile.

Options

OptionMeaning
-p, --portPort to listen to (default 8080)
-h, --helpShow the help
-Dbasil.configurationFile=…Configuration file (required)
-Dlog4j.configurationFile=…Logging configuration
-Dbasil.sparql.serviceParameters=trueAllow parameters as SERVICE IRI (default: disabled). See Variables.

REST API

All paths are relative to the server root, e.g. http://localhost:8080. Operations that modify data require HTTP Basic authentication of the owner of the API. Every response about an API carries X-Basil-* headers with the links to its sub-resources.

ResourceMethodsPurpose
/basilGET, PUTList all APIs; create an API
/basil/usersPOSTCreate a user
/basil/users/{username}/apisGETAPIs created by a user
/basil/{id}GET, DELETERedirects (303) to /spec; delete the API and its sub-resources
/basil/{id}/apiGET, POSTInvoke the API
/basil/{id}/api.{ext}GET, POSTInvoke the API with a given format or view
/basil/{id}/specGET, PUTRead or replace the endpoint and query
/basil/{id}/explainGETThe query after parameter substitution
/basil/{id}/directGETRedirects (303) to the endpoint, with the rewritten query
/basil/{id}/cloneGETCreate a copy of the API, owned by the caller
/basil/{id}/view, /view/{name}GET, PUT, DELETEManage views
/basil/{id}/docsGET, PUT, DELETEName and description
/basil/{id}/aliasGET, PUT, DELETEAliases
/basil/{id}/authPUT, DELETECredentials for a protected endpoint
/basil/{id}/api-docsGETSwagger description (JSON, or HTML in a browser)

Users

curl -X POST http://localhost:8080/basil/users -H "Content-Type: application/json" -d @user.json
curl http://localhost:8080/basil/users/penelope/apis

Create an API

Send the query as the request body, and the endpoint in the X-Basil-Endpoint header (or in the endpoint query parameter):

curl -u penelope:mypassword -X PUT http://localhost:8080/basil \
  -H "X-Basil-Endpoint: https://dbpedia.org/sparql" -T query.rq

The response is 201 Created, with the location of the new API. A query that cannot be parsed, or that uses an undeclared prefix in a typed parameter, gives 400.

Invoke an API

curl "http://localhost:8080/basil/s50nwb9679dd/api?entity=http://dbpedia.org/resource/Rome"
curl -X POST http://localhost:8080/basil/s50nwb9679dd/api.json \
  -d "entity=http://dbpedia.org/resource/Rome"

Parameters are passed as query string or as form data. A missing mandatory parameter, or an invalid value, gives 400 with an explanation. The request parameters limit and offset set the LIMIT and OFFSET of the query. See Variables for how values are substituted.

Output formats

The format is chosen by content negotiation (Accept header) or by an extension of /api:

ExtensionMedia typeNotes
.jsonapplication/jsonPlain JSON, no namespaces
.xmlapplication/xmlPlain XML, no namespaces
.csv, .tsvtext/csv, text/tab-separated-values
.txttext/plainText table
.sparql-json, .sparql-xmlSPARQL results JSON / XMLStandard SPARQL result formats
.ttl, .nt, .nqTurtle, N-Triples, N-QuadsRDF, for CONSTRUCT and DESCRIBE
.rdf, .jsonld, .jrdfRDF/XML, JSON-LD, RDF/JSON
.{view}as declared by the viewSee Views

Manage an API

# read the specification
curl http://localhost:8080/basil/s50nwb9679dd/spec
# replace query and endpoint
curl -u penelope:mypassword -X PUT http://localhost:8080/basil/s50nwb9679dd/spec \
  -H "X-Basil-Endpoint: https://dbpedia.org/sparql" -T query.rq
# see the query that would be executed
curl "http://localhost:8080/basil/s50nwb9679dd/explain?entity=http://dbpedia.org/resource/Rome"
# delete the API
curl -u penelope:mypassword -X DELETE http://localhost:8080/basil/s50nwb9679dd

Views

A view transforms the result of an API, for example into an HTML snippet. Two engines are available: Mustache templates (Content-Type: template/mustache) and JavaScript (Content-Type: application/javascript, executed with Rhino). The type parameter declares the media type of the output.

In a Mustache template, the rows of the result are available as items, and each variable of the query by its name:

list.tmpl

<ul>
{{#items}}
  <li><a href="{{Concept}}">{{Concept}}</a> ({{Type}})</li>
{{/items}}
</ul>
# create or update the view "list"
curl -u penelope:mypassword -X PUT \
  "http://localhost:8080/basil/s50nwb9679dd/view/list?type=text/html" \
  -H "Content-Type: template/mustache" -T list.tmpl
# use it, as extension of /api
curl "http://localhost:8080/basil/s50nwb9679dd/api.list?entity=http://dbpedia.org/resource/Rome"
# list and delete
curl http://localhost:8080/basil/s50nwb9679dd/view
curl -u penelope:mypassword -X DELETE http://localhost:8080/basil/s50nwb9679dd/view/list

Name and description

echo "Labels of a DBpedia entity, in English" > doc.txt
curl -u penelope:mypassword -X PUT http://localhost:8080/basil/s50nwb9679dd/docs \
  -H "X-Basil-Name: Entity labels" -T doc.txt

The name and description are also used in the Swagger description at /api-docs.

Aliases

An alias is a readable name that can be used in place of the identifier, in any path. The body lists one alias per line.

printf "entity-labels\n" > alias.txt
curl -u penelope:mypassword -X PUT http://localhost:8080/basil/s50nwb9679dd/alias -T alias.txt
curl "http://localhost:8080/basil/entity-labels/api?entity=http://dbpedia.org/resource/Rome"

Protected endpoints

If the SPARQL endpoint requires authentication, store its credentials with the API. The body contains user and password, on two lines.

printf "user\npassword\n" | curl -u penelope:mypassword -X PUT \
  http://localhost:8080/basil/s50nwb9679dd/auth -T -

Java library

BASIL is a set of Maven modules published on Maven Central under the group io.github.basilapi. The sparql module is a small library, depending only on Apache Jena, that implements the variables convention: it reads the parameters declared in a query and binds values to them safely. It can be used without the server.

Maven

<dependency>
  <groupId>io.github.basilapi</groupId>
  <artifactId>sparql</artifactId>
  <version>1.0.0</version>
</dependency>

Gradle: implementation("io.github.basilapi:sparql:1.0.0"). Requires Java 21; brings Apache Jena 6.

Coming soon. The 1.0.0 artifacts are not yet available on Maven Central; they will be published soon. Meanwhile, build from source (mvn clean install) to install them in your local Maven repository, or use the previous release, 0.8.3, which follows the earlier variables convention.

Parameterised queries

import io.github.basilapi.basil.core.exceptions.SpecificationParsingException;
import io.github.basilapi.basil.sparql.QueryParameter;
import io.github.basilapi.basil.sparql.Specification;
import io.github.basilapi.basil.sparql.SpecificationFactory;
import io.github.basilapi.basil.sparql.VariablesBinder;
import org.apache.jena.query.Query;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.sparql.exec.http.QueryExecutionHTTP;

public class Example {
  public static void main(String[] args) throws SpecificationParsingException {
    String endpoint = "https://dbpedia.org/sparql";
    String sparql = """
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        SELECT ?label WHERE {
          ?_entity_iri rdfs:label ?label .
          FILTER(lang(?label) = ?_lang)
        } LIMIT ?_max_number
        """;

    // Parse the query and its parameters.
    // strict = true: fail on parameters that cannot be resolved (e.g. undeclared prefix)
    Specification spec = SpecificationFactory.create(endpoint, sparql, true);
    for (QueryParameter p : spec.getParameters()) {
      System.out.println(p.getName() + (p.isOptional() ? " (optional)" : "")
          + (p.isIri() ? " IRI" : p.isNumber() ? " number" : " literal"));
    }

    // Bind values: each is converted to the right RDF term.
    Query query = new VariablesBinder(spec)
        .bind("entity", "http://dbpedia.org/resource/Rome")
        .bind("lang", "en")
        .bind("max", "5")
        .toQuery();

    try (var qe = QueryExecutionHTTP.service(spec.getEndpoint()).query(query).build()) {
      ResultSetFormatter.out(qe.execSelect());
    }
  }
}

Main classes:

  • SpecificationFactory.create(endpoint, query[, strict]) — parses a query and returns a Specification. Throws UnknownQueryTypeException or, in strict mode, ParameterParsingException.
  • Specification — the endpoint, the query and its parameters: getParameters(), hasParameter(name), getVariableOfParameter(name), isUpdate().
  • QueryParameter — name and type of a parameter: isOptional(), isIri(), isNumber(), isLangedLiteral(), getLang(), isTypedLiteral(), getDatatype().
  • VariablesBinder — binds values: bind(name, value) uses the declared type; bindIri, bindNumber, bindPlainLiteral, bindLangedLiteral, bindTypedLiteral force one. toQuery() returns a Jena Query, toUpdate() an UpdateRequest. An invalid IRI or number throws IllegalArgumentException.

Values are always set as RDF terms through Jena's ParameterizedSparqlString, so they cannot change the structure of the query.

Modules

ArtifactContent
sparqlVariables convention: parsing parameters and binding values
coreApiManager, store and user interfaces, views (Mustache, Rhino), file store
renderingSerialisation of results in the supported formats
storeMySQL store (deprecated)
store-tdb2Apache Jena TDB2 store
restJAX-RS resources of the HTTP API
basil-serverRunnable server (Jetty 12)

Building from source

git clone https://github.com/basilapi/basil.git
cd basil
mvn clean install               # with integration tests (need internet)
mvn clean install -P '!it'      # skip integration tests
mvn clean install -DskipTests   # skip all tests

The runnable jar is server/target/basil-server-VERSION.jar. Requires Java 21 and Maven.