Hello, I wonder if it is possible to use for loop ...
# help
b
Hello, I wonder if it is possible to use for loop in response template? Something like
Copy code
{
  "request": {
    "method": "POST",
    "urlPath": "xxxx"
  },
  "response": {
    "status": 201,
    "jsonBody": {
      "items": [
       # for each item in items append the following block:
        {
          "guid": "{{randomValue type='UUID'}}",
          "code": "{{jsonPath request.body 'items.[0].code'}}"
        }
      ]
    }
  }
}
l
Hi, there is the
#each
handlebars element that might be what you are looking for. For example, with a request payload like this:
Copy code
{
  "source": "Web",
  "orders": [
    {
      "id": "Order1",
      "status": "In Progress"
    },
    {
      "id": "Order2",
      "status": "In Progress"
    },
    {
      "id": "Order3",
      "status": "In Progress"
    }
  ]
}
You can write a response body like this:
Copy code
{
  "user": "User1", 
  "orders": [ 
    {{#each (jsonPath request.body '$.orders') as |order|}} 
      {
        "id": "{{order.id}}", 
        "status": "In Progress", 
        "shipping": "Pending"
      } {{#not @last}},{{/not}}  
    {{/each}} 
  ]
}
In the example above there is also the
#not
element to make sure we are not on the last element in the
#each
loop. This allows us to add the
,
to make it valid json.
If you wanted to try this out I have a project here where it is setup - https://github.com/leeturner/wiremock-standalone-docker-example This mapping file references this body file and can be tested with this IntelliJ http request
Or if you don't use intelliJ http files this should also do the trick:
Copy code
curl -X GET --location "<http://localhost:8080/orders>" \
    -H "Content-Type: application/json" \
    -d '{
          "source": "Web",
          "orders": [
            {
              "id": "Order1",
              "status": "In Progress"
            },
            {
              "id": "Order2",
              "status": "In Progress"
            },
            {
              "id": "Order3",
              "status": "In Progress"
            }
          ]
        }'
b
Thank you so much @Lee Turner I will try it out!