REST

This page presents one of the Web Application services. It describes how to use the REST API of BaseX.

BaseX offers a RESTful API for accessing database resources via URLs. REST (REpresentational State Transfer) facilitates a simple and fast access to databases through HTTP. The HTTP methods GET, PUT, DELETE, and POST can be used to interact with the database.

=Usage=

By default, REST services are available at http://localhost:8984/rest/. If no default credentials are specified in the URL or when starting the web application, they will be requested by the client (see further).

A web browser can be used to perform simple GET-based REST requests and display the response. Some alternatives for using REST are listed in the Usage Examples.

=URL Architecture= The root URL lists all available databases. The following examples assume that you have created a database instance from the factbook.xml document:

  factbook 

The resources of a database can be listed by specifying the database, and potential sub directories, in the URL. In the given example, a single XML document is stored in the factbook database:



  factbook.xml  The contents of a database can be retrieved by directly addressing the resource:

If a resource is not found, an HTTP response will be generated with  as status code.

Parameters
The following parameters can be applied to the operations:


 * Variables: External variables can be bound before a query is evaluated (see below for more).
 * Context: The  parameter may be used to provide an initial XML context node.
 * Options: Specified Options are applied before the actual operation will be performed.
 * Serialization: All Serialization parameters known to BaseX can be specified as query parameters. Parameters that are specified within a query will be interpreted by the REST server before the output is generated.

While Options can be specified for all operations, the remaining parameters will only make sense for Query and Run.

=Request=

GET Method
If the GET method is used, all query parameters are directly specified within the URL. Additionally, the following operations can be specified:


 * query: Evaluate an XQuery expression. If a database or database path is specified in the URL, it is set as query context.
 * command: Execute a single database command.
 * run: Evaluate an XQuery file or command script located on the server. The file path is resolved against the directory specified by (before, it was resolved against ). Similar to query, a database or database path is set as context.


 * Examples


 * Lists all resources found in the tmp path of the factbook database:


 * Returns the number of documents in a database:


 * Serializes a document as JSONML:


 * is chosen as output encoding, and the query  is evaluated:


 * The next URL lists all database users that are known to BaseX:

POST Method
The body of a POST request is interpreted as XML fragment, which specifies the operation to perform. The name of the root element determines how the body will be evaluated:


 * commands: Run Command Script
 * query: Execute XQuery expression
 * run: Run server-side file (query or command script)
 * command: Execute single command

The root element may be bound to the optional REST namespace. Existing command scripts can be sent to the server without any modifications:

  
 * Create an empty database and return database information:

For the other commands, the following child elements are supported:


 * Examples

  <![CDATA[ (//city/name)[position <= 5] ]]></rest:text> </rest:query>
 * Return the first five city names of the factbook database:

<pre class="brush:xml"> for $i in .//text return string-length($i) Hello World
 * Return string lengths of all text nodes that are found in the node that has been specified as initial context node:

<pre class="brush:xml"> show users <parameter name='encoding' value='ISO-8859-1'/>
 * Return the registered database users encoded in :

<pre class="brush:xml"> create db test http://files.basex.org/xml/xmark.xml <option name='chop' value='false'/>
 * Create a new database from the specified input and preserve all whitespaces:

<pre class="brush:xml"> <variable name='person' value='Johannes Müller'/> find-person.xq
 * Bind value to the $person variable and run query, which must be located in the directory specified by :

PUT Method
The PUT method is used to create new databases, or to add or update existing database resources:


 * Create Database: A new database is created if the URL only specifies the name of a database. If the request body contains XML, a single document is created, adopting the name of the database.
 * Store Resource: A resource is added to the database if the URL contains a database path. If the addressed resource already exists, it is replaced by the new input.

There are two ways to store non-XML data in BaseX:


 * Store as Raw Data: If  is chosen as content-type, the input is added as Binary Data.
 * Convert to XML: Incoming data is converted to XML if a parser is available for the specified content-type. The following content types are supported:
 * : Stores JSON as XML.
 * : Stores plain text input as XML.
 * : Stores CSV text input as XML.
 * : Stores HTML input as XML.

Conversion can be influenced by specifying additional content-type parameters (see RESTXQ for more information).

If raw data is added and if no content type, or a wrong content, is specified, a  (BAD REQUEST) error will be raised.


 * Examples


 * A new database with the name XMark is created. If XML input is sent in the HTTP body, the resulting database resource will be called XMark.xml:
 * A new database is created, and no whitespaces will be removed from the passed on XML input:
 * The contents of the HTTP body will be taken as input for the document one.xml, which will be stored in the XMark database:

An HTTP response with status code  (CREATED) is sent back if the operation was successful. Otherwise, the server will reply with  (if a specified database was not found) or   (if the operation could not be completed).

Have a look at the usage examples for more detailed examples using Java and shell tools like cURL.

DELETE Method
The DELETE method is used to delete databases or resources within a database.

The HTTP status code  is returned if no database is specified. (OK) will be sent in all other cases.
 * Example
 * The factbook database is deleted:
 * All resources of the XMark database are deleted that reside in the tmp path:

=Assigning Variables=

GET Method
All query parameters that have not been processed before will be treated as variable assignments:


 * Example

<pre class="brush:xquery"> (: XQuery file: mult.xq :) declare variable $a as xs:integer external; declare variable $b as xs:integer external; { $a * $b }
 * The following request assigns two variables to a server-side query file  placed in the HTTP directory:

The dollar sign can be omitted as long as the variable name does not equal a parameter keyword (e.g.: ).

POST Method
If  or   is used as operation, external variables can be specified via the   element:

<pre class="brush:xml"> <query xmlns="http://basex.org/rest"> <![CDATA[ declare variable $x as xs:integer external; declare variable $y as xs:integer external; { $a * $b } ]]>

=Response=

Content Type
As the content type of a REST response cannot necessarily be dynamically determined, it can be enforced by the user. The final content type of a REST response is chosen as follows:


 * 1) If the serialization parameter   is supplied, it will be adopted as content-type.
 * 2) Otherwise, if the serialization parameter   is supplied, the content-type will be chosen according to the following mapping:
 * 3) If no media-type or serialization method is supplied, the content type of a response depends on the chosen REST operation:
 * 4) * Query/Run →
 * 5) * Command →
 * 6) * Get →, or content type of the addressed resource
 * 1) If no media-type or serialization method is supplied, the content type of a response depends on the chosen REST operation:
 * 2) * Query/Run →
 * 3) * Command →
 * 4) * Get →, or content type of the addressed resource
 * 1) * Get →, or content type of the addressed resource

