Warm tip: This article is reproduced from serverfault.com, please click

Dynamic wiremock to capture path parameter and return in response

发布于 2020-12-17 05:01:26

I am trying to create dynamic mocks using WireMock. I have a situation where if I specify URL like

http://localhost:8989/api/account/121

then I should receive response like this:

   "cycleSpecification": {
       "id": "121"
        }
  }

In brief, the path param is returned in the response body, but I am not sure how should I capture 121 and return this in the response using wiremock.

and for this kind of request

/myManagement/v1/source?filters=myParty.id==539&&myParty.role==individual

OR

/myManagement/v1/source?filters=myParty.id%3D%3D539%26myParty.role%3D%individual

what can I used so response will filter out the id and role and put in the response.

I am using standalone wiremock jar 2.27.2 to create wiremock-server.

Questioner
sagar verma
Viewed
0
agoff 2020-12-19 02:21:25

You can achieve this by using response templating. You'll need to add --global-response-templating to how you are starting up your standalone server, and then you can use response templates.

I think you'd want something like:

{
  "request" : {
    "urlPathPattern" : "/api/account/.*",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "body" : "{ \"cycleSpecification\": { \"id\": \"{{request.path.[2]}}\" } }"
  }
}

Check out the documentation on the request model for more information

For your second question, if the query parameters were sent as separate query parameters, you'd be able to reference them with the request model.

{
  "request" : {
    "urlPathPattern" : "/api/account/.*",
    "method" : "GET",
    "queryParameters": {
        "myParty.id" : {
            "matches": ".*"
        },
        "myParty.role": {
            "matches": ".*"
        }
    }
  },
  "response" : {
    "status" : 200,
    "body" : "{ \"cycleSpecification\": { \"id\": \"{{request.query.party.id}}\" } }"
  }
}

Since it doesn't look like you're query parameters are being sent separately, unfortunately, I think you'll need to create a transformer to modify your response.