Skip to main content

General Information

Policy Type

policy-message-builder

Description

Message Builder policy evaluates a list of rows sequentially. Each row reads from a source (body, header, query parameter, or context) and writes the result to a target custom variable. Template mode supports JEXL expressions and multi-line scripts with loops and conditionals.

Endpoints

List Policies

GET /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/

Add Policy

POST /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

Update Policy

PUT /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

Delete Policy

DELETE /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

List Policies

Endpoint

GET /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/

Request

Headers

HeaderValue
AuthorizationBearer {token}

Path Parameters

ParameterTypeRequiredDescription
projectNamestringYesProject name
apiProxyNamestringYesAPI Proxy name

Response

Success Response (200 OK)

{
  "success": true,
  "resultList": [
    {
      "apiProxy": {
        "name": "PetAPI",
        "requestPolicyList": [
          {
            "type": "policy-message-builder",
            "name": "pet-enrichment-builder",
            "description": "Enriches pet request payload with context and custom variables",
            "active": true,
            "rowList": [
              {
                "buildMode": "TEMPLATE",
                "template": "#{body.$.name}",
                "targetVariable": {
                  "name": "petName",
                  "type": "CUSTOM"
                },
                "required": false,
                "continueOnError": true,
                "defaultValue": "unknown"
              }
            ]
          }
        ],
        "responsePolicyList": [],
        "errorPolicyList": []
      }
    }
  ],
  "resultCount": 1
}

cURL Example

curl -X GET \
  "https://demo.apinizer.com/apiops/projects/MyProject/apiProxies/PetAPI/policies/" \
  -H "Authorization: Bearer YOUR_TOKEN"

Add Policy

Endpoint

POST /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

Request

Headers

HeaderValue
AuthorizationBearer {token}
Content-Typeapplication/json

Path Parameters

ParameterTypeRequiredDescription
projectNamestringYesProject name
apiProxyNamestringYesAPI Proxy name
policyNamestringYesPolicy name

Request Body

