GatewayScript code examples

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

Note:
  • 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:
    DataPower
    Gatewayvar name = require('./apim.custom.js');
    DataPower API
    Gatewayvar name = require('apim');
    where name is your chosen name; for example:
    var apim = require('apim');
  • The mechanisms described here for interacting with the API Connect context are compatible with Version 5. However, if you are writing new GatewayScript policy, XSLT policy, or user-defined policy code, the preferred mechanisms, which provide better performance, are as described on Using context variables in GatewayScript and XSLT policies with the DataPower API Gateway.

Access the assembly context

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

Example one returns the request context:

apim.getvariable('request');
Example two returns the header named foo:
apim.getvariable('request.headers.foo');
Example three shows how to set, add, or clear a context variable, in this case a message header:
apim.setvariable('message.headers.name', value, action)
where
  • 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
}
else
{
// 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
json.data = 'This is my test data'
}
session.output.write(json); 
// 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');
where:
  • 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:
apim.output('application/type');
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
apim.output('application/xml');
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.