Can't extract data from RESTClient response - groovy

I am writing my first Groovy script, where I am calling a REST API.
I have the following call:
def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' )
That returns:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
I am trying to get the field level, like this:
def level_value = client.get( path : 'msr/data/level' )
However, when I print the value of the variable obtained:
println level_value.getData()
I get the whole JSON object instead of the field:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
So, what am I doing wrong?

Haven't looked at the docs for RESTClient but like Tim notes you seem to have a bit of a confusion around the rest client instance vs the respons object vs the json data. Something along the lines of:
def client = new RESTClient('http://myServer:9000/api/resources/?format=json')
def response = client.get(path: 'msr/data/level')
def level = response.data[0].msr[0].data.level
might get you your value. The main point here is that client is an instance of RESTClient, response is a response object representing the http response from the server, and response.data contains the parsed json payload in the response.
You would need to experiment with the expression on the last line to pull out the 'level' value.

Related

How to POST a single parameter as JSON in FastAPI?

I have a working model using transformers pipeline and I want to use it with FastAPI to send post requisitions and get the response.
The model works this way:
#Loading the model
classifier = pipeline(path_to_model)
#Making predictions:
classifier(txt)
The output is a list of dicts.
My code is:
app = FastAPI()
#app.post("/predictions")
def extract_predictions(text):
text = text.lower()
out=classifier(text)
return {
"text_message": text,
"predictions": out
}
I can get predictions if I use localhost:8000/docs, but when I use postman or insominia and body(JSON) {"text":"any string"} I get "field_required"
The model takes a string as an input and my postman request uses a JSON body. How can I update model to get the input as JSON?
The text attribute, as is currently defined, is expected to be a query parameter, not body (JSON) parameter. Hence, you can either send it as a query parameter when POSTing your request, or define it using Body field (e.g., text: str = Body(..., embed=True)), so that is expected in the body of the request as JSON. Please have a look at the answers here and here for more details.

How to get the result from API not only the response code

I am trying to get the result of foreign currency exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200 but no exchange rates are there
def main():
res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
if res.status_code!=200:
raise Exception("Error : APIdidn't work")
print(res)
Expected result:
{
"success":true,
"timestamp":1559223544,
"base":"INR",
"rates":{
"USD":0.014,
}
}
Actual result :
<Response [200]>
To use the data that you're pulling from the API - you need to convert it to readable json. DeepSpace is correct - you need to use res.json()
Append the data to a variable if you want to iterate through it or utilize it further.
data = res.json()

How to pass params to a HTTP request (teststep) in a SOAP UI Test case using groovy and run it

I am writing a groovy script to execute/automate my test suite. In one test case i have a HTTPRequest where i have a request URL, parameters( username and password) and method( GET) to get a token-id and then i would pass that token id to my next step( a SOAP request)to get the data.
I am stuck at a point where i need to pass the params(username and password), request URL and method(GET) using groovy.
I have a test step created manaully under a test case, i just need to pass the params
as i search online i got to know how to pass headers,url to a SOAP request which is like below
def headers = new StringToStringMap()
testRunner = new com.eviware............WsdlTestCaseRunner(myTestCase,null);
testStepContext = new com.eviware.soapui........WsdlTestRunContext(testsetp);
headers.put("apikey", "abcd")
teststep.getTestRequest().setRequestHeaders(headers)
teststep.getHttpRequest().setEndpoint(encpointurl);
testsetp.run(testRunner ,testStepContext )
but i looking to know how to pass params to a http request(test step) and run it.
Add a Properties teststep to your testcase. Just let it keep the default "Properties" name.
Add the properties to the Properties teststep, that you need to transfer
Inside your groovy teststep, you may set the properties using something like:
def properties = testRunner.testCase.getTestStepByName("Properties");
properties.setPropertyValue("name", "value");
Add the parameters directly in your request using variables in the format ${Properties#name} and replace "name" with the actual parameter name. This can be done both in the request body and in the URL if you should wish to do so.
It can be done completely in groovy by using groovy.json.JsonBuilder Class.
def body = new StringToStringMap()
def jsonbildr = new JsonBuilder()
body.put("username","Hackme")
body.put("password","LockUout")
def root = jsonbildr body
jsonbildr = jsonbildr.toPrettyString()
log.info(jsonbildr)
testStep.setPropertyValue("Request", jsonbildr)
Output :
{
"password": "LockUout",
"username": "Hackme"
}

How do I set a value in JSON response in Groovy script in SOAP UI

I have two REST request which I am trying to run in SOAP UI. I want to feed response from one REST request to the other REST request. I am using property transfer for this. I first want to modify a Value in Response from 1st request and then feed it . I am trying this
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// request
def request = '''{"data":{
"supplementaryMessages" : [ ],
"requisitionHeaders" : [ {
"dataOperation" : "UPDATE"
} ]
}}'''
// parse the request
def jsonReq = new JsonSlurper().parseText(request);
// get the response where you've the values you want to get
// using the name of your test step
responseContent = testRunner.testCase.getTestStepByName("Fetch1").getPropertyValue("response")
// parse response
def jsonResp = new JsonSlurper().parseText(responseContent)
// get the values from your first test response
// and set it in the request of the second test
jsonResp.data.requisitionHeaders.dataOperation = jsonReq.data.requisitionHeaders.dataOperation
When I run this I am getting the Type Mismatch error .It could be very simple issue but I am new to Groovy .

Getting context using groovyutils outside SoapUI

I am trying to hold the response of my request in a holder variable but I am not able to.
In SoapUI groovyutils is in-built and can be used easily. But I am sending my soap request using groovy and it is working fine. Now I want to get the response in a holder and put some assertions.
My piece of code for this is :
import com.eviware.soapui.*
def groovyUtils = new com.eviware.soapui.support.GroovyUtils()
def responseHolder = groovyUtils.getXmlHolder( messageExchange.responseContent )
Here I am not able to get as how I should pass the context in groovyutils and what all classes to call.
I'm not sure that I fully understand your problem, however seems that you want to check a SOAP response out of SOAPUI but using the facilities from SOAPUI jar isn't it?
If you want simply perform some assert in the response, then I would recommend you to avoid the use of GroovyUtils. Simply use XmlSlurper to parse the response, then get the desired values from the xml nodes and perform your asserts.
Since your Groovy code to you invoke the service and the response is missing I simply show you a possible example using XmlSlurper:
def response = '''<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/">
<soap:Body>
<myResponse>
<someNode>myText</someNode>
</myResponse>
</soap:Body>
</soap:Envelope>'''
def xml = new XmlSlurper().parseText(response)
// find the <someNode> element
def someNode = xml.'**'.find { it.name() == 'someNode' }
// check that the <someNode> has a value equals of 'myText'
assert someNode.text() == 'myText'
Hope it helps,

Resources