Serialization parameters can either be supplied as query parameters or within the query.

The following three example requests all return  with   as content-type:



=Usage Examples=

Authentication
Most programming languages offer libraries to communicate with HTTP servers. The following example demonstrates how easy it is to perform a DELETE request with Java.

Basic access authentication can be activated in Java by adding an authorization header to the  instance. The header contains the word , which specifies the authentication method, followed by the Base64-encoded  pair. As Java does not include a default conversion library for Base64 data, the internal BaseX class can be used for that purpose:

<pre class="brush:java"> import java.net.*; import org.basex.util.*;

public final class RESTExample { public static void main(String[] args) throws Exception { // The java URL connection to the resource. URL url = new URL("http://localhost:8984/rest/factbook"); // Establish the connection to the URL. HttpURLConnection conn = (HttpURLConnection) url.openConnection; // Set as DELETE request. conn.setRequestMethod("DELETE"); // User and password. String user = "bob"; String pw ="alice"; // Encode user name and password pair with a base64 implementation. String encoded = Base64.encode(user + ":" + pw); // Basic access authentication header to connection request. conn.setRequestProperty("Authorization", "Basic " + encoded); // Print the HTTP response code. System.out.println("HTTP response: " + conn.getResponseCode); // Close connection. conn.disconnect; } }

Content-Types
The content-type of the input can easily be included, just add the following property to the connection (in this example we explicitly store the input file as raw):

<pre class="brush:java"> // store input as raw conn.setRequestProperty("Content-Type", "application/octet-stream");

See the PUT Requests section for a description of the possible content-types. Find Java examples for all methods here: GET, POST, PUT, DELETE.

Command Line
Tools such as the Linux commands Wget or cURL exist to perform HTTP requests (try copy &amp; paste):


 * GET
 * POST
 * PUT
 * DELETE
 * PUT
 * DELETE
 * DELETE
 * DELETE
 * DELETE

=Changelog=


 * Version 9.0
 * Added: Support for command scripts in the POST Method.
 * Updated: The REST namespace in the POST Method has become optional.


 * Version 8.1
 * Added: Support for input-specific content-type parameters
 * Updated: The run operation now resolves file paths against the option.


 * Version 8.0
 * Removed: wrap parameter


 * Version 7.9
 * Updated: Also evaluate command scripts via the  operation.


 * Version 7.2
 * Removed: Direct evaluation of adresses resources with  as content type


 * Version 7.1.1
 * Added: options parameter for specifying database options


 * Version 7.1
 * Added: PUT request: automatic conversion to XML if known content type is specified


 * Version 7.0
 * REST API introduced, replacing the old JAX-RX API