Handling Arrays with Template Engine
Beeceptor’s powerful template engine enables you to access, manipulate, and transform arrays in incoming requests. Whether you need to reference specific elements or dynamically handle arrays of varying lengths, Beeceptor makes it easy to simulate real-world API responses.
Accessing using array element using index
For structured data like order line items, you can access specific elements of an array using their index. Here is an example for index-based access where first item's ID is fetched and returned in the response.
Request payload:
{
"line_items": [
{
"id": 110,
"name": "Tiger Tail Pack",
"quantity": 1,
"total": 60
}
]
}
Mock template used:
{
"products": [
{
"productId": "{{body 'line_items.0.id'}}",
"quantity": {{body 'line_items.0.quantity'}},
"price": {{body 'line_items.0.total'}}
}
]
}
Response generated by Beeceptor:
{
"products": [
{
"productId": "110",
"quantity": 1,
"price": 60
}
]
}
Dynamic arrays and transformations
When your request includes arrays of varying lengths, Beeceptor's dynamic templating allows you to process each element and generate responses that align with the input array's size and structure.
Example: Array transformation
You might come across a mocking use case where the response needs to include the exact same list of items as the request payload but with additional properties. For instance, in the following request, listOfItems contains two elements, and the mocked response is expected to mirror this list.
Request payload:
{
"listOfItems": [
{ "name": "Item A", "description": "Details A" },
{ "name": "Item B", "description": "Details B" }
]
}
Mock template used:
[
{{#each (body 'listOfItems')}}
{
"rank": {{@index}}, "title": "{{this.name}}", "details": "{{this.description}}", "id": "{{faker 'string.uuid'}}"
}{{#unless @last}},{{/unless}}
{{/each}}
]
Here,
- the
#eachblock is used to iterate over the array, ensuring the output matches the input's size while transforming its structure. - the
#unlesshelper prevents an extra comma from appearing after the last element. - the
@lastvariable returnstrueonly during the final iteration of the#eachloop, enabling conditional logic for the last element and preventing trailing comma.
Response generated by Beeceptor:
[
{
"rank": 0, "title": "Item A", "details": "Details A", "id": "6cb538c6-021a-493e-a498-1d7b314093e1"
},
{
"rank": 1, "title": "Item B", "details": "Details B", "id": "274ba54a-659a-42eb-b404-61e5fcd88454"
}
]
Special variables with #each
{{@index}}: This emits the current index of the element, starting from 0.{{@first}}: Returns booleantrueif the current element is the first in the array. Else, returnsfalse.{{@last}}: Returns booleantrueif the current element is the last in the array.
Computing array length
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,
bodyrefers to the request payload helper. - The
parameterNamespecifies the key to evaluate from the request payload/body.
Other use-cases for len operator:
{{len 'Alex'}}: Returns 4 as the size of given string.{{len (faker 'string.uuid')}}: Returns 36 as the length of UUIDs.
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
}
Use-cases for dynamic arrays
- Matching Input Array Sizes: Simulate APIs that return responses of the same length as the input. For example, translating a list of user IDs to detailed profiles.
- Enriching Input Data: Add metadata or transform data formats dynamically. For example, attach unique identifiers or timestamps to each input item.
- Variable Data Structures: Handle requests with unpredictable array sizes. For example, generate invoices with a flexible number of line items.