#REDIRECT BaseX offers a RESTful API for accessing distributed XML resources.REST ([http://en.wikipedia.org/wiki/Representational_State_Transfer REpresentational State Transfer])facilitates a simple and fast access to databases through HTTP.The HTTP methods GET, PUT, DELETE, and POST can be applied tointeract with the database. The REST implementation has formerly beenbased on [http://jax-rx.sourceforge.net JAX-RX API], an interface layer toprovide unified access to XML databases and resources. With the releaseof Version 6.8 of BaseX, it will be reimplemented to allow for amuch closer integration with the XQuery processor of BaseX, WebDAV,and many other database features. ==Start BaseX server and client==First of all, please launch a '''HTTP Server''' instance of BaseX: double click on the '''BaseX HTTP''' icon, or run the <code>basexhttp</code> script. [[Startup|Follow this link]] for some more information (or check out the additional [[Startup Options#BaseX HTTP Server|command-line options]]). Some browsers, such as Opera, can be used to directly display the results of REST requests. Some more alternatives how to use REST are listed in the [[#Usage Examples|Usage Examples]] Paragraph. ==URL Architecture== The root URL lists all available databases. The following examples assume thatyou have created a database instance from the <b>[http://files.basex.org/xml/factbook.xml factbook.xml]</b> document: :<code>[http://admin:admin@localhost:8984/rest http://admin:admin@localhost:8984/rest]</code> <pre class="brush:xml"> <rest:databases resources="1" xmlns:rest="http://www.basex.org/rest"> <rest:database resources="1" size="1813599">factbook</rest:database></rest:databases></pre> 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 document is stored in the <b>factbook</b> database: :<code>[http://admin:admin@localhost:8984/rest/factbook http://admin:admin@localhost:8984/rest/factbook]</code> <pre class="brush:xml"> <rest:database name="factbook" resources="1" xmlns:rest="http://www.basex.org/rest"> <rest:resource type="xml" size="77192">factbook.xml</rest:resource></rest:database></pre> The contents of a database can be accessed by adding the <b>query</b> parameter to the path: :<code>[http://admin:admin@localhost:8984/rest/factbook?query http://admin:admin@localhost:8984/rest/factbook?query]</code> If a resource is not found, an HTTP response will be generated with <code>404</code> as status code. ===Query Parameters=== GET and POST requests can be extended with a number of parameters.Only one of the following '''operations''' can be specified: * '''query''':Evaluates an XPath/XQuery expression.:If a database or database path is specified in the URL, it is used as query context.* '''run''':Runs a query file located on the server.:The query directory is defined by the <code>[[Options#HTTPPATH|HTTPPATH]]</code> option.* '''command''':Executes a [[Commands|database command]]. The following parameters can be applied to the '''query''' and '''run''' operations:* '''wrap''':Wraps the results in XML elements (default: <code>no</code>).* Variables: all query parameters prefixed with a dollar sign (<code>$</code>) will be treated as external variables. The parameter name and value will be bound to the query before it is evaluated.* [[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. ==Request Methods== ===GET Requests=== Using GET, all query parameters can be directly specified within the URL.The following example prints the first five city names from the <b>factbook</b> database: :<code>[http://admin:admin@localhost:8984/rest/factbook?query=(//city/name)[position()<=5] http://admin:admin@localhost:8984/rest/factbook?query=(//city/name)[position()<=5]</code> The next request chooses <code>US-ASCII</code> as output encoding and opens the database within the XQuery expression: :<code>[http://admin:admin@localhost:8984/rest?query=distinct-values(doc('factbook')//religions)&encoding=US-ASCII http://admin:admin@localhost:8984/rest?query=distinct-values(doc('factbook')//religions)&encoding=US-ASCII]</code> The next URL turns on XML wrapping and lists all database users registered in BaseX: :<code>[http://admin:admin@localhost:8984/rest?command=show+users http://admin:admin@localhost:8984/rest?command=show+users]</code> ===POST Requests=== The POST method offers two different operations: ====Add New Resources==== By default, the HTTP request body will be added as new XML document to the specifieddatabase. For example, if a document is sent as body of the POST request to the URL <code>localhost:8984/rest/DB</code>, the document will be added to the <code>DB</code>database, and the 201 (Created) status code will be returned to confirm thateverything went alright. ====Execute Queries & Commands==== If <code>application/query+xml</code> is chosen as content type, the HTTP requestbody is interpreted as query. The body must conform to this [[XML Schema]]. The output of the following query equals the above [[REST#GET_Requests|GET request]]: <pre class="brush:xml"><query xmlns="http://www.basex.org/rest"> <text><![CDATA[ (//city/name)[position() <= 5] ]]></text></query></pre> The following POST request prints the registered database users in the specified <code>ISO-8859-1</code> encoding:<pre class="brush:xml"><command xmlns="http://www.basex.org/rest"> <text>show users</text> <parameter name='encoding' value='ISO-8859-1'/></command></pre> ===PUT Requests=== The PUT method can be used to create or update a database resource. ;Usage: Use <b>PUT</b> to send the URL and upload the input XML document. ;Example: A new database with the name <b>XMark</b> is created if the URL <code>localhost:8984/rest/XMark</code> is sent via <b>PUT</b>, followed by the input XML file in the HTTP body. The document will have the same name as the database. If the process was successful, a HTTP response with status code <code>201</code> (CREATED) is sent back.Otherwise, <code>404</code> will be sent. ===DELETE Requests=== The DELETE method can be applied to delete single resources.<br/> ;Usage: Use <b>DELETE</b> to send the URL pointing to the database or resource to be deleted. ;Example: The <b>factbook</b> database is deleted via the <b>DELETE</b> method and the URL <code>localhost:8984/rest/factbook</code>. If deletion was successful, the HTTP status code <code>200</code> (OK) will be sent.If not, <code>404</code> is returned. ==Assigning Variables== ====GET Requests====Query parameters prefixed with a dollar sign (<code>$</code>) will be handled as external variables: Query:<pre class="brush:xquery">declare variable $x as xs:integer external;declare variable $y as xs:integer external;$x * $y</pre> Variables:Set the values of the variables with: <code>&$x=21&$y=2</code> Complete request (compact notation, omitting the explicit variable declarations):<br/>:http://admin:admin@localhost:8984/rest?query=$x*$y&$x=21&$y=2 ====POST Requests==== Using POST, the <code><variable/>></code> element is used to bind external variables to a query: <pre class="brush:xml"><query xmlns="http://www.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></pre> ==Response Media Type== The media type of a REST response is chosen in several steps (<font color='gray'>to be revised for Version 6.8</font>): # The value of the [[#Query Parameters|wrap parameter]] determines the initial media type (default: <code>yes</code>):#* <code>yes</code> → <code>application/xml</code>#* <code>no</code> → <code>text/plain</code># If a valid value for "<code>method</code>" has been specified via the [[#Query Parameters|output parameter]], the media type is overwritten:#*<code>xml</code> → <code>application/xml</code>#*<code>xhtml</code> → <code>application/xhtml+xml</code>#*<code>html</code> → <code>text/html</code>#*<code>text</code> → <code>text/plain</code># Last, the type is overwritten if a valid value for "<code>media-type</code>" has been specified via the [[#Query Parameters|output parameter]]. To give two examples, the following URLs will all choose <code>text/plain</code> as response media type: :http://admin:admin@localhost:8984/rest?query=1&wrap=yes:http://admin:admin@localhost:8984/rest?query=1&method=xml:http://admin:admin@localhost:8984/rest?query=1&media-type=application/xml ==Usage Examples== ===Java===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: <pre class="brush:java">// 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"); // Print the HTTP response code. System.out.println("\n* HTTP response: " + conn.getResponseCode()); // Close connection. conn.disconnect(); </pre> Find Java examples for all methods here:[[RESTGET|GET]], [[RESTPOSTAdd|POST (Add)]], [[RESTPOSTQuery|POST (Query)]], [[RESTPUT|PUT]], [[RESTDELETE|DELETE]]. ===Command Line=== Next, tools such as the Linux command[http://curl.haxx.se/ cURL] exist toperform HTTP requests (try copy & paste): ;GET :<code>curl -i "admin:admin@localhost:8984/rest/factbook?query=//city/name&count=5"</code>;POST (Add):<code>curl -i -H "Content-Type: text/xml" -d "<HelloWorld/>" "admin:admin@localhost:8984/rest/collection"</code> ;POST (Query) :<code>curl -i -X POST -H "Content-Type: application/query+xml" -d <br/> "<query xmlns='http://www.basex.org/rest'><text>//city/name</text><parameter name='count' value='5'/></query>" <br/> "admin:admin@localhost:8984/rest/factbook"</code>:<code>curl -i -X POST -H "Content-Type: application/query+xml" -T query.xml "admin:admin@localhost:8984/rest/factbook"</code> ;PUT:<code>curl -i -X PUT -T "etc/xml/factbook.xml" "admin:admin@localhost:8984/rest/factbook"</code> ;DELETE:<code>curl -i -X DELETE "admin:admin@localhost:8984/rest/factbook"</code> ==User Management== By default, the HTTP server starts with no pre-defined user. Users and passwords can be sent via [http://en.wikipedia.org/wiki/Basic_access_authentication HTTP basic access authentication] with each HTTP request. As an alternative, users and passwords can also be specified as command-line arguments or via the "user.basex.user" and "user.basex.password" system properties before the HTTP server is started. With some browsers and with cURL, you can send specify the user name and password with each HTTP request within the request string as plain text, using the format <code>USER:PASSWORD@URL</code>. An example: ;GET :<code>curl -i "bob:alice@localhost:8984/rest/factbook"</code> ===Java Example=== Basic access authentication can be activated in Java by adding an authorization header to your <code>HttpURLConnection</code> instance. The header contains the word <code>Basic</code>, which specifies the authentication method, followed by the base64-encoded <code>USER:PASSWORD</code> pair. The BaseX internal <code>org.basex.util.Base64</code> can be used for encoding strings to the Base64 format: <pre class="brush:java">// 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 GET request. conn.setRequestMethod("GET"); // 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("\n* HTTP response: " + conn.getResponseCode()); // Close connection. conn.disconnect(); </pre> [[Category:Server]][[Category:REST]][[Category:Developer]]