I am trying to get value of TxnType from json request while mocking a response from SOAPUI. I want to respond with different responses based the value of TxnType.
{
"Request": {
"UserId": "user",
"TxnType": "fetch"
}
}
Here is the groovy script to fetch the request value with fixed json
def json = """{
"Request": {
"UserId": "user",
"TxnType": "fetch"
}
}"""
def transactionType = new groovy.json.JsonSlurper().parseText(json).Request.TxnType
log.info "TxnType is : ${transactionType}"
You may quickly try the Demo
If you want to use the dynamic json in the mock script, then you can use below mock script dispatcher
def transactionType = new groovy.json.JsonSlurper().parseText(mockRequest.requestContent).Request.TxnType
log.info "TxnType is : ${transactionType}"
// Pick Request Body
def requestBody = mockRequest.getRequestContent()
log.info "Request body: " + requestBody
// Pick TxnType value
def txnType = requestBody["TxnType"]
(or something like this)
Related
I am new to Spring Boot and I am trying to load a Json template file and replacing the placeholders with input values read from a user input file.
This is my JSON.
template.json
{
"templateId": "header",
"configurationData": {
"inboundHeaders": [
{
"key": "header1",
"value": {0}
}, {
"key": "header2",
"value": {1}
}, {
"key": "header3",
"value": {3}
}
],
"outboundHeaders": [
{
"key": "header4",
"value": {4}
}, {
"key": "header5",
"value": {5}
}, {
"key": "header6",
"value": {6}
}
]
}
}
So, here I want to replace these placeholders before sending it to remote service
public void processJson(List<String> userParams, String jsonFile){
HttpClient client = new ProductHttpClient();
mapper = new ObjectMapper();
JavaToJsonConverter converter = new JavaToJsonConverter();
RemoteServiceResponse response = null;
RequestPojo requestPojo = createRequestPojo();
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Content-Type", "application/json"));
headers.add(new BasicHeader("Authorization", "Bearer " + token.getAccessToken()));
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String jsonRequest = MessageFormat.format(jsonFile, value1, value2, value3, value4, value5, value6); // This is the problem area which I am unable to achieve
//Working code
HttpResponse httpResponse = client.postRequest(url,
converter.convertToJson(requestPojo), urlParameters, headers);
//Not Working
HttpResponse httpResponse = client.postRequest(url,
jsonRequest, urlParameters, headers);
}
Presently, I am creating POJOs from request Json and replacing the placeholders while passing the request json to remote service. Here I see following issue
I was not able to load Json file from properties file. So, I had to generate POJOs every time for different request Json, fill object with user input value and convert those POJOs back to json string and submit to remote service.
But I just want to load the json file with placeholder and replace the placeholder with the user input values. It will save the overhead of creating so many POJOs many times.
So, can any one help on this?
Thanks in advance.
After I get a token from a Post request as shown below:
{ "access_token": "12345", "expires_in": 3600, "token_type": "Bearer" }
I want to use this token in different TestSteps Headers values.
For example I have to make a GET request after I received this token and it have in the header -> Authentification : Bearer + token_value.
So can I write a GroovyScript or something to make this automatically? I'm using ReadyApi.
Regards,
Adrian
Add Script Assertion for the same step where you receive the mentioned response:
Script Assertion this fetches the values from response and creates a project property and set the retrieved value.
//Check if the response is empty or null
assert context.response, "Response is null or empty"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def token = "${json.token_type} ${json.access_token}" as String
log.info "Token will be: ${token}"
//Assing the value at project level property TOKEN
context.testCase.testSuite.project.setPropertyValue('TOKEN', token)
Now the value needs to be set as header to each outgoing request dynamically. i.e., Add Authorization header and its value for the SOAP or REST request type steps. For this, Events feature is going to be used.
Add a SubmitListener.beforeSubmit event and add the below script into it. Please follow the comments inline.
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep
//Please edit the header name as you wanted
def headerName = 'Authorization'
//a method which sets the headers
def setHttpHeaders(def headers) {
def step = context.getProperty("wsdlRequest").testStep
if (step instanceof RestTestRequestStep || step instanceof WsdlTestRequestStep) {
def currentRequest = step.httpRequest
def existingHeaders = currentRequest.requestHeaders
headers.each {
existingHeaders[it.key] = it.value
}
currentRequest.requestHeaders = existingHeaders
} else {
log.info 'not adding headers to the current step as it is not request type step'
}
}
//read the token from project properties
def token = context.expand('${#Project#TOKEN}')
//assert the value of token
assert token, "Token is null or empty"
//UPDATE from the comment to add the header to next request
if (token) {
def headerValue = [(token)]
def headers = [(headerName) : (headerValue)]
setHttpHeaders(headers)
}
import groovy.json.JsonSlurper
import groovy.json.*
def tokens=testRunner.runStepByname("Token")
def response = context.expand( '${Token#Response}' )
def JsonSlurperjsonSlurper = newJsonSlurper()
def Objectresult = jsonSlurper.parseText(response)
def access_token= result.access_token
def authorization = "Bearer "+access_token
testRunner.testCase.setPropertyValue("access_token", authorization)
I am returning the object directly in the GET request as following.
Ok(object);
and the response json is given as,
json data-->
{
"id":"1",
"name":"testname"
}
I want to add some more details to this json
-->
{
success:"true",
messageDetails:"The response is returned by the service",
data:{}
}
how to accomplish this?
can i club all the things in Ok(object) ??
You can make use of an anonymous type, for example:
object data = new { id = 1, name = "testname" };
return Ok(new
{
success = "true",
messageDetails = "The response is returned by the service",
data
});
I'm trying to make request to facebook REST APIs and in return getting a JSON Response. I'm able to collect the response in REST client, hence I know the requestUrl I'm using while creating HttpRequest in following code is correct. But when I try to mimick the GET using akka-http javadsl, I'm unable to understand how to extract the json from the ResponseEntity.
final HttpRequest request = HttpRequest.GET(requestUrl);
final Materializer materializer = ActorMaterializer.create(this.context.getActorSystem());
final CompletionStage<HttpResponse> responseFuture =
Http.get(this.context.getActorSystem()).singleRequest(request, materializer);
final HttpResponse response = responseFuture.toCompletableFuture().get();
I'm expecting a response something as follows -
{
"data": [
{
"cpc": 9.7938056680162,
"clicks": "247",
"impressions": "15949",
"spend": 2419.07,
"date_start": "2016-06-15",
"date_stop": "2016-08-13"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
}
You should get response entity from response by calling ResponseEntity entity = response.entity() and after that call entity.toStrict(timeoutMillis, materialiser).data.decodeString("UTF-8") to get body string
You can lookup signatures of those methods in official API documentation
I'm using Bee Client as the http-client for my project and I would like to know how can I make a POST request passing a JSON as the body of my request.
I'm using KairosDB as database and I need to query data from http://localhost:8080/api/v1/datapoints/query. KairosDB expects a POST request within the following body:
{
"start_relative": {
"value": "5",
"unit": "years"
},
"metrics": [
{ "name": "DP_391366" },
{ "name": "DP_812682" }
]
}
How can I achieve a call like that using Bee Client? I've searched for the Bee Client and I didn't find how to pass a JSON string as a body of POST or GET requests, just other arguments (like map).
Please, note that this's a self-answered question.
After search almost the whole Bee Client API and part of it's documentation, I've found this small code example from Bee Client documentation that answers the question (check "Making PUT requests section).
1) Import the following modules:
import uk.co.bigbeeconsultants.http._
import uk.co.bigbeeconsultants.http.request.RequestBody
import uk.co.bigbeeconsultants.http.response.Response
import uk.co.bigbeeconsultants.http.header.MediaType._
import java.net.URL
2) After that, it's simple as that:
// Creating our body within a JSON string.
val jsonBody = RequestBody("""{ "x": 1, "y": true }""", APPLICATION_JSON)
// Making the POST request passing the JSON as body of the request.
val httpClient = new HttpClient
val response: Response = httpClient.post(new URL(query_url), Option(jsonBody))
// Print to check the status of the request.
println(response.status)
println(response.body.asString)
If you want a real case example to better understand how it works, I've made the following code with a little help from PlayJSON:
import uk.co.bigbeeconsultants.http._
import uk.co.bigbeeconsultants.http.request.RequestBody
import uk.co.bigbeeconsultants.http.response.Response
import uk.co.bigbeeconsultants.http.header.MediaType._
import java.net.URL
import play.api.libs.json._
object SimpleApp {
def main(args: Array[String]) {
// Creating JSON
val query_url = "http://localhost:8080/api/v1/datapoints/query"
val json: JsValue = Json.parse("""
{
"start_relative": {
"value": "5",
"unit": "years"
},
"metrics": [
{
"name": "DP_391366"
},
{
"name": "DP_812682"
}
]
}
""")
val jsonBody = RequestBody(Json.stringify(json), APPLICATION_JSON)
// Making API call
val httpClient = new HttpClient
val response: Response = httpClient.post(new URL(query_url), Option(jsonBody))
println(response.status)
println(response.body.asString)
}
}
Hope it helps!