Daniel
Daniel

Reputation: 5381

SoapUI REST + JSON Mock Service: How can I return data from the request in a response?

I have a SoapUI REST (i.e. non-SOAP) mock service that returns a response for a POST request. The request and response both contain JSON content.

At the moment, I can get it to return a static response and that works fine, but I want some of the values in the response to be dynamically sourced from the request.

So if I have this request:

 {
   "the_request":{
     "abc":"123",
 }

How can I get the value of "abc" copied in the response?

Investigation has lead me to believe I can do this via including a variable in the response, something like:

Response:

 {
   "the_response":{
     "value_from_request":"${#MockResponse#Request#the_request#abc}",
     "other":"stuff",
 }

And then implementing a script to populate the variable in the response, via the Script tab. How can I then populate this with data from the request?

Currently SoapUI just generates an empty value "value_from_request":"",

Tried using mockRequest.requestContent in the Script tab, but have not found how to obtain the "123" value from it.

Upvotes: 1

Views: 3640

Answers (2)

Azamat Malikov
Azamat Malikov

Reputation: 1

I think the script should be like this

def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())
context.setProperty("the_value",requestBody.the_request.abc)

Upvotes: 0

Daniel
Daniel

Reputation: 5381

OK, worked this out. So the response message can simply reference a variable in the requestContext like so:

Response:

 {
   "the_response":{
     "value_from_request":"${the_value}",
     "other":"stuff",
 }

And a groovy script can be used to parse the JSON request content and populate "the_value" or whatever you like in the requestContext:

// Parse the JSON request.
def requestBody = new groovy.json.JsonSlurper().parseText(mockRequest.getRequestContent())

// Set up "the_value" from the request message.
requestContext.the_value = requestBody.the_request.abc

// Bit of logging so can see this in the "script log" tab.
log.info "Value extracted from request: ${requestContext.the_value}"

Upvotes: 2

Related Questions