1. Accessing Request HTTP Headers with %rest:header-param

The annotation %rest:header-param is provided for accessing HTTP Request headers. Take the following sample HTTP request

GET /my-service HTTP/1.1
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
From: john.smith@xmllondon.com
Origin: http://www.anothersite.com/

The following function retrieves the User-Agent header and returns it back as the response

  %rest:header-param("User-Agent", "{$user-agent}")
function user-agent($user-agent as xs:string?) {

Unfortunately, due to a limitation in MarkLogic, only one %rest:header-param annotation can be used per function. If you wish to access more than one header in same function, use numbered annotations such as %rest:header-param-1, %rest:header-param-2, %rest:header-param-3 etc.

  %rest:header-param-1("User-Agent", "{$user-agent}")
  %rest:header-param-2("From", "{$from}")
  %rest:header-param-3("Origin", "{$origin}")
function show-3-headers(
  $user-agent as xs:string?,
  $from as xs:string?,
  $origin as xs:string?) {

2. Header Values which contain commas

If a single header field value contains comma separated values, XQRS will extract each value from the comma separated list into an item in the sequence passed to the function parameter.

Take the sample HTTP Request

GET /forwarded-for HTTP/1.1
Host: localhost

when passed through the following function

  %rest:header-param("X-Forwarded-For", "{$forwarded-for}")
function forwarded-for($forwarded-for as xs:string*) {
    for $ip in $forwarded-for
    return <ip>{$ip}</ip>

this would produce the following result


3. Automatic Type Conversion

XQRS will automatically convert the Header Parameter into the required parameter type at runtime for you, providing the parameter type inherits from xs:anyAtomicType

Parameters received from Header Parameters can be optional and as such the occurrence indicator on those parameters can be '?'.

  %rest:header-param('X-Optional', '{$opt}')
function optional($opt as xs:date?) {
  if(fn:exists($opt)) then
    'got date ' || $opt
    '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.

4. Default Values

You can give Header Parameters default values, in case the client has not given a value for that parameter. Consider the following example

  %rest:header-param-1('X-Collection', '{$col}', 'my-default')
  %rest:header-param-2('X-ID', '{$id}', '1234')
function optional($col as xs:string, $id as xs:integer) {
  fn:collection($col)/doc[@id = $id]