REST

From BaseX Documentation

Jump to: navigation, search

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.

Contents

[edit] 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.

[edit] 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:

http://localhost:8984/rest
 
<rest:databases resources="1" xmlns:rest="http://basex.org/rest">
  <rest:database resources="1" size="1813599">factbook</rest:database>
</rest:databases>

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:

http://localhost:8984/rest/factbook
 
<rest:database name="factbook" resources="1" xmlns:rest="http://basex.org/rest">
  <rest:resource type="xml" content-type="application/xml" size="77192">factbook.xml</rest:resource>
</rest:database>

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

http://localhost:8984/rest/factbook/factbook.xml

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

[edit] Parameters

The following parameters can be applied to the operations:

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

[edit] Request

[edit] GET Method

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

Examples

[edit] 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:

With Version 9.0, the REST namespace of the root element has become optional. This means, for example, that existing command scripts can be sent to the server without any modifications:

<commands>
  <create-db name='db'/>
  <info-db/>
</commands>

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

Name Description
text Required; contains the query string, command string, or file to be run
parameter Serialization parameter (with @name and @value attributes)
option Database option (with @name and @value attributes)
variable Variable bindings
context Initial context item
Examples
<rest:query xmlns:rest="http://basex.org/rest">
  <rest:text><![CDATA[ (//city/name)[position() <= 5] ]]></rest:text>
</rest:query>
<query>
  <text>for $i in .//text() return string-length($i)</text>
  <context>
    <xml>
      <text>Hello</text>
      <text>World</text>
    </xml>
  </context>
</query>
<command>
  <text>show users</text>
  <parameter name='encoding' value='ISO-8859-1'/>
</command>
<command>
  <text>create db test http://files.basex.org/xml/xmark.xml</text>
  <option name='chop' value='false'/>
</command>
<run>
  <variable name='person' value='Johannes Müller'/>
  <text>find-person.xq</text>
</run>

[edit] PUT Method

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

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

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 400 (BAD REQUEST) error will be raised.

Examples

An HTTP response with status code 201 (CREATED) is sent back if the operation was successful. Otherwise, the server will reply with 404 (if a specified database was not found) or 400 (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.

[edit] DELETE Method

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

Example

The HTTP status code 404 is returned if no database is specified. 200 (OK) will be sent in all other cases.

[edit] Assigning Variables

[edit] GET Method

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

Example
(: XQuery file: mult.xq :)
declare variable $a as xs:integer external;
declare variable $b as xs:integer external;
<mult>{ $a * $b }</mult>

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

[edit] POST Method

If query or run is used as operation, external variables can be specified via the <variable/> element:

<query xmlns="http://basex.org/rest">
  <text><![CDATA[
    declare variable $x as xs:integer external;
    declare variable $y as xs:integer external;
    <mult>{ $a * $b }</mult>
  ]]></text>
  <variable name="a" value="21"/>
  <variable name="b" value="2"/>
</query>

[edit] Response

[edit] 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 media-type is supplied, it will be adopted as content-type.
  2. Otherwise, if the serialization parameter method is supplied, the content-type will be chosen according to the following mapping:
    • xml, adaptive, basexapplication/xml
    • xhtmltext/html
    • htmltext/html
    • texttext/plain
    • jsonapplication/json
  3. If no media-type or serialization method is supplied, the content type of a response depends on the chosen REST operation:
    • Query/Runapplication/xml
    • Commandtext/plain
    • Getapplication/xml, 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 <a/> with application/xml as content-type:

http://localhost:8984/rest?query=%3Ca/%3E
http://localhost:8984/rest?query=%3Ca/%3E&method=xml
http://localhost:8984/rest?query=%3Ca/%3E&media-type=application/xml

[edit] Usage Examples

[edit] Java

[edit] 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 HttpURLConnection instance. The header contains the word Basic, which specifies the authentication method, followed by the Base64-encoded USER:PASSWORD pair. As Java does not include a default conversion library for Base64 data, the internal BaseX class org.basex.util.Base64 can be used for that purpose:

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(); 
  }
}

[edit] 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):

// 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.

[edit] Command Line

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

GET
POST
PUT
DELETE

[edit] Changelog

Version 9.0
Version 8.1
Version 8.0
Version 7.9
Version 7.2
Version 7.1.1
Version 7.1
Version 7.0
Personal tools
Namespaces
Variants
Actions
Navigation
Print/export