How to return request body in a field in response using Wiremock - wiremock

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"
}

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"]
}
}

Related

Wiremock using request templating causes parsing error

I'm trying to use Wiremock Request Templating to generate a response from my request body.
I am unable to replace the newlines that are generated from the jsonPath helper, due to an open issue with Handlebars.java, I have had to resort to a strange hack to remove newlines. This works as expected, but when Wiremock attempts to deal with my request I get an error:
"Unexpected character ('f' (code 102)): was expecting comma to separate Object entries\\n at [Source: (String)\\"{\\"id\\":\\"05325128-01d8-406d-8067-4e8b587a8983\\",\\"person\\":{\\"crn\\":\\"C461082\\",\\"name\\":\\"Sherri Durgan IV\\",\\"dateOfBirth\\":\\"2022-08-31\\",\\"sex\\":\\"Female\\",\\"status\\":\\"InCustody\\",\\"nomsNumber\\":\\"NOMS662\\",\\"nationality\\":\\"Honduras\\",\\"religionOrBelief\\":\\"Buddhist\\",\\"prisonName\\":\\"HMP Emmerich Camp\\"},\\"data\\":\\"{ \\"foo\\" : \\"4%:S2lL$3G\\", \\"bar\\" : \\"+O}btr`,yM\\", \\"bike\\" : \\"'dn+#T;7[s\\", \\"a\\" : 65468, \\"b\\" : \\"mpVql:uMx.\\", \\"name\\" : \\"C'i,+5o{8Y\\", \\"prop\\" : \\"%tEqU;an:]\\", \\"basic-information\\" : { \\"sentence-type\\" : { \\"sentenceTyp\\"[truncated 31 chars]; line: 1, column: 286]"
Here's my request:
{
"request": {
"method": "PUT",
"url": "/applications/some-uuid",
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json;charset=UTF-8"
},
"jsonBody": {
"data": "{{{urlEncode (replace(urlEncode (jsonPath request.body '$.data')) '%0A' '') decode=true}}}",
},
"transformers": ["response-template"]
}
}
Any pointers gratefully received!

Implement different response with WireMock when no request(s) match

I'm trying to stub a RESTful API. One of the resources return the details when the resource is (indeed) found, or an HTTP 404 (Not Found) when, eventually, there is no resource for the given URL.
This is my simplified stub/mapping:
{
"mappings": [
{
"name": "Retrieve Items",
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
},
"response": {
"bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
"headers": {
"content-type": "application/json"
},
"status": 200
}
}
]
}
Then I have several JSON files (in /home/wiremock/__files/items-api/responses/retrieve/ to match the requests against — but I can't find a way to implement the HTTP 404 (Not Found) scenario:
{
"timestamp": {{ now }},
"status": 404,
"error": "Not Found",
"message": null,
"path": "{{ request.path }}"
}
With this config I get back (the expected, but not useful for my use case) response from WireMock that the file name uuid-sent-in-request.json is not found.
Is there a way to implement this behavior currently?
Tom's answer will work as well. I think the benefits to his solution are that they aren't tied to specific request URLs, but my suggestion is to have a specific mapping for the files that will match with their specific JSON files, and a catch-all mapping for un-matched files. By assigning the requests with JSON responses a higher priority, WireMock will check those first, and if the request does not match any of the values specified in that mapping, will then go on to check if the second mapping matches, and return a 404.
{
"mappings": [
{
"name": "Retrieve Items - Success",
"priority": 1, // arbitrary number lower than the second priority
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/(UUID1|UUID2|UUID3|UUID4)"
},
"response": {
"bodyFileName": "items-api/responses/retrieve/{{ request.pathSegments.[2] }}.json",
"headers": {
"content-type": "application/json"
},
"status": 200
}
},
{
"name": "Retrieve Items - 404 Not Found",
"priority": 5, // arbitrary number that is higher than 1
"request": {
"headers": {
"accept": {
"caseInsensitive": true,
"equalTo": "application/json"
}
},
"method": "GET",
"urlPathPattern": "/api/items/[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"
},
"response": {
"status": 404
}
}
]
}
Currently you would need to write a ResponseDefinitionTransformer to get the behaviour you're looking for.
It would need to check whether the ResponseDefinition passed in the parameter required a file, then if so check whether the file exists by doing something like:
try {
fileSource.getBinaryFileNamed(bodyFileName).readContents();
} catch (FileNotFoundException e) {
return WireMock.notFound().withBody("custom body");
}
// Otherwise return the unmodified response definition

WireMock set optional Parameters possibly?

i am very new here. I look up to setup die optional parameters in my Pattern. I have already read the documentary WireMock, but I have not found anything suitable.
My question is, can I query the parameters in any order =?
The next one would is ,y caseInsensitive doesn't work. I dont know why.
{
"priority": 1,
"request": {
"method": "GET",
"headers": {
"Content-Type": {
"equalTo": "application/json",
"caseInsensitive": true
}
},
"urlPattern": "/example\\?name=([a-zA-Z0-9]*)&id=([a-zA-Z0-9]*)"
},
"response": {
"status": 200,
"bodyFileName": "example/test.json"
}
}
As you've written your urlPattern, the query parameter matching is not order indifferent. If you want the query parameters to indifferent, you'd need to do something like...
{
"priority": 1,
"request": {
"method": "GET",
"headers": {
"Content-Type": {
"equalTo": "application/json"
}
},
"urlPath": "/example",
"queryParameters": {
"name": {
"matches": "([a-zA-Z0-9]*)"
},
"id": {
"matches": "([a-zA-Z0-9]*)"
}
}
},
"response": {
"status": 200,
"bodyFileName": "example/test.json"
}
}
The result of the query comes back the same answer.
i want, if i call my request, that the order of Parameters doesn't matter.
example Request: /example?name=max&id=01
example2 Request: /example?id=01&name=max
it should be get same Response.
And it should be case-insensitive.

Wiremock how to map a 302 response in JSON for standalone run

In wiremock, if you are using it for testing, you can programately return 302 using temporaryRedirect(String destination) with a detination path
stubFor(post(urlEqualTo("/firsturl"))
.willReturn(temporaryRedirect("https://somehost:8080/test/")))
My question is: How can I do the same in standalone running mode, using json mapping file
{
"request": {
"method": "POST",
"url": "/api/test"
},
"response": {
"status": 302,
????? <- how to return the path?
}
}
Was not able to find anything about this.
If you want to redirect to a separate url, you can use the WireMock's proxying functionality.
It would look something like...
{
"request": {
"method": "POST",
"url": "/api/test"
},
"response": {
"status": 302,
"proxyBaseUrl": "https://somehost:8080/test/"
}
}
temporaryRedirect("https://somehost:8080/test/") is a wrapper around aResponse().withStatus(302).withHeader(LOCATION, "https://somehost:8080/test/")
In json configuration it will be:
{
"request": {
"method": "POST",
"url": "/api/test"
},
"response": {
"status": 302,
"headers": {
"Location": "https://somehost:8080/test/"
}
}
}

Wiremock Capture path param and return in the response body

I am trying to create dynamic mocks using WireMock. I have a situation where if I specify URL like :
http://localhost:8089/api/account/abc#abc.com
then I should receive response like:
{
"account" : "abc#abc.com"
}
In brief, the path param is returned in the response body. I am able to make the request URL generic by using urlPathPattern set to /api/account/([a-z]*) however, I am not sure how should I capture abc#abc.com and return this in the response using regular expressions.
In WireMock the regular expressions can be used to recognize the email format in the Request Matching. For the purpose of this example I used a very crude example. Your production implementation may require a more robust approach.
This request:
http://localhost:8181/api/account/someone#somewhere.net
Is matched by this rule:
{
"request": {
"method": "GET",
"urlPathPattern": "/api/account/([a-z]*#[a-z]*.[a-z]*)"
},
"response": {
"status": 200,
"jsonBody": {
"account": "{{request.path.[2]}}"
},
"transformers": ["response-template"],
"headers": {
"Content-Type": "application/json"
}
}
}
And returns this response:
{
"account": "someone#somewhere.net"
}
It makes use of a Response Template processing functionality in WireMock. The Request Model variables [{{request.path.[2]}}] can be used to obtain sections from the request.
The same can be done using WireMock.Net - Response-Templating
The rule looks like:
{
"Request": {
"Path": {
"Matchers": [
{
"Name": "RegexMatcher",
"Pattern": "^/api/account/([a-z]*#[a-z]*.[a-z]*)$"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"BodyAsJson": {
"account": "{{request.PathSegments.[2]}}"
},
"UseTransformer": true,
"Headers": {
"Content-Type": "application/json"
}
}
}