XQuery/Checking for Required Parameters

Motivation
You want to check for required parameters and return a useful error message if the required parameters are not present.

Approach
To solve this problem we will use the get-parameter function and only return results if the parameter is present. If it is not present then we will return a useful error message.

Sample Program
xquery version "1.0"; declare namespace request="http://exist-db.org/xquery/request";

let $parameter-1 := request:get-parameter('p1', '')

return if (not($parameter-1)) then (       Parameter 1 is missing.        Parameter 1 is a required parameter for this XQuery.       ) else (         Parameter 1={$parameter-1} )

Output
If you do not supply the required parameter the following will result:

Parameter 1 is missing. Parameter 1 is a required parameter for this XQuery.

Checking for multiple Arguments
The following example checks for multiple arguments. In this case if parameter 1 OR parameter 2 is missing an error will be generated.

xquery version "1.0"; declare namespace request="http://exist-db.org/xquery/request";

declare option exist:serialize "method=xhtml media-type=text/xml indent=yes";

let $parameter-1 := request:get-parameter('p1', '') let $parameter-2 := request:get-parameter('p2', '')

return if (not($parameter-1) or not($parameter-2)) then (       Parameter 1 or 2 is missing.        Both arguments required for this XQuery.         Parameter 1={$parameter-1}         Parameter 2={$parameter-2}     ) else (   Parameter 1={$parameter-1}     Parameter 2={$parameter-2} )

Note that the following logic is equivalent:

Sometimes the second form is easier to read.

Returning HTTP Status Codes
There is considerable discussion if you should also return a HTTP error code such as a 400 error. In general if the checks to the parameters are part of your business logic and not part of the communication protocol you should never return HTTP codes. This tells the calling application that they got the base URL correct and there was no permission problems but the application logic detected an error. The client application should then understand how to parse error documents and display the relevant error messages to the user.

For further details see HTTP Status Codes

Checking for File Availability
Many times a URL parameter is used to open a specific file from a data collection within an application.

You can use the doc-available function and following code sample to check for the existence of a file: