Difference between revisions of "RESTXQ"

From BaseX Documentation
Jump to navigation Jump to search
Line 41: Line 41:
 
A first RESTXQ function is shown below:
 
A first RESTXQ function is shown below:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
module namespace page = 'http://basex.org/examples/web-page';
 
module namespace page = 'http://basex.org/examples/web-page';
  
Line 48: Line 48:
 
     <title>Hello { $who }!</title>
 
     <title>Hello { $who }!</title>
 
   </response>
 
   </response>
};</pre>
+
};</syntaxhighlight>
  
 
If the URI http://localhost:8984/hello/World is accessed, the result will be:
 
If the URI http://localhost:8984/hello/World is accessed, the result will be:
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
&lt;response&gt;
 
&lt;response&gt;
 
   &lt;title&gt;Hello World!&lt;/title&gt;
 
   &lt;title&gt;Hello World!&lt;/title&gt;
 
&lt;/response&gt;
 
&lt;/response&gt;
</pre>
+
</syntaxhighlight>
  
 
The next function demonstrates a POST request:
 
The next function demonstrates a POST request:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/form")
 
   %rest:path("/form")
Line 75: Line 75:
 
   &lt;/response&gt;
 
   &lt;/response&gt;
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...
 
If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...
  
<pre class="brush:shell">
+
<syntaxhighlight lang="shell">
 
curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form
 
curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form
</pre>
+
</syntaxhighlight>
  
 
...you will receive something similar to the following result:
 
...you will receive something similar to the following result:
  
<pre class="brush:shell">
+
<syntaxhighlight lang="shell">
 
HTTP/1.1 200 OK
 
HTTP/1.1 200 OK
 
Content-Type: application/xml; charset=UTF-8
 
Content-Type: application/xml; charset=UTF-8
 
Content-Length: 107
 
Content-Length: 107
 
Server: Jetty(8.1.11.v20130520)
 
Server: Jetty(8.1.11.v20130520)
</pre>
+
</syntaxhighlight>
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
<response type="form">
 
<response type="form">
 
   <message>'CONTENT'</message>
 
   <message>'CONTENT'</message>
 
   <user-agent>curl/7.31.0</user-agent>
 
   <user-agent>curl/7.31.0</user-agent>
 
</response>
 
</response>
</pre>
+
</syntaxhighlight>
  
 
=Request=
 
=Request=
Line 113: Line 113:
 
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:
 
The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for <code>$variable</code> will be cast to an <code>xs:integer</code> before being bound:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %rest:path("/a/path/{$with}/some/{$variable}")
 
declare %rest:path("/a/path/{$with}/some/{$variable}")
 
   function page:test($with, $variable as xs:integer) { ... };
 
   function page:test($with, $variable as xs:integer) { ... };
</pre>
+
</syntaxhighlight>
 
<!-- TODO how matching works -->
 
<!-- TODO how matching works -->
  
 
Variables can be enhanced by regular expressions:
 
Variables can be enhanced by regular expressions:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
(: Matches all paths with "app" as first, a number as second, and "order" as third segment :)
 
(: Matches all paths with "app" as first, a number as second, and "order" as third segment :)
 
declare %rest:path("app/{$code=[0-9]+}/order")
 
declare %rest:path("app/{$code=[0-9]+}/order")
Line 129: Line 129:
 
declare %rest:path("app/{$path=.+}")
 
declare %rest:path("app/{$path=.+}")
 
   function page:others($path) { ... };
 
   function page:others($path) { ... };
</pre>
+
</syntaxhighlight>
 
<!-- TODO how matching works -->
 
<!-- TODO how matching works -->
  
Line 139: Line 139:
  
 
* '''HTTP Content Types''': A function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given content types. Example:
 
* '''HTTP Content Types''': A function will only be invoked if the HTTP {{Code|Content-Type}} header of the request matches one of the given content types. Example:
<pre class="brush:xquery">%rest:consumes("application/xml", "text/xml")</pre>
+
<syntaxhighlight lang="xquery">%rest:consumes("application/xml", "text/xml")</syntaxhighlight>
 
* '''HTTP Accept''': A function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined content types. Example:
 
* '''HTTP Accept''': A function will only be invoked if the HTTP {{Code|Accept}} header of the request matches one of the defined content types. Example:
<pre class="brush:xquery">%rest:produces("application/atom+xml")</pre>
+
<syntaxhighlight lang="xquery">%rest:produces("application/atom+xml")</syntaxhighlight>
  
 
By default, both content types are {{Code|*/*}}. Quality factors supplied by a client will also be considered in the path selection process. If a client supplies the following accept header…
 
By default, both content types are {{Code|*/*}}. Quality factors supplied by a client will also be considered in the path selection process. If a client supplies the following accept header…
Line 153: Line 153:
 
Server-side quality factors are supported as well: If multiple function candidates are left over after the above steps, the <code>qs</code> parameter will be considered. The function with the highest quality factor will be favored:
 
Server-side quality factors are supported as well: If multiple function candidates are left over after the above steps, the <code>qs</code> parameter will be considered. The function with the highest quality factor will be favored:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
%rest:produces("text/html;qs=1")
 
%rest:produces("text/html;qs=1")
 
%rest:produces("*/*;qs=0.8")
 
