Velocity macros for data actions

Note: This article applies to the AWS Lambda, Genesys Cloud, Google, Microsoft Dynamics 365, Salesforce, web services, and Zendesk data actions integrations.

The data actions integrations allow you to create custom actions. These custom actions include request configurations and response configurations with templates that use the Velocity Template Language. These templates support a range of Velocity macros.

Warning: Escape any use of input or output variables within requestTemplate, successTemplate, or requestUrlTemplate. If you do not properly escape variables with special characters, your data actions fail at execution.

Velocity templates are valid for the following fields:

  • requestUrlTemplate
  • headers
  • requestTemplate
  • successTemplate

For more information, see Create a custom action, Request configuration, and Response configuration.

Note: Formal vs. silent formal notation

  • Formal notation: ${variable}

    If the variable is null, formal notation outputs the variable name.

  • Silent formal notation: $!{variable}

    If the variable is null, the silent notation outputs an empty string.

Math library

Prefix: math

Use these math macros to perform a basic math operation. For more information, see Class MathTool in the Velocity documentation.

String-escaping library

Prefix: esc

Use EscapeTool to escape strings in Velocity templates. EscapeTool provides methods to escape outputs for Java, JSON, JavaScript, HTML, XML, and SQL. EscapeTool also provides methods to escape Velocity Template Language characters. For more information, see Class EscapeTool in the Velocity documentation.

The following methods in particular are very helpful:

  • $esc.urlFormEncode(): Use this method to escape characters to comply with URL form coding rules. Note that the spaces are encoded as “+” by this method. It is most likely not used for the urlTemplate. See the $esc.uriEncode() method.
  • $esc.url(): Alias for the $esc.urlFormEncode() with the same functionality.
  • $esc.uriEncode(): Use this method to escape characters to comply with the URI, for example, the URL, rules. This method should be used to escape characters in the urlTemplate. Note that spaces are encoded as ‘%20’ by this method.
  • $esc.jsonEncode(): Use this method to escape JSON’s reserved characters in the output. It allows JSON to be stored in a string form.
  • $esc.jsonString(): Alias for the $esc.jsonEncode() with the same functionality.
  • $esc.jsonDecode(): Use this method to unescape JSON’s reserved characters resulting in the original JSON.
  • $esc.d(): Use this method to include a dollar sign ($).

The following table shows example inputs and outputs of various macros. 

Warning: Do not use JavaScript encoding. $esc.javascript($input) can create invalid JSON that breaks an action.

Macros Inputs Outputs
$esc.java($input) He didn't say, "Stop!" He didn't say, \"Stop!\"
$esc.html($input) "bread" & "butter" "bread" & "butter"
$esc.xml($input) "bread" & "butter" "bread" & "butter"
$esc.sql($input) McHale's Navy McHale''s Navy

$esc.urlFormEncode($input)

or

$esc.url($input)

hello here & there~ hello+here+%26+there~

$esc.uriEncode($input)

hello here & there~ hello%20here%20%26%20there%7E
$esc.dollar $
$esc.hash #
$esc.backslash \
$esc.quote "
$esc.singleQuote '
$esc.exclamation !

encoding.base64

Base64 encodes the strings that you provide. 

Template example

