XQuery/Getting URL Parameters

Motivation

edit

You want to create an XQuery that takes a parameter from the calling URL.

Format

edit

The format of a calling URL that uses the HTTP Get or POST command is:

  <hostname>:<port>/<path>/xquery.xq?param1=123&param2=456

Where param1 is the first parameter with a value of 123 and param2 is the second parameter with a value of 456.

Note that question mark is used to start the parameters and the ampersand is used to separate parameters. Remember to include "amp;" following the &.

xquery version "1.0";

let $param1:= request:get-parameter('param1', '')
let $param2:= request:get-parameter('param2', "")

return
<results>
   if ($param2 = '0') then (
       <message>param2 is empty</message>
   ) else (
      <message>default message</message>
   )
</results>

Checking Data Types

edit

Additionally you can check the data types using the XML Schema data types and the castable as operator.

xquery version "1.0";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace xs="http://www.w3.org/2001/XMLSchema";

let $myint := request:get-parameter("myint",0)
let $myint := if ($myint castable as  xs:integer)
              then xs:integer($myint)
              else 0
let $mydecimal := request:get-parameter("mydecimal", 0.0)
let $mydecimal := if ($mydecimal castable as  xs:decimal)
                  then xs:decimal($mydecimal)
                  else 0.0

return
<results>
   <message>Got  myint: {$myint} and  mydecimal: {$mydecimal} </message>
</results>

Script to echo all URL parameters

edit

echo-parameters.xq

xquery version "1.0";

(: echo a list of all the URL parameters  :)
let $parameters :=  request:get-parameter-names()

return
<results>
   <parameters>{$parameters}</parameters>
   {for $parameter in $parameters
   return
   <parameter>
      <name>{$parameter}</name>
      <value>{request:get-parameter($parameter, '')}</value>
   </parameter>
   }
</results>

Here are the results of sending the parameters "a=1&b=2" to this XQuery:

  echo-parameters.xq?a=1&b=2
<results>
    <parameters>b a</parameters>
    <parameter>
        <name>b</name>
        <value>2</value>
    </parameter>
    <parameter>
        <name>a</name>
        <value>1</value>
    </parameter>
</results>

Adding a Debug Parameter

edit

It is very common that you want to conditionally turn on part of a transform to get additional information during the debugging process.

let $debug := xs:boolean(request:get-parameter('debug', ''))