%rest:produces("*/*;qs=0.8")
</pre>
+
</syntaxhighlight>
  
 
Note that the annotation will ''not'' affect the content type of the actual response. You will need to supply an additional <code>[[#Output|%output:media-type]]</code> annotation.
 
Note that the annotation will ''not'' affect the content type of the actual response. You will need to supply an additional <code>[[#Output|%output:media-type]]</code> annotation.
Line 168: Line 168:
 
The following function will be called if GET or POST is used as request method:
 
The following function will be called if GET or POST is used as request method:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %rest:GET %rest:POST %rest:path("/post")
 
declare %rest:GET %rest:POST %rest:path("/post")
 
   function page:post() { "This was a GET or POST request" };
 
   function page:post() { "This was a GET or POST request" };
</pre>
+
</syntaxhighlight>
  
 
The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a [[#Parameters|function argument]]. Once again, the target variable must be embraced by curly brackets:
 
The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a [[#Parameters|function argument]]. Once again, the target variable must be embraced by curly brackets:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %rest:PUT("{$body}") %rest:path("/put")
 
declare %rest:PUT("{$body}") %rest:path("/put")
 
   function page:put($body) { "Request body: " || $body };
 
   function page:put($body) { "Request body: " || $body };
</pre>
+
</syntaxhighlight>
  
 
====Custom Methods====
 
====Custom Methods====
Line 184: Line 184:
 
Custom HTTP methods can be specified with the {{Code|%rest:method}} annotation. An optional body variable can be supplied as second argument:
 
Custom HTTP methods can be specified with the {{Code|%rest:method}} annotation. An optional body variable can be supplied as second argument:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("binary-size")
 
   %rest:path("binary-size")
Line 194: Line 194:
 
   "Size of body: " || bin:length($body)
 
   "Size of body: " || bin:length($body)
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
{{Mark|Updated with Version 9.3:}}
 
{{Mark|Updated with Version 9.3:}}
Line 249: Line 249:
 
Conversion options for {{Option|JSON}}, {{Option|CSV}} and {{Option|HTML}} can also be specified via annotations with the <code>input</code> prefix. The following function interprets the input as text with the CP1252 encoding and treats the first line as header:
 
Conversion options for {{Option|JSON}}, {{Option|CSV}} and {{Option|HTML}} can also be specified via annotations with the <code>input</code> prefix. The following function interprets the input as text with the CP1252 encoding and treats the first line as header:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/store.csv")
 
   %rest:path("/store.csv")
Line 257: Line 257:
 
   "Number of rows: " || count($csv/csv/record)
 
   "Number of rows: " || count($csv/csv/record)
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===Multipart Types===
 
===Multipart Types===
Line 266: Line 266:
 
A function that is capable of handling multipart types is identical to other RESTXQ functions:
 
A function that is capable of handling multipart types is identical to other RESTXQ functions:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/multipart")
 
   %rest:path("/multipart")
Line 274: Line 274:
 
   "Number of items: " || count($data)
 
   "Number of items: " || count($data)
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
==Parameters==
 
==Parameters==
Line 284: Line 284:
 
The value of the ''first parameter'', if found in the [[Request_Module#Conventions|query component]], will be assigned to the variable specified as ''second parameter''. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):
 
The value of the ''first parameter'', if found in the [[Request_Module#Conventions|query component]], will be assigned to the variable specified as ''second parameter''. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/params")
 
   %rest:path("/params")
Line 292: Line 292:
 
   <result id="{ $id }" sum="{ sum($add) }"/>
 
   <result id="{ $id }" sum="{ sum($add) }"/>
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===HTML Form Fields===
 
===HTML Form Fields===
Line 298: Line 298:
 
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are the result of HTML forms submitted with the content type <code>application/x-www-form-urlencoded</code>.
 
Form parameters are specified the same way as [[#Query Parameters|query parameters]]. Their values are the result of HTML forms submitted with the content type <code>application/x-www-form-urlencoded</code>.
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
%rest:form-param("parameter", "{$value}", "default")
 
%rest:form-param("parameter", "{$value}", "default")
</pre>
+
</syntaxhighlight>
  
 
====File Uploads====
 
====File Uploads====
Line 306: Line 306:
 
Files can be uploaded to the server by using the content type {{Code|multipart/form-data}} (the HTML5 {{Code|multiple}} attribute enables the upload of multiple files):
 
Files can be uploaded to the server by using the content type {{Code|multipart/form-data}} (the HTML5 {{Code|multiple}} attribute enables the upload of multiple files):
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
<form action="/upload" method="POST" enctype="multipart/form-data">
 
<form action="/upload" method="POST" enctype="multipart/form-data">
 
   <input type="file" name="files"  multiple="multiple"/>
 
   <input type="file" name="files"  multiple="multiple"/>
 
   <input type="submit"/>
 
   <input type="submit"/>
 
</form>
 
</form>
</pre>
+
</syntaxhighlight>
  
 
The file contents are placed in a [[Map Module|map]], with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:
 
The file contents are placed in a [[Map Module|map]], with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:POST
 
   %rest:POST
Line 329: Line 329:
 
   )
 
   )
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===HTTP Headers===
 
===HTTP Headers===
Line 335: Line 335:
 
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:
 
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
%rest:header-param("User-Agent", "{$user-agent}")
 
%rest:header-param("User-Agent", "{$user-agent}")
 
%rest:header-param("Referer", "{$referer}", "none")
 
%rest:header-param("Referer", "{$referer}", "none")
</pre>
+
</syntaxhighlight>
  
 
===Cookies===
 
===Cookies===
Line 344: Line 344:
 
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:
 
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
%rest:cookie-param("username", "{$user}")
 
%rest:cookie-param("username", "{$user}")
 
%rest:cookie-param("authentication", "{$auth}", "no_auth")
 
%rest:cookie-param("authentication", "{$auth}", "no_auth")
</pre>
+
</syntaxhighlight>
  
 
==Query Execution==
 
==Query Execution==
Line 355: Line 355:
 
With the <code>%rest:single</code> annotation, it can be enforced that only one instance of a function will be executed for the same client. If the same function will be called for the second time, the already running query will be stopped, and the HTTP error code {{Code|460}} will be returned instead:
 
With the <code>%rest:single</code> annotation, it can be enforced that only one instance of a function will be executed for the same client. If the same function will be called for the second time, the already running query will be stopped, and the HTTP error code {{Code|460}} will be returned instead:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
(: If fast enough, returns the result. Otherwise, if called again, raises 460 :)
 
(: If fast enough, returns the result. Otherwise, if called again, raises 460 :)
 
declare
 
declare
Line 367: Line 367:
 
   }</ul>
 
   }</ul>
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
By specifying a string along with the annotation, functions can be bundled together, and one request can be canceled by calling another one.
 
By specifying a string along with the annotation, functions can be bundled together, and one request can be canceled by calling another one.
Line 373: Line 373:
 
This is shown by another example, in which the first function can be interrupted by the second one. If you call both functions in separate browser tabs, you will note that the first tab will return <code>460</code>, and the second one will return <xml>stopped</xml>.
 
This is shown by another example, in which the first function can be interrupted by the second one. If you call both functions in separate browser tabs, you will note that the first tab will return <code>460</code>, and the second one will return <xml>stopped</xml>.
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare  
 
declare  
 
   %rest:path("/compute")
 
   %rest:path("/compute")
Line 387: Line 387:
 
   <xml>stopped</xml>
 
   <xml>stopped</xml>
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
The following things should be noted:
 
The following things should be noted:
Line 402: Line 402:
 
Custom responses can be generated in XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and optional child nodes that will be serialized as usual. A function that yields a response on an unknown resource may look as follows:
 
Custom responses can be generated in XQuery by returning an <code>rest:response</code> element, an <code>http:response</code> child node that matches the syntax of the [http://expath.org/spec/http-client EXPath HTTP Client Module] specification, and optional child nodes that will be serialized as usual. A function that yields a response on an unknown resource may look as follows:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %output:method("text") %rest:path("") function page:error404() {
 
declare %output:method("text") %rest:path("") function page:error404() {
 
   <rest:response>
 
   <rest:response>
Line 412: Line 412:
 
   "The requested resource is not available."
 
   "The requested resource is not available."
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
==Forwards and Redirects==
 
==Forwards and Redirects==
Line 422: Line 422:
 
The server can invite the client (e.g., the web browser) to make a second request to another URL by sending a 302 response:
 
The server can invite the client (e.g., the web browser) to make a second request to another URL by sending a 302 response:
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
<rest:response>
 
<rest:response>
 
   <http:response status="302">
 
   <http:response status="302">
Line 428: Line 428:
 
   </http:response>
 
   </http:response>
 
</rest:response>
 
</rest:response>
</pre>
+
</syntaxhighlight>
  
 
The convenience function {{Function|Web|web:redirect}} can be called to create such a response.
 
The convenience function {{Function|Web|web:redirect}} can be called to create such a response.
Line 434: Line 434:
 
In the XQuery context, redirects are particularly helpful if [[XQuery Update|Updates]] are performed. An updating request may send a redirect to a second function that generates a success message, or evaluates an updated database:
 
In the XQuery context, redirects are particularly helpful if [[XQuery Update|Updates]] are performed. An updating request may send a redirect to a second function that generates a success message, or evaluates an updated database:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %updating %rest:path('/app/init') function local:create() {
 
declare %updating %rest:path('/app/init') function local:create() {
 
   db:create('app', <root/>, 'root.xml'),
 
   db:create('app', <root/>, 'root.xml'),
Line 443: Line 443:
 
   'Stored documents: ' || count(db:open('app'))
 
   'Stored documents: ' || count(db:open('app'))
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===Forwards===
 
===Forwards===
Line 449: Line 449:
 
A server-side redirect is called forwarding. It reduces traffic among client and server, and the forwarding will not change the URL seen from the client’s perspective:
 
A server-side redirect is called forwarding. It reduces traffic among client and server, and the forwarding will not change the URL seen from the client’s perspective:
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
<rest:forward>new-location</rest:forward>
 
<rest:forward>new-location</rest:forward>
</pre>
+
</syntaxhighlight>
  
 
The fragment can also be created with the convenience function {{Function|Web|web:forward}}.
 
The fragment can also be created with the convenience function {{Function|Web|web:forward}}.
Line 463: Line 463:
 
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:
 
In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the {{Code|media-type}} parameter:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare option output:media-type 'text/plain';
 
declare option output:media-type 'text/plain';
  
Line 469: Line 469:
 
   'Keep it simple, stupid'
 
   'Keep it simple, stupid'
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===Annotations===
 
===Annotations===
Line 475: Line 475:
 
Global serialization parameters can be overwritten via <code>%output</code> annotations. The following example serializes XML nodes as JSON, using the [[JSON Module|JsonML]] format:
 
Global serialization parameters can be overwritten via <code>%output</code> annotations. The following example serializes XML nodes as JSON, using the [[JSON Module|JsonML]] format:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("cities")
 
   %rest:path("cities")
Line 485: Line 485:
 
   }
 
   }
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
The next function, when called, generates XHTML headers, and {{Code|text/html}} will be set as content type:
 
The next function, when called, generates XHTML headers, and {{Code|text/html}} will be set as content type:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("done")
 
   %rest:path("done")
Line 501: Line 501:
 
   </html>
 
   </html>
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
===Response Element===
 
===Response Element===
Line 507: Line 507:
 
Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:
 
Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %rest:path("version3") function page:version3() {
 
declare %rest:path("version3") function page:version3() {
 
   <rest:response>
 
   <rest:response>
Line 516: Line 516:
 
   'Not that simple anymore'
 
   'Not that simple anymore'
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
=Error Handling=
 
=Error Handling=
Line 528: Line 528:
 
With the {{Function|Web|web:error}} function, you can abort query evaluation and enforce a premature HTTP response with the supplied status code and response body text:
 
With the {{Function|Web|web:error}} function, you can abort query evaluation and enforce a premature HTTP response with the supplied status code and response body text:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/teapot")
 
   %rest:path("/teapot")
Line 534: Line 534:
 
   web:error(418, "I'm a pretty teapot")
 
   web:error(418, "I'm a pretty teapot")
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
The XQuery error code and the stack trace will be suppressed in the body of the HTTP response.
 
The XQuery error code and the stack trace will be suppressed in the body of the HTTP response.
Line 577: Line 577:
 
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:
 
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare
 
declare
 
   %rest:path("/check/{$user}")
 
   %rest:path("/check/{$user}")
Line 592: Line 592:
 
   'User "' || $user || '" is unknown'
 
   'User "' || $user || '" is unknown'
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
==Catch HTTP Errors==
 
==Catch HTTP Errors==
Line 598: Line 598:
 
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):
 
Errors that occur outside RESTXQ can be caught by adding {{Code|error-page}} elements with an error code and a target location to the {{Code|web.xml}} configuration file (find more details in the [http://www.eclipse.org/jetty/documentation/current/custom-error-pages.html Jetty Documentation]):
  
<pre class="brush:xml">
+
<syntaxhighlight lang="xml">
 
<error-page>
 
<error-page>
 
   <error-code>404</error-code>
 
   <error-code>404</error-code>
 
   <location>/error404</location>
 
   <location>/error404</location>
 
</error-page>
 
</error-page>
</pre>
+
</syntaxhighlight>
  
 
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:
 
The target location may be another RESTXQ function. The [[Request Module#request:attribute|request:attribute]] function can be used to request details on the caught error:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
declare %rest:path("/error404") function page:error404() {
 
declare %rest:path("/error404") function page:error404() {
 
   "URL: " || request:attribute("javax.servlet.error.request_uri") || ", " ||  
 
   "URL: " || request:attribute("javax.servlet.error.request_uri") || ", " ||  
 
   "Error message: " || request:attribute("javax.servlet.error.message")
 
   "Error message: " || request:attribute("javax.servlet.error.message")
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
=User Authentication=
 
=User Authentication=
Line 624: Line 624:
 
The following example returns the current host name:
 
The following example returns the current host name:
  
<pre class="brush:xquery">
+
<syntaxhighlight lang="xquery">
 
import module namespace request = "http://exquery.org/ns/request";
 
import module namespace request = "http://exquery.org/ns/request";
  
Line 630: Line 630:
 
   'Remote host name: ' || request:remote-hostname()
 
   'Remote host name: ' || request:remote-hostname()
 
};
 
};
</pre>
+
</syntaxhighlight>
  
 
=References=
 
=References=

Revision as of 14:57, 27 February 2020

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

RESTXQ, introduced by Adam Retter, is an API that facilitates the use of XQuery as a server-side processing language for the Web. RESTXQ has been inspired by Java’s JAX-RS API: it defines a pre-defined set of XQuery 3.0 annotations for mapping HTTP requests to XQuery functions, which in turn generate and return HTTP responses.

Please note that BaseX provides various extensions to the original draft of the specification:

  • Multipart types are supported, including multipart/form-data
  • A %rest:error annotation can be used to catch XQuery errors
  • Servlet errors can be redirected to other RESTXQ pages
  • A RESTXQ Module provides some helper functions
  • Parameters are implicitly cast to the type of the function argument
  • The Path Annotation can contain regular expressions
  • %input annotations, support for input-specific content-type parameters
  • %rest:single annotation to cancel running RESTXQ functions
  • Quality factors in the Accept header will be evaluated
  • Support for server-side quality factors in the %rest:produces annotation
  • Better support for the OPTIONS and HEAD methods


Introduction

Preliminaries

The RESTXQ service is accessible via http://localhost:8984/.

All RESTXQ annotations are assigned to the http://exquery.org/ns/restxq namespace, which is statically bound to the rest prefix. A Resource Function is an XQuery function that has been marked up with RESTXQ annotations. When an HTTP request comes in, a resource function will be invoked that matches the constraints indicated by its annotations.

If a RESTXQ URL is requested, the RESTXQPATH module directory and its sub-directories will be traversed, and all XQuery files will be parsed for functions with RESTXQ annotations. Sub-directories that include an .ignore file will be skipped. In addition, XQuery modules that cannot be parsed will be ignored if RESTXQERRORS is enabled.

To speed up processing, the functions of the existing XQuery modules are automatically cached in main memory:

  • Functions will be invalidated and parsed again if the timestamp of their module changes.
  • File monitoring can be adjusted via the PARSERESTXQ option. In productive environments with a high load, it may be recommendable to change the timeout, or completely disable monitoring.
  • If files are replaced while the web server is running, the RESTXQ module cache should be explicitly invalidated by calling the static root path /.init or by calling the rest:init function.

Examples

A first RESTXQ function is shown below:

<syntaxhighlight lang="xquery"> module namespace page = 'http://basex.org/examples/web-page';

declare %rest:path("hello/{$who}") %rest:GET function page:hello($who) {

 <response>
   <title>Hello { $who }!</title>
 </response>

};</syntaxhighlight>

If the URI http://localhost:8984/hello/World is accessed, the result will be:

<syntaxhighlight lang="xml"> <response>

 <title>Hello World!</title>

</response> </syntaxhighlight>

The next function demonstrates a POST request:

<syntaxhighlight lang="xquery"> declare

 %rest:path("/form")
 %rest:POST
 %rest:form-param("message","{$message}", "(no message)")
 %rest:header-param("User-Agent", "{$agent}")

function page:hello-postman(

 $message as xs:string,
 $agent   as xs:string*

) as element(response) {

 <response type='form'>
   <message>{ $message }</message>
   <user-agent>{ $agent }</user-agent>
 </response>

}; </syntaxhighlight>

If you post something (e.g. using curl or the embedded form at http://localhost:8984/)...

<syntaxhighlight lang="shell"> curl -i -X POST --data "message='CONTENT'" http://localhost:8984/form </syntaxhighlight>

...you will receive something similar to the following result:

<syntaxhighlight lang="shell"> HTTP/1.1 200 OK Content-Type: application/xml; charset=UTF-8 Content-Length: 107 Server: Jetty(8.1.11.v20130520) </syntaxhighlight>

<syntaxhighlight lang="xml"> <response type="form">

 <message>'CONTENT'</message>
 <user-agent>curl/7.31.0</user-agent>

</response> </syntaxhighlight>

Request

This section shows how annotations are used to handle and process HTTP requests.

Constraints

Constraints restrict the HTTP requests that a resource function may process.

Paths

A resource function must have a single Path Annotation with a single string as argument. The function will be called if a URL matches the path segments and templates of the argument. Path templates contain variables in curly brackets, and map the corresponding segments of the request path to the arguments of the resource function. The first slash in the path is optional.

The following example contains a path annotation with three segments and two templates. One of the function arguments is further specified with a data type, which means that the value for $variable will be cast to an xs:integer before being bound:

<syntaxhighlight lang="xquery"> declare %rest:path("/a/path/{$with}/some/{$variable}")

 function page:test($with, $variable as xs:integer) { ... };

</syntaxhighlight>

Variables can be enhanced by regular expressions:

<syntaxhighlight lang="xquery"> (: Matches all paths with "app" as first, a number as second, and "order" as third segment :) declare %rest:path("app/{$code=[0-9]+}/order")

 function page:order($code) { ... };

(: Matches all other all paths starting with "app/" :) declare %rest:path("app/{$path=.+}")

 function page:others($path) { ... };

</syntaxhighlight>

If multiple path candidates are found for the request, the one with more segments will be preferred.

Content Negotiation

Two following annotations can be used to restrict functions to specific content types:

  • HTTP Content Types: A function will only be invoked if the HTTP Content-Type header of the request matches one of the given content types. Example:

<syntaxhighlight lang="xquery">%rest:consumes("application/xml", "text/xml")</syntaxhighlight>

  • HTTP Accept: A function will only be invoked if the HTTP Accept header of the request matches one of the defined content types. Example:

<syntaxhighlight lang="xquery">%rest:produces("application/atom+xml")</syntaxhighlight>

By default, both content types are */*. Quality factors supplied by a client will also be considered in the path selection process. If a client supplies the following accept header…

<syntaxhighlight>

  • /*;q=0.5,text/html;q=1.0

</syntaxhighlight>

…and if two RESTXQ functions exist with the same path annotation, one with the produces annotation */*, and another with text/html, the second function will be called, because the quality factor for text/html documents is highest.

Server-side quality factors are supported as well: If multiple function candidates are left over after the above steps, the qs parameter will be considered. The function with the highest quality factor will be favored:

<syntaxhighlight lang="xquery"> %rest:produces("text/html;qs=1") %rest:produces("*/*;qs=0.8") </syntaxhighlight>

Note that the annotation will not affect the content type of the actual response. You will need to supply an additional %output:media-type annotation.

HTTP Methods

Default Methods

The HTTP method annotations are equivalent to all HTTP request methods except TRACE and CONNECT. Zero or more methods may be used on a function; if none is specified, the function will be invoked for each method.

The following function will be called if GET or POST is used as request method:

<syntaxhighlight lang="xquery"> declare %rest:GET %rest:POST %rest:path("/post")

 function page:post() { "This was a GET or POST request" };

</syntaxhighlight>

The POST and PUT annotations may optionally take a string literal in order to map the HTTP request body to a function argument. Once again, the target variable must be embraced by curly brackets:

<syntaxhighlight lang="xquery"> declare %rest:PUT("{$body}") %rest:path("/put")

 function page:put($body) { "Request body: " || $body };

</syntaxhighlight>

Custom Methods

Custom HTTP methods can be specified with the %rest:method annotation. An optional body variable can be supplied as second argument:

<syntaxhighlight lang="xquery"> declare

 %rest:path("binary-size")
 %rest:method("SIZE", "{$body}")

function page:patch(

 $body  as xs:base64Binary

) {

 "Request method: " || request:method(),
 "Size of body: " || bin:length($body)

}; </syntaxhighlight>

Template:Mark

If an OPTIONS request is received, and if no function is defined, an automatic response will be generated, which includes an Allow header with all supported methods.

If a HEAD request is received, and if no function is defined, the corresponding GET function will be processed, but the response body will be discarded.

Content Types

The body of a POST or PUT request will be converted to an XQuery item. Conversion can be controlled by specifying a content type. It can be further influenced by specifying additional content-type parameters:

Content-Type Parameters (;name=value) Type of resulting XQuery item
text/xml, application/xml document-node()
text/* xs:string
application/json JSON Options document-node() or map(*)
text/html HTML Options document-node()
text/comma-separated-values CSV Options document-node() or map(*)
others xs:base64Binary
multipart/* sequence (see next paragraph)

For example, if application/json;lax=yes is specified as content type, the input will be transformed to JSON, and the lax QName conversion rules will be applied, as described in the JSON Module.

Input options

Conversion options for JSON, CSV and HTML can also be specified via annotations with the input prefix. The following function interprets the input as text with the CP1252 encoding and treats the first line as header:

<syntaxhighlight lang="xquery"> declare

 %rest:path("/store.csv")
 %rest:POST("{$csv}")
 %input:csv("header=true,encoding=CP1252")

function page:store-csv($csv as document-node()) {

 "Number of rows: " || count($csv/csv/record)

}; </syntaxhighlight>

Multipart Types

The single parts of a multipart message are represented as a sequence, and each part is converted to an XQuery item as described in the last paragraph.

A function that is capable of handling multipart types is identical to other RESTXQ functions:

<syntaxhighlight lang="xquery"> declare

 %rest:path("/multipart")
 %rest:POST("{$data}")
 %rest:consumes("multipart/mixed") (: optional :)

function page:multipart($data as item()*) {

 "Number of items: " || count($data)

}; </syntaxhighlight>

Parameters

The following annotations can be used to bind request values to function arguments. Values will implicitly be cast to the type of the argument.

Query Parameters

The value of the first parameter, if found in the query component, will be assigned to the variable specified as second parameter. If no value is specified in the HTTP request, all additional parameters will be bound to the variable (if no additional parameter is given, an empty sequence will be bound):

<syntaxhighlight lang="xquery"> declare

 %rest:path("/params")
 %rest:query-param("id", "{$id}")
 %rest:query-param("add", "{$add}", 42, 43, 44)

function page:params($id as xs:string?, $add as xs:integer+) {

 <result id="{ $id }" sum="{ sum($add) }"/>

}; </syntaxhighlight>

HTML Form Fields

Form parameters are specified the same way as query parameters. Their values are the result of HTML forms submitted with the content type application/x-www-form-urlencoded.

<syntaxhighlight lang="xquery"> %rest:form-param("parameter", "{$value}", "default") </syntaxhighlight>

File Uploads

Files can be uploaded to the server by using the content type multipart/form-data (the HTML5 multiple attribute enables the upload of multiple files):

<syntaxhighlight lang="xml"> <form action="/upload" method="POST" enctype="multipart/form-data">

 <input type="file" name="files"  multiple="multiple"/>
 <input type="submit"/>

</form> </syntaxhighlight>

The file contents are placed in a map, with the filename serving as key. The following example shows how uploaded files can be stored in a temporary directory:

<syntaxhighlight lang="xquery"> declare

 %rest:POST
 %rest:path("/upload")
 %rest:form-param("files", "{$files}")

function page:upload($files) {

 for $name    in map:keys($files)
 let $content := $files($name)
 let $path    := file:temp-dir() || $name
 return (
   file:write-binary($path, $content),
   <file name="{ $name }" size="{ file:size($path) }"/>
 )

}; </syntaxhighlight>

HTTP Headers

Header parameters are specified the same way as query parameters:

<syntaxhighlight lang="xquery"> %rest:header-param("User-Agent", "{$user-agent}") %rest:header-param("Referer", "{$referer}", "none") </syntaxhighlight>

Cookies

Cookie parameters are specified the same way as query parameters:

<syntaxhighlight lang="xquery"> %rest:cookie-param("username", "{$user}") %rest:cookie-param("authentication", "{$auth}", "no_auth") </syntaxhighlight>

Query Execution

In many RESTXQ search scenarios, input from browser forms is processed and search results are returned. User experience can generally be made more interactive if an updated search request is triggered with each key click. However, this may lead to many expensive parallel requests, from which only the result of the last request will be relevant for the client.

With the %rest:single annotation, it can be enforced that only one instance of a function will be executed for the same client. If the same function will be called for the second time, the already running query will be stopped, and the HTTP error code 460 will be returned instead:

<syntaxhighlight lang="xquery"> (: If fast enough, returns the result. Otherwise, if called again, raises 460 :) declare

 %rest:path("/search")
 %rest:query-param("term", "{$term}")
 %rest:single

function page:search($term as xs:string) {

    { for $result in db:open('large-db')//*[text() = $term] return
  • { $result }
  • }

}; </syntaxhighlight>

By specifying a string along with the annotation, functions can be bundled together, and one request can be canceled by calling another one.

This is shown by another example, in which the first function can be interrupted by the second one. If you call both functions in separate browser tabs, you will note that the first tab will return 460, and the second one will return <xml>stopped</xml>.

<syntaxhighlight lang="xquery"> declare

 %rest:path("/compute")
 %rest:single("EXPENSIVE")

function local:compute() {

 (1 to 100000000000000)[. = 0]

};

declare

 %rest:path("/stop")
 %rest:single("EXPENSIVE")

function local:stop() {

 <xml>stopped</xml>

}; </syntaxhighlight>

The following things should be noted:

  • If a query will be canceled, there will be no undesirable side-effects. For example, it won’t be possible to kill a query if it is currenly updating the database or perfoming any other I/O operations. As a result, the termination of a running query can take some more time as expected.
  • The currently executed function is bound to the current session. This way, a client will not be able to cancel requests from other clients. As a result, functions can only be stopped if there was at least one previous successful response, in which initial session data was returned to the client.

Response

By default, a successful request is answered with the HTTP status code 200 (OK) and is followed by the given content. An erroneous request leads to an error code and an optional error message (e.g. 404 for “resource not found”).

Custom Response

Custom responses can be generated in XQuery by returning an rest:response element, an http:response child node that matches the syntax of the EXPath HTTP Client Module specification, and optional child nodes that will be serialized as usual. A function that yields a response on an unknown resource may look as follows:

<syntaxhighlight lang="xquery"> declare %output:method("text") %rest:path("") function page:error404() {

 <rest:response>
   <http:response status="404">
     <http:header name="Content-Language" value="en"/>
     <http:header name="Content-Type" value="text/plain; charset=utf-8"/>
   </http:response>
 </rest:response>,
 "The requested resource is not available."

}; </syntaxhighlight>

Forwards and Redirects

Redirects

Template:Mark rest:redirect element.

The server can invite the client (e.g., the web browser) to make a second request to another URL by sending a 302 response:

<syntaxhighlight lang="xml"> <rest:response>

 <http:response status="302">
   <http:header name="Location" value="new-location"/>
 </http:response>

</rest:response> </syntaxhighlight>

The convenience function web:redirect can be called to create such a response.

In the XQuery context, redirects are particularly helpful if Updates are performed. An updating request may send a redirect to a second function that generates a success message, or evaluates an updated database:

<syntaxhighlight lang="xquery"> declare %updating %rest:path('/app/init') function local:create() {

 db:create('app', <root/>, 'root.xml'),
 db:output(web:redirect('/app/ok'))

};

declare %rest:path('/app/ok') function local:ok() {

 'Stored documents: ' || count(db:open('app'))

}; </syntaxhighlight>

Forwards

A server-side redirect is called forwarding. It reduces traffic among client and server, and the forwarding will not change the URL seen from the client’s perspective:

<syntaxhighlight lang="xml"> <rest:forward>new-location</rest:forward> </syntaxhighlight>

The fragment can also be created with the convenience function web:forward.

Output

The content-type of a response can be influenced by the user via Serialization Parameters. The steps are described in the REST chapter. In RESTXQ, serialization parameters can be specified in the query prolog, via annotations, or within the REST response element:

Query Prolog

In main modules, serialization parameters may be specified in the query prolog. These parameters will then apply to all functions in a module. In the following example, the content type of the response is overwritten with the media-type parameter:

<syntaxhighlight lang="xquery"> declare option output:media-type 'text/plain';

declare %rest:path("version1") function page:version1() {

 'Keep it simple, stupid'

}; </syntaxhighlight>

Annotations

Global serialization parameters can be overwritten via %output annotations. The following example serializes XML nodes as JSON, using the JsonML format:

<syntaxhighlight lang="xquery"> declare

 %rest:path("cities")
 %output:method("json")
 %output:json("format=jsonml")

function page:cities() {

 element cities {
   db:open('factbook')//city/name
 }

}; </syntaxhighlight>

The next function, when called, generates XHTML headers, and text/html will be set as content type:

<syntaxhighlight lang="xquery"> declare

 %rest:path("done")
 %output:method("xhtml")
 %output:omit-xml-declaration("no")
 %output:doctype-public("-//W3C//DTD XHTML 1.0 Transitional//EN")  
 %output:doctype-system("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd")

function page:html() {

 <html xmlns="http://www.w3.org/1999/xhtml">
   <body>done</body>
 </html>

}; </syntaxhighlight>

Response Element

Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:

<syntaxhighlight lang="xquery"> declare %rest:path("version3") function page:version3() {

 <rest:response>
   <output:serialization-parameters>
     <output:media-type value='text/plain'/>
   </output:serialization-parameters>
 </rest:response>,
 'Not that simple anymore'

}; </syntaxhighlight>

Error Handling

Raise Errors

Template:Mark:

If an error is raised during the evaluation of a RESTXQ function, an HTTP response with the status code 400 is generated. The response body contains the full error message and stack trace.

With the web:error function, you can abort query evaluation and enforce a premature HTTP response with the supplied status code and response body text:

<syntaxhighlight lang="xquery"> declare

 %rest:path("/teapot")

function page:teapot() {

 web:error(418, "I'm a pretty teapot")

}; </syntaxhighlight>

The XQuery error code and the stack trace will be suppressed in the body of the HTTP response.

Catch XQuery Errors

XQuery runtime errors can be processed via error annotations. Error annotations have one or more arguments, which represent the error codes to be caught. The codes equal the names of the XQuery 3.0 try/catch construct:

Precedence Syntax Example
1 prefix:name
Q{uri}name
err:FORG0001
Q{http://www.w3.org/2005/xqt-errors}FORG0001
2 prefix:*
Q{uri}*
err:*
Q{http://www.w3.org/2005/xqt-errors}*
3 *:name *:FORG0001
4 * *

All error codes that are specified for a function must have the same precedence. The following rules apply when catching errors:

  • Codes with a higher precedence (smaller number) will be given preference.
  • A global RESTXQ error will be raised if two functions with conflicting codes are found.

Similar to try/catch, the pre-defined variables (code, description, value, module, line-number, column-number, additional) can be bound to variables via error parameter annotations, which are specified the same way as query parameters.

Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:

<syntaxhighlight lang="xquery"> declare

 %rest:path("/check/{$user}")

function page:check($user) {

 if($user = ('jack', 'lisa'))
 then 'User exists'
 else fn:error(xs:QName('err:user'), $user)

};

declare

 %rest:error("err:user")
 %rest:error-param("description", "{$user}")

function page:user-error($user) {

 'User "' || $user || '" is unknown'

}; </syntaxhighlight>

Catch HTTP Errors

Errors that occur outside RESTXQ can be caught by adding error-page elements with an error code and a target location to the web.xml configuration file (find more details in the Jetty Documentation):

<syntaxhighlight lang="xml"> <error-page>

 <error-code>404</error-code>
 <location>/error404</location>

</error-page> </syntaxhighlight>

The target location may be another RESTXQ function. The request:attribute function can be used to request details on the caught error:

<syntaxhighlight lang="xquery"> declare %rest:path("/error404") function page:error404() {

 "URL: " || request:attribute("javax.servlet.error.request_uri") || ", " || 
 "Error message: " || request:attribute("javax.servlet.error.message")

}; </syntaxhighlight>

User Authentication

If you want to provide restricted access to parts of a web applications, you will need to check permissions before returning a response to the client. The Permissions layer is a nice abstraction for defining permission checks.

Functions

The Request Module contains functions for accessing data related to the current HTTP request. Two modules exist for setting and retrieving server-side session data of the current user (Session Module) and all users known to the HTTP server (Sessions Module). The RESTXQ Module provides functions for requesting RESTXQ base URIs and generating a WADL description of all services. Please note that the namespaces of all of these modules must be explicitly specified via module imports in the query prolog.

The following example returns the current host name:

<syntaxhighlight lang="xquery"> import module namespace request = "http://exquery.org/ns/request";

declare %rest:path("/host-name") function page:host() {

 'Remote host name: ' || request:remote-hostname()

}; </syntaxhighlight>

References

Documentation:

Examples:

  • Sample code combining XQuery and JavaScript: Materials and paper from Amanda Galtman, Balisage 2016.
  • DBA: The Database Administration interface, bundled with the full distributions of BaseX.

Changelog

Version 9.3
  • Updated: Custom Methods: Better support for the OPTIONS and HEAD methods.
  • Updated: XQuery Errors: Suppress stack trace and error code in the HTTP response.
  • Removed: rest:redirect element (web:redirect can be used instead)
Version 9.2
  • Updated: Ignore XQuery modules that cannot be parsed
Version 9.0
  • Added: Support for server-side quality factors in the %rest:produces annotation
  • Updated: Status code 410 was replaced with 460
  • Removed: restxq prefix
Version 8.4
  • Added: %rest:single annotation
Version 8.1
  • Added: support for input-specific content-type parameters
  • Added: %input annotations
Version 8.0
Version 7.9
  • Updated: XQuery Errors, extended error annotations
  • Added: %rest:method
Version 7.7
  • Added: Error Handling, File Uploads, Multipart Types
  • Updated: RESTXQ function may now also be specified in main modules (suffix: *.xq).
  • Updated: the RESTXQ prefix has been changed from restxq to rest.
  • Updated: parameters are implicitly cast to the type of the function argument
  • Updated: the RESTXQ root url has been changed to http://localhost:8984/
Version 7.5
  • Added: new XML elements <rest:redirect/> and <rest:forward/>