Changes

Jump to navigation Jump to search
360 bytes removed ,  18:36, 1 December 2023
m
Text replacement - "<syntaxhighlight lang="xquery">" to "<pre lang='xquery'>"
A first RESTXQ function is shown below:
<syntaxhighlight pre lang="'xquery"'>
module namespace page = 'http://basex.org/examples/web-page';
The next function demonstrates a POST request:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/form")
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:
<syntaxhighlight pre lang="'xquery"'>
declare %rest:path("/a/path/{$with}/some/{$variable}")
function page:test($with, $variable as xs:integer) { ... };
Variables can be enhanced by regular expressions:
<syntaxhighlight pre 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")
A function will only be taken into consideration if the HTTP {{Code|Content-Type}} header of the request matches one of the given types:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:POST("{$body}")
A function will only be chosen if the HTTP {{Code|Accept}} header of the request matches one of the given types:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/xml")
…and if two RESTXQ functions exist for the addressed path with two different annotations for producing data…
<syntaxhighlight pre lang="'xquery"'>
declare function %rest:produces("text/html") ...
...
As we cannot ensure that the client may supply quality factors, the selection process can also be controlled server-side. The <code>qs</code> parameter can be attached server-side to the Media Type. If multiple functions are left in the selection process, the one with the highest quality factor will be favored:
<syntaxhighlight pre lang="'xquery"'>
declare function %rest:produces("application/json;qs=1") ...
...
The following function will be called if GET or POST is used as request method:
<syntaxhighlight pre lang="'xquery"'>
declare %rest:GET %rest:POST %rest:path("/post")
function page:post() { "This was a GET or POST request" };
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:
<syntaxhighlight pre lang="'xquery"'>
declare %rest:PUT("{$body}") %rest:path("/put")
function page:put($body) { "Request body: " || $body };
Custom HTTP methods can be specified with the {{Code|%rest:method}} annotation. An optional body variable can be supplied as second argument:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("binary-size")
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:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/store.csv")
A function that is capable of handling multipart types is identical to other RESTXQ functions:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/multipart")
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):
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/params")
Form parameters are specified the same way as [[#Query Parameters|query parameters]]:
<syntaxhighlight pre lang="'xquery"'>
%rest:form-param("city", "{$city}", "no-city-specified")
</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:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:POST
Header parameters are specified the same way as [[#Query Parameters|query parameters]]:
<syntaxhighlight pre lang="'xquery"'>
%rest:header-param("User-Agent", "{$user-agent}")
%rest:header-param("Referer", "{$referer}", "none")
Cookie parameters are specified the same way as [[#Query Parameters|query parameters]]:
<syntaxhighlight pre lang="'xquery"'>
%rest:cookie-param("username", "{$user}")
%rest:cookie-param("authentication", "{$auth}", "no_auth")
With the <code>%rest:single</code> annotation, it can be enforced that only one instance of a function will run at the same time and for the same client. If the same function will be called for the second time, a currently executed query will be stopped, and the HTTP error code {{Code|460}} will be returned instead:
<syntaxhighlight pre lang="'xquery"'>
(: If fast enough, returns the result. Otherwise, if called again, raises 460 :)
declare
By adding a string value to with the annotation, functions can be bundled together, and a running query can be canceled by calling another one that has the same annotation value. 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>.
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/compute")
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:
<syntaxhighlight pre lang="'xquery"'>
declare %output:method("text") %rest:path("") function page:error404() {
<rest:response>
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:
<syntaxhighlight pre lang="'xquery"'>
declare %updating %rest:path('/app/init') function local:create() {
db:create('app', <root/>, 'root.xml'),
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:
<syntaxhighlight pre lang="'xquery"'>
declare option output:media-type 'text/plain';
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:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("cities")
The next function, when called, generates XHTML headers, and {{Code|text/html}} will be set as content type:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("done")
Serialization parameters can also be specified in a REST reponse element in a query. Serialization parameters will be overwritten:
<syntaxhighlight pre lang="'xquery"'>
declare %rest:path("version3") function page:version3() {
<rest:response>
With {{Function|Web|web:error}}, you can abort query evaluation, enforce a premature HTTP response and report errors back to the client:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/teapot")
Errors may occur unexpectedly. However, they can also be triggered by a query, as demonstrated by the following example:
<syntaxhighlight pre lang="'xquery"'>
declare
%rest:path("/check/{$user}")
The target location may be another RESTXQ function. The {{Function|Request|request:attribute}} function can be used to request details on the caught error:
<syntaxhighlight pre lang="'xquery"'>
declare %rest:path("/error404") function page:error404() {
"URL: " || request:attribute("javax.servlet.error.request_uri") || ", " ||
The following example returns the current host name:
<syntaxhighlight pre lang="'xquery"'>
import module namespace request = "http://exquery.org/ns/request";
Bureaucrats, editor, reviewer, Administrators
13,551

edits

Navigation menu