2

I have a JSON request as below:

{
    "fieldOne": 12345,
    "fieldTwo": 1234,
    "fieldThree": "2019-12-05T12:32:42.323905",
    "fieldFour": "string",
    "fieldFive": 5432,
    "fieldSix": "string",
    "fieldSeven": "string",
    "fieldEight": "string"
}

I need to send the complete request JSON object inside a field in response. My Wiremock stub JSON is,

{
  "request": {
    "method": "POST",
    "urlPath": "/endpoint"
},
  "response": {
    "status": 200,
    "jsonBody": {
      "request": "{{{request.body}}}", //If I remove quotes here then I get error so I added the quotes
      "anotherField": "string"
    },
    "headers": {
      "Content-Type": "application/json;charset=UTF-8"
    },
    "transformers": ["response-template"]
  }
}

How can I send request body in a field in response?.

I now get error:

    Illegal unquoted character ((CTRL-CHAR, code 10)): 
has to be escaped using backslash to be included in string value\n at [Source: (

Edit:-

I was using wiremock 2.19.0 version which is causing this issue. I upgraded the version to 2.21.0 and now the issue is resolved

But in the response I still have the below problem where the request body is within double quotes which is an invalid JSON. Response:-

{
    "request": "{ //Here the double quotes should not be present before curly brace
        "fieldOne": 12345,
        "fieldTwo": 1234,
        "fieldThree": "2019-12-05T12:32:42.323905",
        "fieldFour": "string",
        "fieldFive": 5432,
        "fieldSix": "string",
        "fieldSeven": "string",
        "fieldEight": "string"
    }",
    "anotherField": "string"
}
firstpostcommenter
  • 2,328
  • 4
  • 30
  • 59
  • https://github.com/tomakehurst/wiremock/issues/891 – firstpostcommenter Dec 26 '20 at 19:57
  • one option is to retrieve each field in the request json using `jsonPath` handlebar helper like this:- `{ "request": { "fieldOne": {{jsonPath request.body '$.fieldOne'}}, "fieldTwo": 1234 }, "anotherField": "string" }` but even in this case this will work for string but not working for number – firstpostcommenter Dec 27 '20 at 14:59
  • https://stackoverflow.com/questions/76455655/wiremock-how-to-include-request-json-body-into-the-response-body/76470633#76470633 This answer helped me. – Zahid Khan Jul 21 '23 at 13:38

1 Answers1

2

Use body instead of jsonBody. Then the response message(the content present within double quotes in body) can be formatted in whatever way required.

This will work with wiremock 2.19.0 version as well

{
  "request": {
    "method": "POST",
    "urlPath": "/endpoint"
},
  "response": {
    "status": 200,
    "body": "{\"request\": {{{request.body}}}, \"anotherField\": \"string\" }",
    "headers": {
      "Content-Type": "application/json;charset=UTF-8"
    },
    "transformers": ["response-template"]
  }
}
firstpostcommenter
  • 2,328
  • 4
  • 30
  • 59