GatewayScript code examples

Example GatewayScript code snippets to help the creation of a gatewayscript policy.

  • The mechanisms described here for interacting with the API Connect context are intended for v5-compatible gateways and also to provide v5 compatibility for APIs created for the API Gateway. However, if you are writing a GatewayScript policy or user-defined policy for a new API Gateway API, use the mechanisms described in Using context variables in GatewayScript and XSLT policies with the DataPower API Gateway for better performance and long-term support. For API Gateway APIs, the v5-compatibility functions listed here are to be used for v5 migration only.
  • The GatewayScript functions that are listed here use the common name apim to call the methods. However, you can change the common name to one of your choice by using one or other of the following function calls depending on your gateway type:
    Gatewayvar name = require('local:///isp/policy/apim.custom.js');   // v5-Compatible Gateway
    DataPower API
    Gatewayvar name = require('apim');                                 // DataPower API Gateway
    where name is your chosen name; for example:
    var apim = require('apim');

Access the assembly context

The following code snippets show examples of how to access the assembly context.

Example one returns the request context:

Example two returns the header named myheader:
Example three shows how to set, add, or clear a context variable, in this case a message header:
apim.setvariable('', value, action)
  • name is the name of the message header that you want to set, add, or clear.
  • value is the string value that you want to set the variable to. This can be a literal value, or another variable. For example, to set your named variable to the value of the Content-Type header in a request, you would specify the value as request.headers.content-type. This property is only required when set or add is specified as the action.
  • action is the action that you want to apply to the variable. Valid options are:
    • set
    • add
    • clear
    If no option is set, the default option of set is applied.

For a complete list of context variables, see API Gateway context variables, and for more information about how to reference context variables in IBM API Connect see Variable references in API Connect. If you are using the DataPower® API Gateway, see also Using context variables in GatewayScript and XSLT policies with the DataPower API Gateway.

Read input synchronously

The following code snippets show examples of how to read input synchronously by using the apim.getvariable function to read data direct from a context. JSON input is returned as a JavaScript object. XML data is returned as a NodeList object (DOM).

Example one returns a synchronous read of the original request body into the variable that is called json:

var json = apim.getvariable('request.body');
Example two returns a synchronous read of the current message into the variable that is called xml:
var xml = apim.getvariable('message.body');
Note: If the content type of the data is neither XML nor JSON, the apim.getvariable() function returns a NodeList object consisting of one binary node, which must be converted to a string. If the content really is XML or JSON, you must then parse this string, as illustrated in the following example:
var data = apim.getvariable('request.body');

// if a nodelist was returned and the type is 13 (BLOB/Binary Node), convert it
// to a Buffer, which can then be converted to a string
if ((data.item && data.length > 0 && data.item(0).nodeType === 13)) {
  data = data.item(0).toBuffer().toString();

// if the string really is XML or JSON, then now add code to parse it with
// the appropriate XML or JSON parse function

Read input asynchronously

The following code snippets show the apim.readInput() calls that you can use to perform a JavaScript callback function to read input data asynchronously into a variable. JSON input is returned as a JavaScript object. XML data is returned as a NodeList object (DOM). Other types of input are returned as a Buffer object.
apim.readInput(callback(err,input) {});
apim.readInputAsJSON(callback(err,json) {});
apim.readInputAsXML(callback(err,nodelist) {});
apim.readInputAsBuffer(callback(err,buffer) {});
Note: The apim.readInput() function attempts to determine the input data type and call the appropriate apim.readInputAstype() function in order to return the data in the correct format. However, to ensure that the correct data type is returned, use the apim.readInputAstype() function.

The apim.readInputAstype() function reads the data from either the INPUT context (for example session.INPUT), or from a policy output context (for example policy.output), depending on whether a previous policy had been called that had written output to a policy output context. This function then calls the underlying IBM DataPower GatewayScript readAstype method on the relevant context to read the data, and then use JavaScript callbacks to return the data to a variable. For more information about DataPower methods, see APIs for methods.

The following is an example of how to use the apim.readInputAsJSON() callback function to get data into a variable that is called json:
apim.readInputAsJSON(function (error, json) {
if (error)
// handle error
// the json parameter will contain the json data that has been read
// process the json object in some way and write to the output context
if (json.test=='true') 
// if json data contains a variable called test that is set to true, then also add some test data = 'This is my test data'
// write to the output context

Configure error information

The following code block shows an example of how to configure the policy implementation to produce error information by using the apim.error() function. In this example, MyError is thrown to the assembly flow. If there is a catch handler it catches this error, otherwise the assembly skips the execution of the flow and sends a 500 Internal Error response.
apim.error('MyError', 500, 'Internal Error', 'Some error message');
  • MyError is the name of the error.
  • 500 is the HTTP code of the required error message.
  • Internal Error is the HTTP reason phrase for the error.
  • Some error message is the suggested action for the user.

Accessing the caught exception in a catch block

The following example shows how, in the catch block of an API assembly, you can obtain the details of the current caught exception. A possible use would be to create a custom error response using the details of the caught exception.
let exception = apim.getError();
The function returns a JSON object; for example:
  "name": "OperationError",
  "message": "This is a thrown Operation Error",
  "policyTitle": "Throw Operation Error",
  "status": {
    "code": "500",
    "reason": "Internal Server Error"

Write output

The following example shows how to write data into the output, in this case the JSON data '{ "status": "created" }', by using the session.output.write variable:
session.output.write('{ "status": "created" }');
The session.output.write variable is a standard GatewayScript method that writes data to the output context. For more information, see Contexts and sessions.
Use the following function to set the format of the content that is written to the session.output variable:
For example, if you were creating a policy that called:
session.output.write('<test>this is some xml data</test>');
the policy would write XML data to the output context. You would need to configure the policy to also call
to tell the system that the output is XML. It can cause issues in the processing of the policy if the actual output context format, and the format that is specified in apim.output, are different.
Note: If you use apim.setvariable to manipulate message.body, you must immediately follow the apim.setvariable function call with an apim.output function call that specifies the content type of the payload that was written to message.body by apim.setvariable.