Difference between revisions of "REST"
|Line 281:||Line 281:|
Find Java examples for all methods here:
Find Java examples for all methods here:
[https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTGet.java GET], [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTPost.java
[https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTGet.java GET], [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTPost.java POST], [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTPut.java PUT], [https://github.com/BaseXdb/basex-examples/tree/master/src/main/java/org/basex/examples/rest/RESTDelete.java DELETE].
Revision as of 14:08, 17 February 2012
This page is part of the Developer Section. It describes how to use the REST API of BaseX.
BaseX offers a RESTful API for accessing distributed XML resources. 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.
The REST implementation has formerly been based on JAX-RX, a generic layer to provide unified access to XML databases and resources. With Version 7.0, it has been replaced with a native REST implementation that allows a closer integration with XQuery, WebDAV, and other features of BaseX. If you have worked with JAX-RX before, please take some time to understand the differences between the old and new API.
- 1 Starting HTTP Server
- 2 URL Architecture
- 3 Request Methods
- 4 Assigning Variables
- 5 User Management
- 6 Content Type
- 7 Usage Examples
- 8 Recent Changes
Starting HTTP Server
First of all, launch the BaseX HTTP Server, which will itself start an instance of the Jetty WebServer, which listens to the default port
8984 by default (check out the additional command-line options).
Most browsers can be used to get to know the REST API, and to directly display the results.
When requesting the first result, you will have to enter some database credentials
admin, see below).
Some alternatives for using REST are listed in the Usage Examples.
The root URL lists all available databases. The following examples assume that you have created a database instance from the factbook.xml document:
<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:
<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:
If a file with the mime type
application/xquery is addressed, it will be evaluated, and the result will be returned:
If a resource is not found, an HTTP response will be generated with
404 as status code.
GET and POST requests support the following operations:
Evaluates an XPath/XQuery expression. If a database or database path is specified in the URL, it is used as initial query context.
Runs a query file located on the server. The query directory is defined by the
Executes a database command.
This is the default operation for the GET operation (it is not possible to use this operation in a POST request). It returns a list of all databases, the resources of a database or the addressed resource. If a resource with content type
application/xqueryis addressed, it will be evaluated first, and the result will be returned.
Additionally, the following parameters can be applied to the operations:
External variables can be bound before a query is evaluated (see below for more).
contextparameter may be used to provide an initial XML context node.
- Options (Introduced with Version 7.1.1):
Specified Options are applied before the actual operation will be performed.
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.
wrapparameter encloses all query results with XML elements, using the
While Options can be specified for all operations, the remaining parameters will only make sense for Query and Run.
If the GET method is used, all query parameters are directly specified within the URL.
- The first example lists all resources found in the tmp path of the factbook database:
- The first example prints the city names from the factbook database and encloses all results with a
- In the next request,
US-ASCIIis chosen as output encoding, and the query
- The next URL turns on XML wrapping and lists all database users that are known to BaseX:
- The last example includes an to disallow XQuery 3.0 expressions:
The body of a POST request is interpreted as XML fragment, which specifies the operation to perform. The body must conform to a given REST POST Schema.
- The following query returns the first five city names of the factbook database:
<query xmlns="http://basex.org/rest"> <text><![CDATA[ (//city/name)[position() <= 5] ]]></text> </query>
- The second query returns the string lengths of all text nodes, which are found in the node that has been specified as initial context node:
<rest:query xmlns:rest="http://basex.org/rest"> <rest:text>for $i in .//text() return string-length($i)</rest:text> <rest:context> <xml> <text>Hello</text> <text>World</text> </xml> </rest:context> </rest:query>
- The following request returns the registered database users encoded in
<command xmlns="http://basex.org/rest"> <text>show users</text> <parameter name='encoding' value='ISO-8859-1'/> </command>
- This example creates a new database from the specified input and retains all whitespaces (works since Version 7.1.1):
<command xmlns="http://basex.org/rest"> <text>create db test http://files.basex.org/xml/xmark.xml</text> <option name='chop' value='false'/> </command>
- The last request runs a query
query.xqlocated in the directory specified by
<run xmlns="http://basex.org/rest"> <text>query.xq</text> </run>
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 XML input.
If a content type different to
application/xml is specified in the request header, the data will be stored as raw resource.
- 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 (works since Version 7.1.1):
- 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
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).
The DELETE method is used to delete databases or resources within a database.
- The factbook database is deleted:
- All resources of the XMark database are deleted that reside in the tmp path:
The HTTP status code
404 is returned if no database is specified.
200 (OK) will be sent in all other cases.
All query parameters that have not been processed before will be treated as variable assignments:
- The following request binds a single variable to the query to be processed:
- The following request assigns two variables to a server-side query file
mult.xqplaced in the database
(: XQuery file: mult.xq :) declare variable $a as xs:integer external; declare variable $b as xs:integer external; $a * $b
Variables can also be explicitly prefixed with a dollar sign (
$); this way, those variables can be bound as well that would otherwise be interpreted in a different way (e.g.:
run is used as operation, external variables can be specified via the
<query xmlns="http://basex.org/rest"> <text> declare variable $x as xs:integer external; declare variable $y as xs:integer external; $x * $y </text> <variable name="x" value="21"/> <variable name="y" value="2"/> </query>
By default, the HTTP server is started with no predefined user. Users and passwords can be sent via HTTP basic authentication with each HTTP request. As alternative, users and passwords can also be stored server-side in the "org.basex.user" and "org.basex.password" system properties before the HTTP server is started, or specified as command-line arguments.
With cURL, and most browsers, you can specify the user name and password with each HTTP request within the request string as plain text, using the format
USER:PASSWORD@URL. An example:
As the content type of a REST response cannot be dynamically determined in all cases, it can be manually adjusted by the user. The final content type of a REST response is chosen in several steps:
- By default, the content type of a response depends on the chosen operation:
- Query/Run ?
- Command ?
- Get ?
application/xml, or content type of the addressed resource
- Query/Run ?
- The default content type is overwritten if a serialization method is specified, either as query parameter or within the XQuery expression. The following methods are available:
- The content type is overwritten in any case if a specific media-type is chosen, again as query parameter or within the query.
The following three example requests will all return
<a/> as result and use
application/xml as content-type:
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
HttpURLConnection instance. The header contains the word
Basic, which specifies the authentication method, followed by the
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:
// The java URL connection to the resource. URL url = new URL("http://admin:admin@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();
curl -i "admin:admin@localhost:8984/rest/factbook?query=//city/name"
curl -i -X POST -H "Content-Type: application/xml" -d
curl -i -X POST -H "Content-Type: application/xml" -T query.xml "admin:admin@localhost:8984/rest/factbook"
curl -i -X PUT -T "etc/xml/factbook.xml" "admin:admin@localhost:8984/rest/factbook"
curl -i -X DELETE "admin:admin@localhost:8984/rest/factbook"
optionsparameter for specifying database options