Skip to main content

Comparison & Arithmetic Operators

You can use comparison operators within an if/else block to create dynamic responses based on incoming request parameters. In Beeceptor, comparison expressions follow a prefix-based notation, where the operator is placed before the arguments. Refer to the supported operators and their usage to craft dynamic mock responses.

Note:

  1. By default, template engine is off. You need to explicitly mark a rule to enable usage of operators and If/Else constructs.
  2. If you have a use-case for an operator that isn't listed below, please contact our Support Team. They can assist you in prioritizing your request.

Comparison Operators

eq (equals compare)

The eq (equals) operator checks if two arguments are equal, returning a boolean value. It supports both number and string data types and returns false if the types or the values don't match.

The following example demonstrates how to use the eq operator to return a specific response when both arguments are the same.

{{#if (eq 100 100)}}
This text block is always qualified for the response.
{{/if}}

You can also use the eq operator to conditionally send a response based on the value of a field in the request body. In the example below, the response block varies based on the value of stage field in the request body.

{{#if (eq (body 'stage') 1)}}
{
"message": "This JSON is qualified for the response if the stage field is sent as 1."
}
{{else}}
{
"message": "This JSON is sent if the stage field is not 1."
}
{{/if}}

Explore more operators and their usage to craft flexible and dynamic mock responses that fit your specific needs.

gt (greater than)

The gt (greater than) operator checks if the first argument is greater than the second, returning a boolean value.

The example below shows how to use the gt operator to send a conditional response based on the creditScore field in the request body. If the creditScore exceeds 700, the application status is marked as "APPROVED".

{
"applicationId": "{{faker 'random.uuid'}}",
"creditScore": {{body 'creditScore'}},
{{#if (gt (body 'creditScore') 700 )}}
"status": "APPROVED",
{{else}}
"status": "REJECTED",
{{/if}}
}

lt (less than)

The lt (less than) operator checks if the first argument is lesser than the second, returning a boolean value.

The example below shows how to use the lt operator to send a conditional response based on the creditScore field in the request body. If the creditScore is less than 700, the application status is marked as "REJECTED."

{
"applicationId": "{{faker 'random.uuid'}}",
"creditScore": {{body 'creditScore'}},
{{#if (lt (body 'creditScore') 700)}}
"status": "REJECTED",
{{else}}
"status": "APPROVED",
{{/if}}
}

Arithmetic Operations

Beeceptor supports basic arithmetic operations in response template. These operations allow you to perform calculations using numbers from request parameters or static values, enabling dynamic HTTP response for numerical data.

math-operators-add-substract-demo

add

The add operator sums a list of numbers, which can be a combination of request parameters and static values.

Example:

The following template picks price and tax values from the request payload (JSON) and computes total in the HTTP response:

{
"total": {{add (body 'price') (body 'tax') 5}}
}

When the request body is {"price": 100, "tax": 10}, the response will be:

{
"total": 115
}

Additional Examples:

  • {{add 10 5 2}}: Adds a static list of numbers (10, 5, and 2).
  • {{add (body 'price') 2}}: Combines dynamic values (e.g., from the request body) with static values in a single operation.
  • {{add '10' 5.4 (body 'price')}}: Demonstrates how you can mix data types (strings, decimals, and dynamic values).
  • {{add 'abc' 2 (queryParam 'type')}}: In this example, any invalid values (non-numeric or NaN) will be ignored and treated as zero.

subtract

The subtract operator subtracts subsequent numbers from the first number. This is useful when you need to calculate differences between values, such as remaining balance, deductions, or similar operations.

Example:

{
"remaining": {{subtract (queryParam 'balance') (queryParam 'withdrawal')}}
}

If the request URL contains ?balance=1000&withdrawal=200, the response will be:

{
"remaining": 800
}

Additional Examples:

  • {{subtract 100 25 10}}: Subtracts 25 and 10 from 100, resulting in 65.
  • {{subtract (body 'total') 5}}: Subtracts a static value from a dynamic value retrieved from the request body.
  • {{subtract (queryParam 'initial') (queryParam 'deduction') 50}}: Subtracts two dynamic values, followed by a static value.
  • {{subtract '200' 50 (body 'discount')}}: Demonstrates mixed data types, where invalid values like strings ('200') will be treated as numbers if they can be converted, or ignored if not valid.

multiply

The multiply operator multiplies a list of numbers, which can be a combination of static values or dynamic data extracted from the request.

{
"total": {{multiply (body 'quantity') (body 'unitPrice')}}
}

If the request body contains {"quantity": 10, "unitPrice": 5}, the response will be:

{
"total": 50
}

Additional Examples:

  • {{multiply 5 4 3}}: Multiplies the static values 5, 4, and 3, resulting in 60.
  • {{multiply (body 'quantity') 2}}: Multiplies a dynamic value from the request body with a static value.
  • {{multiply (queryParam 'length') (queryParam 'width') (queryParam 'height')}}: Multiplies multiple dynamic values from query parameters to calculate volume, for example.
  • {{multiply '10' 2.5 (body 'factor')}}: This example uses mixed data types, where non-numeric or invalid values will be assumed as zero.

divide

The divide operator divides the first number by subsequent numbers. It's useful for calculating ratios, averages, or percentages.

Example:

{
"average": {{divide 100 2}}
}

This divides 100 by 2, resulting in the following response:

{
"average": 50
}

Note: Division by zero will result in an error, as dividing any number by zero is undefined.

Set Operators

oneOf (random pick)

The oneOf operator selects a random item from a provided list of values. You can supply any number of values, and this operator will pick one randomly. If no values are provided, it returns an empty string.

In the example below, the operator picks a random status from a list of possible application statuses.

Template definition:

{
"status" : "{{oneOf 'draft' 'in-progress' 'approved' 'rejected' 'cancelled'}}"
}

Generated response:

{
"status": "cancelled"
}

Demo:

Date Operators

now - current time

The now operator allows you to retrieve the current date and time. Additionally, you can customize the format of the date-time output by passing a shorthand format parameter.

SyntaxDescription & Sample Output
{{now}}Current date-time, in long format
Thu Oct 10 2024 04:39:51 GMT+0000 (Coordinated Universal Time)
{{now 'utc'}}Current date-time in UTC format
2024-10-10T04:39:51Z
{{now 'iso'}}Current date-time in ISO format
2024-10-10T04:39:51.000+00:00

now - relative time

You can create custom date-time values relative to the current time by using additional parameters that specify the duration. For example, you can set the time to be 5 minutes in the future or 1 hour in the past. The duration can be defined in seconds, minutes, hours, days, months, or years, and it accepts both positive and negative whole numbers.

This feature is particularly useful when you need an API response that always returns a recent or dynamically adjusted date whenever the API is called. Below are some examples to help you customize date-time values:

SyntaxDescription & Sample Output
{{now '{minutes:5}' 'utc'}}Date-time exactly 5 minutes in the future
2024-10-10T04:44:51Z
{{now '{months:-11, days:1}' 'iso'}}Date-time exactly 11 months in the past
2023-11-11T04:39:51.000+00:00
{{now '{hours:-5, minutes:-30}' 'YYYYMMDD'}}Date with timezone adjustments
20241009
{{now '{hours:3}' 'utc'}}Date-time 3 hours in the future (in UTC)
2024-10-10T07:39:51Z
{{now '{days: 1, hours:10}' 'utc'}}Date-time 1 day and 3 hours in the future (in UTC)
2024-10-10T07:39:51Z

Note: The last parameter here is optional, and controls the output format. Refer date/time formatting for more details.

Other Operators

len

The len operator in Beeceptor calculates the length of arrays, strings, or numbers from the request payload. It is helpful for creating mock responses that needs to emit the size of input data.

Syntax

{{len (body 'parameterName')}}
  • In the above, body refers to the request payload helper.
  • The parameterName specifies the key to evaluate from the request payload/body.

Other examples:

  • {{len (faker 'string.uuid')}}: Returns 36 as the length of UUIDs.
  • {{len 'Alex'}}: Returns 4 as the size of given string.

Example

Request Payload:

{
"companyName": "Acme Corporation",
"amount": 2342432,
"listOfItems": [
{"name": "one", "description": "details about one"},
{"name": "two", "description": "details about two"},
{"name": "three", "description": "details about three"}
]
}

Mock Template:

{
"itemsCount": {{len (body 'listOfItems')}},
"companyNameLength": {{len (body 'companyName')}},
"amountSize": {{len (body 'amount')}}
}

Response Generated:

{
"itemsCount": 3,
"companyNameLength": 16,
"amountSize": 7
}