Changes

Jump to navigation Jump to search
1,649 bytes added ,  16:00, 17 April 2024
m
no edit summary
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 ([httphttps://en.wikipedia.org/wiki/Representational_State_Transfer REpresentational State Transfer])facilitates a simple and fast access to databases through HTTP. The HTTP methodsGET, PUT, DELETE, and POST can be used to interact with the database.
=Usage=
By default, REST services are available at {{Code|http://localhost:89848080/rest/}}. If no default credentials are specified in the URL or when starting the web application, they will be requested by the client ([[Web Application#User Management|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|Usage Examples]].
 
Since BaseX 10, results in the {{Code|rest}} namespace are returned unprefixed:
 
<pre lang="xml">
<!-- before -->
<rest:databases xmlns:rest="http://basex.org/rest"/>
 
<!-- BaseX 10 -->
<databases xmlns="http://basex.org/rest"/>
</pre>
=URL Architecture=
 
A request to the root URL returns all available databases:
The root URL lists all available databases. The following examples assume thatyou have created a database instance from the [:<code>http://files.basex.orglocalhost:8080/xmlrest</factbook.xml factbook.xml] document:code>
:<code>http://localhost:8984/rest</code> <pre classlang="brush:xml"> <rest:databases resources="1" xmlns:rest="http://basex.org/rest"> <rest:database resources="125742" size="181359943813599">factbookarticles</rest:database> ...</rest:databases></pre>
The resources of a database can be (directories, resource metadata) are listed by specifying the if a database, and potential sub directories, in the URL.In the given example, a single XML document an optional directory path is stored in the ''factbook'' databasespecified:
:<code>http://localhost:89848080/rest/factbookarticles</code>
<pre classlang="brush:xml"> <rest:database name="factbook" resources="1articles" xmlns:rest="http://basex.org/rest"> <rest:dir>binaries</dir> <resource type="xml" content-type="application/xml" size="77192">factbook1973-02-08-xltp325.xml</rest:resource> ...</rest:database></pre>  If the path to a single resource is specified, the resource itself will be returned:
The contents of a database can be retrieved by directly addressing the resource: :<code>http://localhost:89848080/rest/factbookarticles/factbook1973-02-08-xltp325.xml</code> If a resource is not found, an HTTP response will be generated with <code>404</code> as status code.
==Parameters==
While '''Options''' can be specified for all operations, the remaining parameters will only make sense for '''Query''' and '''Run'''.
=Request Methods=
==GET RequestsMethod==
If the GET method is used, all query parameters are directly specified within the URL.Additionally, the following '''operations''' can be specified:
* {{Code|query}}: Evaluate an XQuery expression. If a database or database path is specified in the URL, it is used set as initial query context.
* {{Code|command}}: Execute a single [[Commands|database command]].
* {{Code|run}}: Evaluate an XQuery file or command script located on the server. Since The file path is resolved against the {{Option|RESTPATH}} directory. Similar to {{VersionCode|8query}}, a database or database path is set as context.1With {{Announce|Version 11}}, if no file is found and if the file path is resolved against suffix has been omitted, the directory specified by <code>[[Options#WEBPATHextensions {{Code|RESTPATH]]</code> (before, it was resolved against <code>[[Options#WEBPATH.xq}} and {{Code|WEBPATH]]</code>).bxs}} are successively attached to the supplied filename.
; Examples
* Lists all resources found in the '''tmp''' path of the ''factbook'' database:<br/><code>http://localhost:89848080/rest/factbook/tmp</code>* Returns the number of documents in a database called ''test'':<br/><code>http://localhost:8080/rest/test?query=count(.)</code>* Serializes a document as JsonML:<br/><code>http://localhost:8080/rest/factbook/factbook.xml?method=json&json=format=jsonml</code>* <code>US-ASCII</code> is chosen as output encoding, and the query <code>eval.xq</code> is evaluated:<br/><code>http://localhost:8080/rest?run=eval&encoding=US-ASCII</code>* The next URL lists all database users who are known to BaseX:<br/><code>http://localhost:8080/rest?command=show+users</code>
* Serializes a document as JSONML:<br/><code>http://localhost:8984/rest/factbook/factbook.xml?method=json&json=formatPOST Method==jsonml</code>
* <code>US-ASCII</code> The body of a POST request is chosen interpreted as output encodingXML fragment, and which specifies the query <code>evaloperation to perform.xq</code> is The name of the root element determines how the body will be evaluated:<br/><code>http://localhost:8984/rest?run=eval.xq&encoding=US-ASCII</code>
* The next URL lists all database users that are known to BaseX{{Code|commands}}:<br/><code>httpRun [[Commands#Command Scripts|Command Script]]* {{Code|query}}://localhostExecute XQuery expression* {{Code|run}}:8984/rest?Run server-side file (query or command script)* {{Code|command}}: Execute single command=show+users</code>
==POST Requests==The root element may be bound to the optional REST namespace. Existing command scripts can be sent to the server without any modifications.
The body of a POST request is interpreted as XML fragmentFor the other commands, which specifies thefollowing child elements are supported: {| class="wikitable"|-! Name! Description|-operation | {{Code|text}}| Required; contains the query string, command string, or file to perform. The body must conform to a given [[REST: POST Schemabe run|-| {{Code|parameter}}| Serialization parameter (with {{Code|@name}} and {{Code|@value}} attributes)|-| {{Code|option}}| Database option (with {{Code|@name}} and {{Code|@value}} attributes)|-| {{Code|variable}}| Variable bindings|-| {{Code|context}}| Initial context item|XML Schema]].}
; Examples
* The following query returns Create an empty database and return database information:  <pre lang="xml"><commands> <create-db name='db'/> <info-db/></commands></pre> Return the first five city names of the <b>factbook</b> database:  <pre classlang="brush:xml"><query rest xmlns="http://basex.org/rest"> <textrest><![CDATA[ (//city/name)[position() <= 5] ]]></text></queryrest>
</pre>
* The second query returns the Return string lengths of all text nodes, which that are found in the node that has been specified as initial context node: <pre classlang="brush:xml"><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>
</pre>
* The following request returns Return the registered database users encoded in <code>ISO-8859-1</code>: <pre classlang="brush:xml"><command xmlns="http://basex.org/rest">
<text>show users</text>
<parameter name='encoding' value='ISO-8859-1'/>
</pre>
* This example creates Create a new database from the specified input and retains preserve all whitespaces: <pre classlang="brush:xml"><command xmlns="http://basex.org/rest">
<text>create db test http://files.basex.org/xml/xmark.xml</text>
<option name='chop' value='false'/>
</pre>
* The last request runs a Bind value to the {{Code|$person}} variable and run query <code>queryfind-person.xq</code> located in the directory specified by <code>[[Options#WEBPATH|WEBPATH]]</code>: <pre classlang="brush:xml"><run xmlns> <variable name="http://basex.org'person' value='Johannes Müller'/rest"> <text>queryfind-person.xq</text>
</run>
</pre>
==PUT RequestsMethod==
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:
* '''Store as rawRaw Data''':<br/> If <code>application/octet-stream</code> is chosen as content-type, the input data is added as raw[[Binary Data]].
* '''Convert to XML''':<br/> Incoming data is converted to XML if a parser is available for the specified content-type. The following content types are supported:
** <code>application/json</code>: Stores JSON as XML.
** <code>text/html</code>: Stores HTML input as XML.
Since {{Version|8.1}}, conversion Conversion can be influenced by specifying additional content-type parameters (see [[RESTXQ#Content Types|RESTXQ]] for more information).
If raw data is added and if no content type, or a wrong content, is specified, a <code>400</code> (BAD REQUEST) error will be raised.
; Examples
* A new database with the name <b>XMark</b> is created. If XML input is sent in the HTTP body, the resulting database resource will be called <b>XMark.xml</b>:<br/><code><nowiki>http://localhost:89848080/rest/XMark</nowiki></code>* A new database is created, and no whitespaces will be removed from the passed on XML input:<br/><code><nowiki>http://localhost:89848080/rest/XMark?chop=false</nowiki></code>* The contents of the HTTP body will be taken as input for the document <b>one.xml</b>, which will be stored in the <b>XMark</b> database:<br/><code><nowiki>http://localhost:89848080/rest/XMark/one.xml</nowiki></code> An HTTP response with status code <code>201</code> (CREATED) is sent back if the operation was successful. Otherwise, the server will reply with <code>404</code> (if a specified database was not found) or <code>400</code> (if the operation could not be completed).
An HTTP response with status code <code>201</code> (CREATED)is sent back if the operation was successful. Otherwise,the server will reply with <code>404</code> (if Take a specifieddatabase was not found) or <code>400</code> (if look at the operationcould not be completed)[[REST#Usage Examples|usage examples]] for more detailed examples using Java and shell tools like cURL.
Have a look at the [[REST#Usage Examples|usage examples]] for more detailed examples using Java and shell tools like cURL.==DELETE Method==
==DELETE Requests==
The DELETE method is used to delete databases or resources within a database.
; ExampleExamples* The <b>factbook</b> database is deleted:<br/><code><nowiki>http://localhost:89848080/rest/factbook</nowiki></code>* All resources of the <b>XMark</b> database are deleted that reside in the <b>tmp</b> path:<br/><code><nowiki>http://localhost:89848080/rest/XMark/tmp/</nowiki></code>
The HTTP status code <code>404</code> is returned if no database is specified.
=Assigning Variables=
==GET RequestsMethod==
All query Query parameters that have not been processed before otherwise will be treated as variable assignments:
; Example
* The following request assigns two variables to a server-side query file <code>mult.xq</code> placed in the HTTP directory:<br/><code>http://localhost:89848080/rest?run=mult.xqmultiply&$a=21&$b=2</code>assigns two variables and invokes <code>multiply.xq</code>:<pre classlang="brush:'xquery"'>(: XQuery file: multmultiply.xq :)
declare variable $a as xs:integer external;
declare variable $b as xs:integer external;
<mult>{ $a * $b }</mult>
</pre>
 
; Example
 
{{Announce|Updated with Version 11:}} Support for multiple values.
 
The request <code>http://localhost:8080/rest?run=sum&n=3&n=4&n=5</code> assigns multiple values to the same variable:
<pre lang='xquery'>
(: XQuery file: sum.xq :)
declare variable $n as xs:integer* external;
sum($n)
</pre>
The dollar sign can be omitted as long as the variable name does not equal a parameter keyword (e.g.: <code>method</code>).
==POST RequestsMethod==
If <code>query</code> or <code>run</code> is used as an operation, external variables can be specified via the <code><variable/></code> element:
<pre classlang="brush:xml">
<query xmlns="http://basex.org/rest">
<text><![CDATA[
declare variable $x a as xs:integer external; declare variable $y b as xs:integer external;
<mult>{ $a * $b }</mult>
]]></text>
</pre>
=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:
# If a the serialization parameter <code>[[Serialization|media-type]] </code> is supplied, either as [[#Parameters|query parameter]] or within the query, it will be used adopted as content-type.# Otherwise, if a the serialization parameter <code>[[Serialization|serialization method]] </code> is supplied (either as query parameter or within the query), the content-type will be chosen according to the following mapping:#* <code>xml</code>, <code>adaptive</code>, <code>basex</code> → <code>application/xml</code>
#* <code>xhtml</code> → <code>text/html</code>
#* <code>html</code> → <code>text/html</code>
#* <code>text</code> → <code>text/plain</code>
#* <code>raw</code> → <code>application/octet-stream</code>
#* <code>json</code> → <code>application/json</code>
# If no media-type or serialization method is supplied, the content type of a response depends on the chosen REST operation:
#* '''Command''' → <code>text/plain</code>
#* '''Get''' → <code>application/xml</code>, or content type of the addressed resource
 
Serialization parameters can either be supplied as [[#Parameters|query parameters]] or within the query.
The following three example requests all return <code>&lt;a/&gt;</code> with <code>application/xml</code> as content-type:
:<code>http://localhost:89848080/rest?query=%3Ca/%3E</code><br/><code>http://localhost:89848080/rest?query=%3Ca/%3E&method=xml</code><br/><code>http://localhost:89848080/rest?query=%3Ca/%3E&media-type=application/xml</code>
=Usage Examples=
<code>org.basex.util.Base64</code> can be used for that purpose:
<pre classlang="brush:java">
import java.net.*;
import org.basex.util.*;
public static void main(String[] args) throws Exception {
// The java URL connection to the resource.
URL url = new URL("http://localhost:89848080/rest/factbook");
// Establish the connection to the URL.
String user = "bob";
String pw ="alice";
// Encode user name username and password pair with a base64 implementation.
String encoded = Base64.encode(user + ":" + pw);
// Basic access authentication header to connection request.
the connection (in this example we explicitly store the input file as raw):
<pre classlang="brush:java">
// store input as raw
conn.setRequestProperty("Content-Type", "application/octet-stream");
==Command Line==
Tools such as the Linux commands [httphttps://www.gnu.org/s/wget/ Wget] or [http://curl.haxx.se/ cURL] exist to
perform HTTP requests (try copy &amp; paste):
;GET
* <code><nowiki>curl -i "http://localhost:89848080/rest/factbook?query=//city/name"</nowiki></code>
;POST
* <code><nowiki>curl -i -X POST -H "Content-Type: application/xml" -d "&lt;query xmlns='http://basex.org/rest'&gt;&lt;text&gt;//city/name&lt;/text&gt;&lt;/query&gt;" "http://localhost:89848080/rest/factbook"</nowiki></code>* <code><nowiki>curl -i -X POST -H "Content-Type: application/xml" -T query.xml "http://localhost:89848080/rest/factbook"</nowiki></code>
;PUT
* <code><nowiki>curl -i -X PUT -T "etc/xml/factbook.xml" "http://localhost:89848080/rest/factbook"</nowiki></code>* <code><nowiki>curl -i -X PUT -H "Content-Type: application/json" -T "plain.json" "http://localhost:89848080/rest/plain"</nowiki></code>
;DELETE
* <code><nowiki>curl -i -X DELETE "http://admin:admin@localhost:89848080/rest/factbook"</nowiki></code>
=Changelog=
 
;Version 11.0
* Updated: [[#Request|Request]]: The extensions {{Code|.xq}} and {{Code|.bxs}} are successively attached to the supplied filename.
* Updated: [[#Assigning Variables|Assigning Variables]]: Support for multiple values.
 
;Version 10.0
* Updated: Results in the {{Code|rest}} namespace will be returned unprefixed.
* Updated: {{Code|dir}} elements are returned when listing the contents of a database.
 
;Version 9.0
* Added: Support for command scripts in the [[#POST Method|POST Method]].
* Updated: The REST namespace in the [[#POST Method|POST Method]] has become optional.
;Version 8.1
* Added: support Support for input-specific content-type parameters* Updated: the The [[#GET RequestsMethod|run operation]] now resolves file paths against the [[Options#RESTPATH{{Option|RESTPATH]] }} option.
;Version 8.0
;Version 7.9
* Updated: Also evaluate command scripts via the <code>[[#GET RequestsMethod|run]]</code> operation.
;Version 7.2
* Removed: direct Direct evaluation of adresses resources with <code>application/xquery</code> as content type
;Version 7.1.1
;Version 7.0
* REST API introduced, replacing the old JAX-RX API
 
[[Category:Server]]
[[Category:HTTP]]
[[Category:Developer]]
administrator, editor
31

edits

Navigation menu