Scenario
In some cases, the value of a variable depends on the content of the incoming request. There are two approaches to conditional value assignment:
- Row Condition: Execute the row only when a specific condition is met.
- JEXL Ternary Expression: Decide which value to assign within a single row.
Approach 1: Conditional Row Execution
Row conditions allow you to execute a row only when a specific condition is true. For the “false” case, set the default value as the fallback.
Example: Different Label Based on Status
Assign ACTIVE if the status field in the request body is active, otherwise assign PASSIVE.
Row 1 — Default value (always runs):
| Field | Value |
|---|
| Build Mode | Template |
| Template | PASSIVE |
| Target | Custom Variable → statusLabel |
Row 2 — Override when condition is met:
| Field | Value |
|---|
| Row Condition | request.body.$.status == 'active' |
| Build Mode | Template |
| Template | ACTIVE |
| Target | Custom Variable → statusLabel |
Result
| Request Body | statusLabel Value |
|---|
{"status": "active"} | ACTIVE |
{"status": "passive"} | PASSIVE |
{"status": "pending"} | PASSIVE |
Approach 2: JEXL Ternary Expression
A ternary expression makes the decision within a single row using the condition ? trueValue : falseValue syntax.
Example: Operation Type Based on HTTP Method
#{context.request.httpMethod == 'POST' ? 'create' : context.request.httpMethod == 'PUT' ? 'update' : context.request.httpMethod == 'DELETE' ? 'delete' : 'read'}
Result
| HTTP Method | operationType Value |
|---|
POST | create |
PUT | update |
DELETE | delete |
GET | read |
Approach 3: Conditional JSON Part Generation
Generating an optional JSON object conditionally is one of the most powerful use cases. This is achieved by combining row conditions with custom variables.
Scenario
Include a metadata object in the body only if the type field in the request body is premium.
Row 1 — Default: empty JSON string:
| Field | Value |
|---|
| Build Mode | Template |
| Template | null |
| Target | Custom Variable → metadataBlock |
Row 2 — Override with row condition:
| Field | Value |
|---|
| Row Condition | request.body.$.type == 'premium' |
| Build Mode | Template |
| Template | {"tier":"gold","features":["analytics","support"]} |
| Target | Custom Variable → metadataBlock |
Row 3 — Final body template:
{"id":"#{body.$.id}","type":"#{body.$.type}","metadata":#{metadataBlock}}
Do not wrap #{metadataBlock} in quotes in the final template. Since the variable already contains valid JSON, adding quotes would turn it into a string, breaking the JSON structure.
Result
| Request Body | metadata Value |
|---|
{"id":1,"type":"premium"} | {"tier":"gold","features":["analytics","support"]} |
{"id":2,"type":"basic"} | null |
When using row conditions with custom variables, define the default value in the first row (without a condition). This way, if no condition matches, the variable will still have a safe default value.