how to design dynamic response in mock server

Viewed 3561

I'm now using the mock server from https://www.mock-server.com/ and run it in a docker container.

Now I would like to let the response change as request body changes. I've looked up for dynamic response on official webiste for a while, but have no idea on how to extract specific data from request body.

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
    "httpRequest": {
        "path": "/some/path"
    },
    "httpResponseTemplate": {
        "template": "return { statusCode: 200, body:  request.body };",
        "templateType": "JAVASCRIPT"
    }
}'

The code above is to create a simple expectation, which will response the request body. For example,

$curl http://localhost:1080/some/path -d '{"name":"welly"}'
{"name":"welly"}  //response

Now I want to change the way of giving the response. For example, I would like to input {a:A, b:B} and get the response {a:B, b:A}.

So, how to modify the json data in request body and give it to response? I guess there are some methods to extract specific data from json file, or modify json data, etc. Also, I want to know how to better search the detailed information, since the official website and full REST API json specification (https://app.swaggerhub.com/apis/jamesdbloom/mock-server-openapi/5.11.x#/expectation/put_expectation) is hard for me to understand.

Thanks a lot!

1 Answers

I needed to do this as well, I think I got this to work have a look at my curl example for the expectation I hope that helps:

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
"httpRequest": {
    "path": "/api/fun",
    "method": "POST"
},
"httpResponseTemplate": {
  "template": "
    req = JSON.parse(request.body.string)
    rid = req[\"id\"]
    return { statusCode: 201, body: {new_id: rid} }
  ",
  "templateType": "JAVASCRIPT"
}}'

After you do this if send:

curl -X POST http://localhost:1080/api/fun --data '{"id": "test_1"}'

it should return:

{ "new_id" : "test_1" }
Related