Full JSON Body Example
The following example builds an enriched JSON payload from request body, headers, query parameters, and context variables. It also produces a nested conditional element using intermediate custom variables.
{
  "operationMetadata": {
    "targetScope": "ALL",
    "targetPipeline": "REQUEST",
    "deploy": true,
    "deployTargetEnvironmentNameList": ["production"],
    "order": 1
  },
  "policy": {
    "type": "policy-message-builder",
    "description": "Enriches pet request payload with context and custom variables",
    "active": true,
    "rowList": [
      {
        "buildMode": "TEMPLATE",
        "template": "#{body.$.name}",
        "targetVariable": {
          "name": "petName",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "unknown"
      },
      {
        "buildMode": "TEMPLATE",
        "template": "#{body.$.category.name}",
        "targetVariable": {
          "name": "categoryLabel",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": ""
      },
      {
        "buildMode": "TEMPLATE",
        "template": "#{body.$.status == 'available' ? 'AVAILABLE' : body.$.status == 'pending' ? 'PENDING' : 'SOLD'}",
        "targetVariable": {
          "name": "statusLabel",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": ""
      },
      {
        "buildMode": "TEMPLATE",
        "template": "null",
        "targetVariable": {
          "name": "nestedObject",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "null"
      },
      {
        "policyCondition": {
          "conditionRuleList": [
            {
              "conditionCriteria": "AND",
              "conditionRuleList": [
                {
                  "conditionCriteria": "VALUE",
                  "firstVariable": {
                    "type": "BODY",
                    "jsonPathValue": "$.status",
                    "messageContentType": "JSON"
                  },
                  "variableDataType": "STRING",
                  "valueComparisonOperator": "EQ",
                  "secondValueSource": "VALUE",
                  "secondValue": "available"
                }
              ]
            }
          ]
        },
        "buildMode": "TEMPLATE",
        "template": "{\"displayName\":\"#{petName} - #{categoryLabel}\",\"statusLabel\":\"#{statusLabel}\"}",
        "targetVariable": {
          "name": "nestedObject",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "null"
      },
      {
        "buildMode": "TEMPLATE",
        "template": "{\"request\":{\"headers\":{\"contentType\":\"#{header.Content-Type}\",\"xRequestId\":\"#{header.X-Request-Id}\"},\"query\":{\"format\":\"#{query.format}\"},\"body\":{\"id\":#{body.$.id},\"name\":\"#{petName}\",\"category\":{\"id\":#{body.$.category.id},\"name\":\"#{categoryLabel}\",\"nested\":#{nestedObject}},\"photoUrls\":#{body.$.photoUrls},\"tags\":#{body.$.tags},\"status\":\"#{body.$.status}\"}},\"context\":{\"httpMethod\":\"#{context.request.httpMethod}\",\"clientIp\":\"#{context.request.remoteAddress}\",\"correlationId\":\"#{context.message.correlationId}\",\"year\":\"#{context.system.year}\",\"dateTime\":\"#{context.system.dateTime}\",\"environment\":\"#{context.environment.name}\"},\"computed\":{\"operationType\":\"#{context.request.httpMethod == 'POST' ? 'create' : context.request.httpMethod == 'PUT' ? 'update' : context.request.httpMethod == 'DELETE' ? 'delete' : 'read'}\",\"summary\":\"#{petName} (#{categoryLabel}) - #{statusLabel}\"}}",
        "targetVariable": {
          "name": "enrichedPayload",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "{}"
      }
    ]
  }
}

Request Body Fields

operationMetadata
FieldTypeRequiredDefaultDescription
targetScopestringYes-Policy scope: ALL or ENDPOINT
targetEndpointstringNo*-Endpoint path (required if targetScope=ENDPOINT)
targetEndpointHTTPMethodstringNo*-HTTP method (required if targetScope=ENDPOINT)
targetPipelinestringYes-Pipeline: REQUEST, RESPONSE, or ERROR
deploybooleanNotrueWhether to deploy after adding policy
deployTargetEnvironmentNameListarrayNo[]List of environment names to deploy to
orderintegerNonullPolicy execution order (starts from 1)
Enum: targetScope
  • ALL - Policy applies to all endpoints
  • ENDPOINT - Policy applies only to specified endpoint
Enum: targetPipeline
  • REQUEST - Executes in request pipeline
  • RESPONSE - Executes in response pipeline
  • ERROR - Executes in error pipeline
Enum: targetEndpointHTTPMethod
  • GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD
policy
FieldTypeRequiredDefaultDescription
typestringYes-Policy type: policy-message-builder
descriptionstringNo-Policy description
activebooleanNotrueWhether policy is active
rowListarrayYes-List of message builder rows (at least one)
rowList[] (Message Builder Row)
FieldTypeRequiredDefaultDescription
buildModestringYes-Build mode: FORM or TEMPLATE
sourceVariableobjectYes (FORM mode)-Source variable to read the value from
targetVariableobjectYes-Target variable to write the result to
templatestringYes (TEMPLATE mode)-Template string with #{...} expressions
requiredbooleanNofalseIf true, throws an error when the source value is empty
continueOnErrorbooleanNotrueIf true, processing continues to next row when an error occurs
defaultValuestringNo-Value to use when source is empty
policyConditionobjectNo-Row-level condition; row is skipped when condition is not met
Enum: buildMode
  • FORM - Copies value directly from source variable to target variable
  • TEMPLATE - Evaluates #{...} template expressions (supports JEXL expressions and multi-line scripts)
variable (sourceVariable / targetVariable)
FieldTypeRequiredDescription
namestringYes (CUSTOM type)Variable name (used to reference in templates as #{name})
typestringYesVariable type (see EnumVariableType below)
headerNamestringYes (HEADER type)Header name (e.g., Content-Type, X-Request-Id)
paramTypestringYes (PARAMETER type)Parameter category: QUERY, PATH, or FORM
paramNamestringYes (QUERY/PATH param)Query or path parameter name
formNamestringYes (FORM param)Form field name
jsonPathValuestringYes (BODY/JSON type), Optional (CUSTOM)JSONPath expression (e.g., $.user.name, $[0].id). For CUSTOM type, extracts a specific value from the variable’s JSON content.
xpathValuestringYes (BODY/XML type), Optional (CUSTOM)XPath expression (e.g., /root/user/name). For CUSTOM type, extracts a specific value from the variable’s XML content.
messageContentTypestringYes (BODY type), Optional (CUSTOM with path)Body content type: JSON or XML. Required when using jsonPathValue or xpathValue with CUSTOM type.
contextValuestringYes (CONTEXT_VALUES type)Context value enum (see EnumVariableContextValue below)
Enum: EnumVariableType
ValueDescriptionRequired Fields
HEADERRequest or response header valueheaderName
PARAMETERQuery, path, or form parameterparamType, paramName or formName
BODYRequest or response body fieldjsonPathValue or xpathValue, messageContentType
CUSTOMCustom variable stored in the variable map. Optionally supports jsonPathValue/xpathValue with messageContentType to extract a specific value from the variable’s content.name, optionally jsonPathValue or xpathValue + messageContentType
CONTEXT_VALUESGateway context value (runtime metadata)contextValue
Enum: EnumVariableParameterType
  • QUERY - URL query parameter
  • PATH - URL path parameter
  • FORM - Form-encoded parameter
Enum: EnumMessageContentType
  • JSON - JSON body (use with jsonPathValue)
  • XML - XML body (use with xpathValue)
Enum: EnumVariableContextValue (contextValue)
ValueDescription
REQUEST_HTTP_METHODHTTP method (GET, POST, PUT, DELETE, etc.)
REQUEST_REMOTE_ADDRESSClient IP address
REQUEST_CONTENT_TYPERequest Content-Type header
REQUEST_REQUEST_URIFull request URI
REQUEST_QUERY_STRINGRaw query string
REQUEST_USERNAME_KEYAuthenticated username or API key
RESPONSE_STATUS_CODEResponse HTTP status code
MESSAGE_CORRELATION_IDUnique correlation ID assigned by the gateway
ENVIRONMENT_IDGateway environment ID
ENVIRONMENT_NAMEGateway environment name
APIPROXY_IDAPI Proxy ID
APIPROXY_NAMEAPI Proxy name
APIPROXYGROUP_IDAPI Proxy Group ID
APIPROXYGROUP_NAMEAPI Proxy Group name
APIMETHOD_IDAPI Method ID
APIMETHOD_NAMEAPI Method name
APIMETHOD_HTTPMETHODAPI Method HTTP method
APIMETHOD_ENDPOINTAPI Method endpoint path
APIMETHOD_BACKEND_HTTPMETHODBackend API method HTTP method
APIMETHOD_BACKEND_ENDPOINTBackend API method endpoint path
DATETIME_YEARCurrent year (integer)
DATETIME_MONTHCurrent month (integer, 1-12)
DATETIME_DAY_OF_WEEKDay of week (integer, 1=Monday, 7=Sunday)
DATETIME_DAY_OF_MONTHDay of month (integer, 1-31)
DATETIME_HOURCurrent hour (0-23)
DATETIME_MINUTECurrent minute (0-59)
DATETIME_SECONDCurrent second (0-59)
DATETIME_EPOCH_MILLISEpoch milliseconds since 1970-01-01T00:00:00Z
DATETIME_FORMATTED_TEXTDate-time in yyyy-MM-dd'T'HH:mm:ss.SSS'Z' format
DATE_FORMATTED_TEXTDate in yyyy-MM-dd format
TIME_FORMATTED_TEXTTime in HH:mm:ss format
CREDENTIAL_USERNAMEAuthenticated credential username
CREDENTIAL_EMAILAuthenticated credential email
CREDENTIAL_FULLNAMEAuthenticated credential full name
policyCondition
The policyCondition object defines a row-level condition. The row is skipped when the condition evaluates to false.
FieldTypeRequiredDescription
conditionRuleListarrayYesList of condition rules
conditionRule fields:
FieldTypeRequiredDescription
conditionCriteriastringYesRule type: AND, OR, NOT, or VALUE
conditionRuleListarrayYes (AND/OR/NOT)Nested list of condition rules
firstVariableobjectYes (VALUE)Left-hand side variable for comparison
variableDataTypestringYes (VALUE)Data type: STRING, NUMERIC, or DATE
valueComparisonOperatorstringYes (VALUE)Comparison operator (see below)
secondValueSourcestringYes (VALUE)Right-hand side source: VALUE (literal) or VARIABLE
secondValuestringYes (VALUE, secondValueSource=VALUE)Literal value to compare against
secondVariableobjectYes (VALUE, secondValueSource=VARIABLE)Variable to compare against
Enum: valueComparisonOperator
  • EQ - Equals
  • NE - Not equals
  • EQ_IGNORE_CASE - Equals, case insensitive (string only)
  • NE_IGNORE_CASE - Not equals, case insensitive (string only)
  • LT - Less than
  • LE - Less than or equal
  • GT - Greater than
  • GE - Greater than or equal
  • CONTAINS - String contains
  • NOT_CONTAINS - String does not contain
  • CONTAINS_IGNORE_CASE - String contains, case insensitive
  • NOT_CONTAINS_IGNORE_CASE - String does not contain, case insensitive
  • STARTS_WITH - String starts with
  • NOT_STARTS_WITH - String does not start with
  • STARTS_WITH_IGNORE_CASE - String starts with, case insensitive
  • NOT_STARTS_WITH_IGNORE_CASE - String does not start with, case insensitive
  • ENDS_WITH - String ends with
  • NOT_ENDS_WITH - String does not end with
  • ENDS_WITH_IGNORE_CASE - String ends with, case insensitive
  • NOT_ENDS_WITH_IGNORE_CASE - String does not end with, case insensitive
  • IS_EXISTS - Variable exists (regardless of value)
  • IS_NOT_EXISTS - Variable does not exist
  • IS_NOT_EMPTY - Variable exists and is not empty
  • IS_EMPTY - Variable does not exist or is empty
  • EXISTS_AND_EMPTY - Variable exists but is empty
  • IN - Value is in list
  • NOT_IN - Value is not in list
  • IN_IGNORE_CASE - Value is in list, case insensitive
  • NOT_IN_IGNORE_CASE - Value is not in list, case insensitive

Response

Success Response (200 OK)

{
  "success": true,
  "deploymentResult": {
    "success": true,
    "deploymentResults": [
      {
        "environmentName": "production",
        "success": true,
        "message": "Deployment successful"
      }
    ]
  }
}

cURL Example

curl -X POST \
  "https://demo.apinizer.com/apiops/projects/MyProject/apiProxies/PetAPI/policies/pet-enrichment-builder/" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "operationMetadata": {
      "targetScope": "ALL",
      "targetPipeline": "REQUEST",
      "deploy": true,
      "deployTargetEnvironmentNameList": ["production"],
      "order": 1
    },
    "policy": {
      "type": "policy-message-builder",
      "description": "Enriches pet request payload",
      "active": true,
      "rowList": [
        {
          "buildMode": "TEMPLATE",
          "template": "#{body.$.name}",
          "targetVariable": {
            "name": "petName",
            "type": "CUSTOM"
          },
          "required": false,
          "continueOnError": true,
          "defaultValue": "unknown"
        },
        {
          "buildMode": "TEMPLATE",
          "template": "{\"id\":#{body.$.id},\"name\":\"#{petName}\",\"status\":\"#{body.$.status}\",\"method\":\"#{context.request.httpMethod}\",\"correlationId\":\"#{context.message.correlationId}\"}",
          "targetVariable": {
            "name": "enrichedPayload",
            "type": "CUSTOM"
          },
          "required": false,
          "continueOnError": true,
          "defaultValue": "{}"
        }
      ]
    }
  }'

Update Policy

Endpoint

PUT /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

Request

Headers

HeaderValue
AuthorizationBearer {token}
Content-Typeapplication/json

Path Parameters

ParameterTypeRequiredDescription
projectNamestringYesProject name
apiProxyNamestringYesAPI Proxy name
policyNamestringYesPolicy name

Request Body

Same structure as Add Policy request body.
Full JSON Body Example
{
  "operationMetadata": {
    "targetScope": "ALL",
    "targetPipeline": "REQUEST",
    "deploy": true,
    "deployTargetEnvironmentNameList": ["production"]
  },
  "policy": {
    "type": "policy-message-builder",
    "description": "Updated: Enriches pet payload with JEXL script for tags",
    "active": true,
    "rowList": [
      {
        "buildMode": "TEMPLATE",
        "template": "#{body.$.name}",
        "targetVariable": {
          "name": "petName",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "unknown"
      },
      {
        "buildMode": "TEMPLATE",
        "template": "#{body.$.status == 'available' ? 'AVAILABLE' : body.$.status == 'pending' ? 'PENDING' : 'SOLD'}",
        "targetVariable": {
          "name": "statusLabel",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": ""
      },
      {
        "buildMode": "TEMPLATE",
        "template": "#{\n  var out = '[';\n  var first = true;\n  for (item : body.$.tags) {\n    if (!first) { out = out + ','; }\n    out = out + '{\"id\":' + item.id + ',\"label\":\"' + item.name + '\"}';\n    first = false;\n  }\n  out + ']'\n}",
        "targetVariable": {
          "name": "tagList",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "[]"
      },
      {
        "buildMode": "TEMPLATE",
        "template": "{\"name\":\"#{petName}\",\"status\":\"#{statusLabel}\",\"tags\":#{tagList},\"correlationId\":\"#{context.message.correlationId}\"}",
        "targetVariable": {
          "name": "enrichedPayload",
          "type": "CUSTOM"
        },
        "required": false,
        "continueOnError": true,
        "defaultValue": "{}"
      }
    ]
  }
}

Response

Success Response (200 OK)

{
  "success": true,
  "deploymentResult": {
    "success": true,
    "deploymentResults": [
      {
        "environmentName": "production",
        "success": true,
        "message": "Deployment successful"
      }
    ]
  }
}

cURL Example

curl -X PUT \
  "https://demo.apinizer.com/apiops/projects/MyProject/apiProxies/PetAPI/policies/pet-enrichment-builder/" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "operationMetadata": {
      "targetScope": "ALL",
      "targetPipeline": "REQUEST",
      "deploy": true,
      "deployTargetEnvironmentNameList": ["production"]
    },
    "policy": {
      "type": "policy-message-builder",
      "description": "Updated: Enriches pet payload",
      "active": true,
      "rowList": [
        {
          "buildMode": "TEMPLATE",
          "template": "#{body.$.name}",
          "targetVariable": { "name": "petName", "type": "CUSTOM" },
          "required": false,
          "continueOnError": true,
          "defaultValue": "unknown"
        }
      ]
    }
  }'

Delete Policy

Endpoint

DELETE /apiops/projects/{projectName}/apiProxies/{apiProxyName}/policies/{policyName}/

Request

Headers

HeaderValue
AuthorizationBearer {token}

Path Parameters

ParameterTypeRequiredDescription
projectNamestringYesProject name
apiProxyNamestringYesAPI Proxy name
policyNamestringYesPolicy name

Response

Success Response (200 OK)

{
  "success": true
}

cURL Example

curl -X DELETE \
  "https://demo.apinizer.com/apiops/projects/MyProject/apiProxies/PetAPI/policies/pet-enrichment-builder/" \
  -H "Authorization: Bearer YOUR_TOKEN"

Template Syntax Reference

Simple Variable Access

SyntaxDescription
#{body.$.field}JSON body field via JSONPath
#{body.$[0].field}JSON array body — first element field
#{body./root/field}XML body field via XPath
#{header.Header-Name}Request header value
#{query.paramName}URL query parameter
#{path.paramName}URL path parameter
#{form.fieldName}Form-encoded parameter
#{customVarName}Custom variable from current row chain

Region-Aware Variable Access

SyntaxDescription
#{request.body.$.field}Request body field (explicit region)
#{request.header.Name}Request header (explicit region)
#{response.body.$.field}Response body field (explicit region)
#{response.header.Name}Response header (explicit region)
#{request.body./root/field}Request body XPath (explicit region)
#{response.body./root/field}Response body XPath (explicit region)

Custom Variable Path (JSONPath/XPath on variable content)

SyntaxDescription
#{myVar.$.user.name}JSONPath on custom variable’s JSON content
#{myVar./root/element}XPath on custom variable’s XML content
#{myVar./bookstore/book[1]/title}XPath with predicate on custom variable

Context Variable Syntax

SyntaxcontextValue Enum
#{context.request.httpMethod}REQUEST_HTTP_METHOD
#{context.request.remoteAddress}REQUEST_REMOTE_ADDRESS
#{context.message.correlationId}MESSAGE_CORRELATION_ID
#{context.apiProxy.name}APIPROXY_NAME
#{context.apiMethod.httpMethod}APIMETHOD_HTTPMETHOD
#{context.system.year}DATETIME_YEAR
#{context.system.dateTime}DATETIME_FORMATTED_TEXT
#{context.environment.name}ENVIRONMENT_NAME
#{context.credential.username}CREDENTIAL_USERNAME

JEXL Expression Examples

#{body.$.price * 1.18}
#{body.$.firstName + ' ' + body.$.lastName}
#{body.$.status == 'available' ? 'IN_STOCK' : 'OUT_OF_STOCK'}
#{context.request.httpMethod == 'POST' ? 'create' : 'read'}

JEXL Script (Multi-Line) Example

#{
  var out = '[';
  var first = true;
  for (item : body.$.tags) {
    if (!first) { out = out + ','; }
    out = out + '{"id":' + item.id + ',"name":"' + item.name + '"}';
    first = false;
  }
  out + ']'
}
The return keyword is not used in JEXL Script. The value of the last evaluated expression is returned automatically.