Expressions Syntax¶ Synapse Expressions are identified by the enclosing ${} syntax. ${expression} By default, Synapse Expressions returns a valid JSON result. When working with XML payloads, we can use the XPATH function which returns an XML result. The main building blocks of Synapse Expressions are expressions and parameters. Each expression can just be a parameter or an expression which combines multiple parameters. We can chain the above building blocks to create complex expressions required by integration use cases. Note For the rest of this document, we will refer to the Synapse Expression without the enclosing ${}. Note We have a dedicated sample in the MI for VS Code extension to demonstrate each of the following sections. You can deploy the sample in WSO2 Integrator: MI and follow along by invoking the relevant resources to see the results. Literals¶ Literals are constant values that are directly used in the expression. The following types of literals are supported in Synapse expressions. Literal Type Example String "Hello World" Number 123.4 Boolean true Null null Note Refer the sample to test the literals. Accessing values¶ Synapse expression has six top level access operators and some of them are branched out to access nested values. Access values in payloads¶ Synapse expressions allow direct access to payload content using the payload or the $ prefix. payload.students $.orders payload.user["first name"] Note Use the bracket notation ["first name"] when the key contains spaces, special characters, or reserved words. Access variables¶ Variables defined using the variable mediator, are accessed using the vars prefix. vars.name vars.totalPrice vars["last name"] Access transport headers¶ Transport headers can be accessed using the headers prefix. headers.Host headers["Content-Type"] Access properties¶ Properties scoped to Synapse or Axis2 can be retrieved using the properties or props (shortened) prefix. props.synapse.propertyName properties.axis2.propertyName Access query and path parameters¶ Query and path parameters are available through the params prefix. params.queryParams.queryParamName params.pathParams.pathParamName Access function parameters¶ Function parameters used in templates are available through the params prefix. params.functionParams.paramName Access config parameters¶ Config parameters are accessed via the configs prefix with the property name. configs.configName For more information about Config parameters, see Injecting Parameters. Note Refer the sample to test accessing values. Operators¶ Synapse expressions support arithmetic, comparison, and logical operators between operands. Arithmetic operators¶ Addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) operators are supported between operands. vars.num1 + vars.num2 vars.num1 - vars.num2 vars.num1 * vars.num2 vars.num1 / vars.num2 vars.num1 % vars.num2 Comparison operators¶ Greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (==), and not equal to (!=) operators are supported between operands. vars.num1 > vars.num2 vars.num1 < vars.num2 vars.num1 >= vars.num2 vars.num1 <= vars.num2 vars.num1 == vars.num2 vars.num1 != vars.num2 Logical operators¶ Logical AND (&&) and Logical OR (||) operators are supported between operands. vars.boolValue1 and vars.boolValue2 vars.boolValue1 && vars.boolValue2 vars.boolValue1 or vars.boolValue2 vars.boolValue1 || vars.boolValue2 When using operators, it's possible to use brackets to group expressions and enforce precedence. (vars.num1 + vars.num2) * vars.num3 vars.boolValue1 && (vars.boolValue2 || vars.boolValue3) (vars.num1 + 5) > vars.num2 && (vars.num3 - 3) < vars.num4 Note Refer the sample to test operators. Conditional expressions¶ Synapse Expressions support conditional expressions using the ternary operator with the following syntax. conditional expression ? true expression : false expression Here, true expression will be evaluated if the conditional expression is true, otherwise, the false expression will be evaluated. Example usage: vars.age > 18 ? "Adult" : "Child" vars.num1 > vars.num2 ? vars.num1 : vars.num2 Note Refer the sample to test conditional expressions. Filter expressions¶ Filter expressions are used to filter arrays based on a condition. The filter expression is enclosed within square brackets and the condition is specified within the brackets. Note Filter expressions have the same syntax as JSONPath filter expressions (with the added functionality of injecting parameters using access expressions) and internally also use the JSONPath engine to evaluate the filter expression. Example usage: Selects users with age greater than or equal to 18: payload.users[?(@.age >= 18)] Selects users with age greater than or equal to the value of the minAge variable: payload.users[?(@.age >= vars.minAge)] Note Refer the sample to test filter expressions. Functions¶ Synapse Expressions support a wide range of functions that are essential for integration use cases. String functions¶ The following functions are applicable when the value is a string. Function Name Syntax Description length length("text") length(payload.array) Returns the length of the string if the input is a string. Returns the length of the array if the input is a JSON array. toUpper toUpper("text") toUpper(payload.value) Converts the provided string to uppercase. toLower toLower("TEXT") toLower(payload.value) Converts the provided string to lowercase. subString subString(payload.value, 2) subString("text", 0, 2) Extracts a substring from the input string starting from the specified index. Specify an end index as third parameter to extract up to that position. startsWith startsWith("text", "te") startsWith(payload.value, "start") Checks if the string starts with the specified prefix. endsWith endsWith("text", "xt") endsWith(payload.value, "end") Checks if the string ends with the specified suffix. contains contains("text", "e") contains(payload.value, "substring") Checks if the string contains the specified substring. trim trim(" text ") trim(payload.value) Removes leading and trailing whitespace from the string. replace replace("text", "t", "r") replace(payload.value, "old", "new") Replaces all occurrences of the specified old value with the new value in the string. split split("a,b,c", ",") split(payload.value, ";") split(payload.value, "[.]") Splits the string into an array using the specified delimiter. The delimiter is interpreted as a Java regular expression. For example, use [.] to split a string using a literal period (.) as the delimiter. charAt charAt("text", 1) charAt(payload.value, 3) Returns the character at the specified index in the string. indexOf indexOf("text", "e") indexOf(payload.value, "text", 5) Returns the position of the first occurrence of the specified input in the string. Specify a starting index as the third parameter (indexOf search begins after this position). Numerical functions¶ The following functions are applicable when the value is a number. Function Name Syntax Description abs abs(-5) abs(payload.value) Returns the absolute value of the input. floor floor(3.7) floor(payload.value) Returns the largest integer less than or equal to the input value. ceil ceil(3.2) ceil(payload.value) Returns the smallest integer greater than or equal to the input value. sqrt sqrt(16) sqrt(payload.value) Returns the square root of the input value. log log(10) log(payload.value) Returns the natural logarithm (base e) of the input value. pow pow(2, 3) pow(payload.base, payload.exponent) Returns the result of raising the base to the power of the exponent. round round(2.7543) round(2.7543, 2) round(payload.value, payload.decimalPlaces) Round the number to the given decimal places Encode and decode functions¶ Synapse expressions provide XPath functions to encode and decode strings. Function Name Syntax Description base64encode base64encode("text") base64encode(payload.value, "ISO-8859-1") Encodes the input value using Base64 encoding. Encodes the input value using Base64 encoding with the specified character set. base64decode base64decode("dGV4dA==") base64decode(payload.encodedValue) Decodes a Base64-encoded value to its original form. urlEncode urlEncode("text with spaces") urlEncode(payload.value) Encodes a string to make it safe for inclusion in a URL. urlDecode urlDecode("text%20with%20spaces") urlDecode(payload.value) Decodes a URL-encoded string to its original form. Type checking functions¶ Synapse Expressions include the following type checks to validate the type of the input value before evaluating expressions on them. Function Name Syntax Description isNumber isNumber(payload.value) Checks if the input value is a number. isString isString(payload.value) Checks if the input value is a string. isArray isArray(payload.array) Checks if the input value is an array. isObject isObject(payload.object) Checks if the input value is an object. Type conversion functions¶ Synapse Expressions include the following type conversion functions to convert the input value to the specified type. Function Name Syntax Description integer integer(payload.value) Converts the input value to an integer. float float(payload.value) Converts the input value to a floating-point number. string string(payload.value) Converts the input value to a string. boolean boolean(payload.value) Converts the input value to a boolean. object object(payload.value) Converts the string representation of a JSON object to a JSON object. After conversion, JSONPath syntax can be used to access the object. For example, object(value).students..* array array(payload.value) Converts the string representation of a JSON array to a JSON array. After conversion, JSONPath syntax can be used to access the array. For example, array(value)[3].name Registry functions¶ Synapse expressions include the following functions to access registry content and registry properties. Syntax Description registry("gov:/config/service") registry(payload.path) Accesses the registry value at the specified path. registry("gov:/config/service").property("key") registry(payload.path).property("key") Accesses the registry property at the specified path with the provided key. registry("gov:/config/resource").student.name registry(payload.path).student.name Accesses the JSON payload inside the registry resource at the specified path. Supported only for JSON resources in registry. Date time functions¶ Synapse expressions include the following functions to work with date and time. Function Name Syntax Description now now() Returns the current time in milliseconds since the Unix epoch. formatDateTime formatDateTime("29-09-1988", "dd-MM-yyyy", "yyyy MMM dd") formatDateTime(now(), "yyyy-MM-dd") Transforms the input date/time from the specified old format to the new format. Accepts string inputs or results from now(). Fetch secrets¶ Synapse expressions can be used to fetch secrets from the default secure-vault and the hashicorp vault. Syntax for fetching secrets: wso2-vault('alias') hashicorp-vault('pathName','fieldName') hashicorp-vault('namespace', 'pathname','fieldname') Example usage: <variable name="password" expression="${wso2-vault('mysqlpassword')}"/> Check exists function¶ Synapse Expressions include the following function to check if a property exists. Syntax for checking if a property exists: exists(value) Example usage: <variable name="var1" expression="${exists('vars.notMandatoryProperty') ? vars.notMandatoryProperty : 'default' }"/> Invert function¶ Not function can be used to invert a boolean value. Syntax for inverting a boolean value: not(value) Example usage: <variable name="var1" expression="${not(payload.booleanValue)}"/> Note Refer the sample to test functions. XPath functions¶ Synapse expressions provide XPath functions to work with XML payloads. Syntax for calling an XPath function without namespaces: xpath(expression) Example usage: Calling an XPath function without namespaces: <variable name="StudentName" expression="${xpath('//student/text()')}"/> Example usage: Calling an XPath function with namespaces: <variable name="Width" expression="${xpath('//a:parent/b:child/a:value/text()')}" xmlns:a="http://namespaceA.com" xmlns:b="http://namespaceB.com"/> Syntax for calling an XPath function on a variable: xpath(expression, 'variable-name') Example usage: <variable name="StudentName" expression="${xpath('//student/text()', 'Students')}"/> Note Refer the sample to test XPath functions. Reserved keywords¶ The following keywords are reserved in Synapse expressions and cannot be used in value access expressions with dot notation. Instead, use the bracket notation. contains in nin subsetof size empty empty true empty false Best practices¶ SynapsePath provides a fault tolerance design which avoids disruptive failures. In case of an error in a complex expression, it fails in the first evaluation without propagating the invalid result to the rest of the evaluation steps. For example: 45 == ( $["null"] ? vars.num1 : vars.num2) When we evaluate the above expression, it will try to parse the value of $["null"] to a boolean. If its true it will compare 45 with vars.num1, otherwise it will compare 45 with vars.num2. If $["null"] is not a boolean, the evaluation will not throw any exceptions, but will return an empty result. We need to carefully handle these empty results, when the data we take as inputs are not guaranteed to be valid. Check for null values¶ When accessing values from a JSON payload, it is important to check for null values before performing operations on them. vars.num1 == null ? vars.num2 : vars.num1 "Hello " + ( exists($.student.lastName) ? $.student.firstName + " " + $.student.lastName : $.student.firstName ) Use brackets for complex expressions¶ When using multiple operators in an expression, it is recommended to use brackets to group expressions and enforce precedence. (vars.num1 + vars.num2) * vars.num3 Check data types¶ When performing operations on values, it is important to check the data type of the values to avoid unexpected results. isNumber(vars.num1) ? vars.num1 * 2 : 0 Check expression results¶ As described above, Synapse expressions return an empty result if an error occurs during evaluation. Therefore, it is important to check for empty values before proceeding with further operations.