The annotation %rest:query-param
is provided for
accessing parameters in the Query String of the URL used for a
RESTful Web Service request. Consider the following example
declare
%rest:path("/search")
%rest:query-param('query', '{$q}')
function perform-search($q as xs:string) {
<results>{
cts:search(fn:doc(), cts:parse($q))[1 to 10]
}</results>
};
A client could call this function by sending a
GET
request along the lines of the following
/search?query=hello+world
In this case the query
Query Parameter is mapped
to the Function parameter $q
.
Unfortunately, due to a limitation in MarkLogic, only one
%rest:query-param
annotation can be used per function.
To accept more Query Parameters, you can use numbered Query
Param Annotations, such as
%rest:query-param-1
,
%rest:query-param-2
,
%rest:query-param-3
etc. Consider the following example
declare
%rest:path("/search")
%rest:query-param-1('query', '{$q}')
%rest:query-param-2('from', '{$from}')
%rest:query-param-3('to', '{$to}')
function perform-search(
$q as xs:string,
$from as xs:integer,
$to as xs:integer) {
<results>{
cts:search(fn:doc(), cts:parse($q))[$from to $to]
}</results>
};
A client could call this function by sending a
GET
request along the lines of the following
/search?query=hello+world&from=1&to=10
XQRS will automatically convert the Query Parameter into
the required parameter type at runtime for you, providing
the parameter type inherits from xs:anyAtomicType
Parameters received from Query Parameters can be optional and
as such the occurrence indicator on those parameters can be '?
'.
declare
%rest:path("/my-little-service")
%rest:query-param('optional-param', '{$opt}')
function optional($opt as xs:date?) {
if(fn:exists($opt)) then
'got date ' || $opt
else
'optional-param not given.'
};
If automatic type conversion is not possible, for instance the parameter expects a date but the value given for that parameter can not be cast to a date then an exception is thrown explaining this.
You can give Query Parameters default values, in case the client has not given a value for that parameter. Consider the following example
declare
%rest:path("/document-in-collection")
%rest:query-param-1('collection', '{$col}', 'my-default')
%rest:query-param-2('id', '{$id}', '1234')
function optional($col as xs:string, $id as xs:integer) {
fn:collection($col)/doc[@id = $id]
};
It's possible to receive a list of different values for a Query Parameter, for instance a client could send something along the lines of
/my-service?a=1&a=2&a=3&a=4
A request like that could be handled by the following Function
declare
%rest:path("/my-service")
%rest:query-param('a', '{$a}')
function list($a as xs:integer*) {
'found ' || count($a) || ' values'
};
You can even use a list of values as default parameters if you so wished
declare
%rest:path("/my-service")
%rest:query-param('a', '{$a}', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
function list($a as xs:integer+) {
'found ' || count($a) || ' values'
};