The encoded field is $encoding.base64(\"${first} and ${second}\")

Template example results

Inputs Resolved templates

first == cat

second == dog

Encoded field is Y2F0IGFuZCBkb2c=

esc.jsonEncode

When you build JSON bodies for POST, PUT, and PATH requests, you must escape reserved characters in any strings. This macro escapes quotes and other characters based on JSON encoding rules.

Note: esc.jsonEncode treats Unicode characters differently than EscapeTool.javascript() does. 

Template example

$esc.jsonEncode(${input.json})

Encoding example

Input Output

{

“foo”:”bar”

}

{\n\t\”foo\”:\”bar\”\n}

Null

Null

“”(empty string)

“”(empty string)

esc.jsonDecode

When you have a JSON encoded string and want to have JSON form of it, you can use the esc.jsonDecode() macro. This macro unescapes quotes and other characters based on JSON encoding rules.

Template example

$esc.jsonDecode(${input.escapedjson})

Decoding example

Input Output

{\n\t\”foo\”:\”bar\”\n}

{

“foo”:”bar”

}

successTemplateUtils.firstFromArray

This macro extracts the first element from the provided JSON array string and has two parameters. The first parameter, which is the input array for the extracted value, is required. The second parameter, which specifies the response that is returned when the array is empty, is optional and by defaults returns nothing. If the array is not empty, the second parameter is ignored. 

If the input for firstFromArray is data extracted through the translationMap JSONPath, then no string escaping is needed. In the following template examples, ids could come from a translationMap entry, such as "ids": "$.idArray".

Template examples and results

Template examples Inputs Resolved templates
${successTemplateUtils.firstFromArray("${ids}")} ids == "[1, 2, 3]" 1
ids == "[{\"id\":1}, {\"id\":2}, {\"id\":3}, {\"id\":4}]" {\"id\":1}
ids == "[]"
ids == "" This input results in an error.
${successTemplateUtils.firstFromArray(\"${ids}\", \"{}\")} ids == "[1, 2, 3]" 1
ids == "[{\"id\":1}, {\"id\":2}, {\"id\":3}, {\"id\":4}]" {\"id\":1}
ids == "[]" {}
ids == "" This input results in an error.
${successTemplateUtils.firstFromArray(\"${ids}\", \"$esc.quote $esc.quote\")}* ids == "[1, 2, 3]" 1
ids == "[{\"id\":1}, {\"id\":2}, {\"id\":3}, {\"id\":4}]" {\"id\":1}
ids == "[]" ""
ids == "" This input results in an error.

* This template example uses EscapeTool to escape characters. For more information, see String-escaping library.

successTemplateUtils.moveKeysIntoArrayOfObjects

This macro converts data into a format that is compatible with Architect and has two required parameters. The first parameter is the input from the original response. The second parameter is the key name that the macro adds to an object and the value is the dynamic field from the original response.

Note: If the macro cannot convert data, then the data action returns an error or an empty array.

To return the converted data, configure the translationMap and successTemplate in your data action based on the following example.

Data action example

"config": {
  "request": {
    "requestUrlTemplate": "https://some.website.com/with/normalized/data",
    "requestType": "GET",
    "headers": {
    },
    "requestTemplateDefault": true
  },
  "response": {
    "translationMap": {
      "entitySegmentMembershipUps": "$.*.path.to.dynamic.key"
    },
    "translationMapDefaults": {},
    "successTemplate": "{\"segments\": ${successTemplateUtils.moveKeysIntoArrayOfObjects(${entitySegmentMembershipUps})},\"segmentId\")}}"
  }
}

In the original response, you cannot access the GUID because it is a dynamic key and cannot be flattened correctly.

Original returned response

"segmentMembership": { 
  "ups": { 
    "a959c128-d6d9-4a42-a307-c5d278cfcbe2": { 
      "lastQualificationTime": "2020-11-16T03:23:31Z", 
      "status": "realized" 
    } 
  }
}

The macro moves the ID into an object and returns it as segmentId

Macro returned response

"segments": [
  {
    "lastQualificationTime": "2020-11-16T03:23:31Z",
    "status": "realized",
    "segmentId": "a959c128-d6d9-4a42-a307-c5d278cfcbe2"
  }
]

urlTool.optionalQueryParam

This macro formats a key-value pair as a query parameter, unless the value is empty. Otherwise, the macro returns an empty string. Do not include the ampersand (&) in your template; the macro automatically adds the ampersand. See the Template example results.  Only use the macro after at least one required query parameter. In the following template example, the required query parameter is ${input.AMOUNT}.

Note: Use silent formal notation: $!{variable}.
Template example

amount=${input.AMOUNT}$urlTool.optionalQueryParam(\"description\", $!{input.DESCRIPTION})

Template example results

Inputs Resolved templates

input.AMOUNT == 30

input.DESCRIPTION == potatoes

amount=30&description=potatoes

input.AMOUNT == 30

input.DESCRIPTION == ""

amount=30

Java string method macros

Use Java string methods in Velocity templates to manipulate string variables, such as changing the case of a value or extracting a value from a string. For more information, see Class String in the Java 17 documentation.

In the following example, the toUpperCase() method converts the string value of the variable $a to uppercase. The split() method splits the variable $b into an array of strings. Variable $d concatenates values from variable $a, variable $b, and the first item in the array for variable $c.

Template example

#set($a = ${input1.string1} )
#set($a = $a.toUpperCase() )
#set($b = ${input1.string2} )
#set($c = $b.split("\+") )
#set($d = "We are using ""${a}"" ""${b}"" ""$c[1]"" to render this." )
$d

Template example results

Inputs Resolved templates

input.string1 = value1

input.string2 = value1+value2

We are using "VALUE1" "value1+value2" "value2" to render this.

Microsoft Dynamics macros

msdynamics.fieldSearchFilter

This macro builds a search filter given a value and a list of fields that you want to search. The macro compares the value to each of the fields in the list.

Template example

$msdynamics.fieldSearchFilter(\"$input.EMAIL_ADDRESS\", [\"emailaddress1\", \"emailadress2\"]

Template example results

Inputs Resolved templates
input.EMAIL_ADDRESS = TestMail@example.com emailaddress1 eq 'TestMail@example.com' or emailaddress2 eq 'TestMail@example.com'

msdynamics.phoneNumberFilter

This macro builds a search filter given a phone number and a list of fields that you want to search. The macro strips unsupported characters and any non-digit values, such as + and parentheses, from the phone number and adds “or” between each field. This search filter is useful for comparing a phone number to multiple phone numbers in an account record.

Template example

$msdynamics.phoneNumberFilter(\"$input.PHONE_NUMBER\", [\"telephone1\", \"telephone2\"])

Template example results

Inputs Resolved templates
input.PHONE_NUMBER = +1 (555) 555-0123 telephone1 eq '+1 (555) 555-0123' or telephone2 eq '+1 (555) 555-0123' or telephone1 eq '15555550123' or telephone2 eq '15555550123'

Salesforce macros

salesforce.escReserved

This macro escapes reserved characters from Salesforce SOQL/SOSL queries made in a URL. Salesforce reserves the following characters: ? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -. This macro ensures that the characters are properly escaped. For more information, see FIND {SearchQuery} in the Salesforce documentation.

Template example

FIND {$salesforce.escReserved(${input.PHONE_NUMBER})} IN PHONE FIELDS

Template example results

Inputs Resolved templates
input.PHONE_NUMBER == (555) 555-5555 FIND {\(555\) 555\-5555} IN PHONE FIELDS

For more information, see About custom actions for integrations.

For more information about the integrations, see About the data actions integrations.