Couple of days back, i was exploring REST API and thought of writing some generic groovy code lines – to count the number of nodes in the response & iterate (and to assert values) through them (actually one of my friend asked me ;-)) So i started thinking on same lines & luckily found the solution only in 5 minutes. Amazing…isn’t it :-p

So before i share the lines of code, here i have couple of quick question for you all to think & then answer :

“What is REST API?”
“What is JSON?”
“When to use REST api & How i can identify if it is?”

Now many of you (i hope you all) might know the answer to these silly question. So here is a REST request to all such people to share their views/answers in the comment section. Few others may think :
“Why the hell in world, i should care whether it is REST api or some __ api?”
and for those people i would say “Good you dumb***! Now stop testing/developing, if you don’t care”.

Before you find the correct answer & share, let me copy paste my script code lines here (for those who don’t care about concept).

/*
@Author: Pradeep Bishnoi
@Description : To read the REST response and iterate node using Xpath
*/
testStepName = messageExchange.modelItem.testStep.name   //to get the Test Step Name
xmlHold = messageExchange.responseContentAsXml.toString()  //to store the response as Xml string
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context )
def holder = groovyUtils.getXmlHolder (xmlHold)
log.info holder.getXml()  // will display /Log the response in Xml
count  = holder.getNodeValue(“count(//Response/e)”)
count = count.toInteger() + 1  //converting count into Integer & adding 1 for looping purpose
xPath = “//Response/e[“
for (i in 1..<count)
{
xPath1 = xPath + i + “]/Name”  // Name value
xPath2 = xPath + i + “]/EmailAddresses/e”   //email Node value
log.info holder.getNodeValue(xPath1)
log.info holder.getNodeValue(xPath2)
i++
}

if you noticed in the above code lines.. i have used an XPath expression to navigate to the Xml node tree structure. Since the response received is in JSON format [as mentioned in post header], soapui automatically generates/performs the XML structure/translation  of the received response. And the xml response would have Root node as “Response” followed by child nodes named as “e”. To access each individual child node and their child you have to use an XPath expression like  //Response/e[1]/childNode

Now i don’t have anything else to share, so please stop reading and consider this as the end of this blog. And if are still reading, then … well

Hint to find answer : Use any search engine and you will get the answer :-p

Till next blog post… happy reading & happy sharing 🙂

Advertisements
Comments
  1. Dear [PB],great sharing…. I’ve always been concentrated on your blog…..also, subscribed your news……what’s more, I will also start to learn the new skills here….your blog..so wonderful……
    btw, a minor question i think you can give me solution: I’d like to determine if the xml node exist. I get response and return the 5 same nodes, and i need to check if one node exist under the 5 nodes? how to create script to verify that?

    thanks,
    Aaron

    • Hi Aaron,

      good that u r learning new stuff & my blog is helping in some way 🙂
      and regarding ur question :
      you can use .childNodes() method to get all the child nodes of any selected node. by using that rest can be achieved.
      and one more thing, if a node is null generally appears in response as and for such cases xPath works perfect by returning null as the response value.

      btw, as i asked you in the past, am asking you again. would you b able to help me (or other readers) with a some stuff related to JMS. am desperate to write or publish something about JMS & soapUI.

      regards,
      /pradeep bishnoi

  2. Boson says:

    Hello Pradeep,

    Very good information! Do you know how to edit a REST json request with groovy. Say I have REST-json request something like this {“FooRequest”:{“Country”:[“DK”]}}

    How can I use a variable instead of “DK”, to be set on a previous Groovy step? For XML, I can just use setNodeValue, but this is json and I haven’t found a corresponding function.

    Thanks for any help,

    Boson

    • Hi Boson,

      How about replacing the parameter with Variable name & property expansion would take care while sending out the request.
      {“FooRequest”:{“Country”:[“${#TestCase#MyProp“]}}

      So, to use above code syntax you have to create a Property variable at TestCase level name it as MyProp and assign the needed value.
      I hope this will help.

      Best Regards,
      {Pradeep Bishnoi}

  3. newbie says:

    Hi i am newbie to SOAP UI. Webservice which i am going to test consume JSON format input.
    1.How do i sent JSON input as parameter from my request?
    2. How do i make use of Date source and Data loop concept to conduct data driven for JSON input.

    Please help. Thanks in advance.

    Regards,
    Newbie

  4. maddila says:

    How to validate the response data dynamically?
    We have request data in a datasource. Whenever the request data changes the response also changes. We want to keep the expected response in external file so that no need to touch the assertion scripts… Basicall we are using RESTAPI json input/output…
    Can you please suggest a solution?

  5. Kinjal says:

    I want to do property transfer between two test cases.I have 2 test cases save tenant and get tenant.Now when I run Save Tenant method ,I get json object as a response.Now,I want to take Tenant id from the response and pass it to the get tenant test case as a parameter.For that I have created a property at a testsuit level-TenantId and stored the value of the tenantId into that.Now I want to pass this value to get Tenant testcase as a json object in below format

    {“Id”:{my tenant id should go here}}

    How can I pass it over here ?
    I have used below format but it does not work

    {“Id”:${#TestSuit#TenantId}}

    Please help me.

  6. learningSOAPUI says:

    I keep getting Unexpected element: CDATA if I use the example provided above

    and when I try following

    def response = messageExchange.getResponse().getContentAsXml();
    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
    def holder = groovyUtils.getXmlHolder( response );
    holder.namespaces[“ns”] = “https://maps.googleapis.com/maps/api/place/search/json”

    I am getting:
    Cannot invoke method getContentAsXml() on null object\

    Help!!

  7. SOAPUIWSTesting says:

    Hello Pradeep,

    Very good blog. I learnt so much from all the posts.

    I am new to REST services. Could you please suggest how to test ODATA REST services. From a testing perspective what would we look for?

    Do we compare the ODATA output with a direct query against DB (using JDBC test step)?

  8. guitarmanvt says:

    Well, technically, REST is not equal to JSON over HTTP…which is what you describe here.

    REST begins when we ask “What Representations are we using?” instead of “What services do we need to call?” Also, REST requires HATEOAS, which I don’t see here.

    It’s definitely worth your time to read up on REST. Roy Fielding’s dissertation defined it. Perhaps you’d enjoy his article at http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

  9. Nick says:

    Hello Pradeep,

    Nice blog.

    When I have a request, the return data looks like a json format in a CDATA like this :

    <![CDATA[{"AllNoctilienLines": [
    {
    "prop1": "value1",
    "prop2": "value2",
    "prop3": "value3",
    "prop4": "value4",
    "prop5": [
    {
    "x1": "string",
    "x2": "true",
    "x3": "1"
    }
    ]
    },

    How can I read this response and analyze if the values are OK or not?

  10. shuvadip das says:

    Hi PB,

    I have wrote an groovy script in soapui for .docx file creation, its working fine and printing also . But the request XML and response XML are not coming in Pretty print , its coming as a paragraph.
    Please guide me..

    Code:
    ========
    import java.io.FileInputStream;
    import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;

    import org.apache.poi.xwpf.usermodel.*;
    def groovy=new com.eviware.soapui.support.GroovyUtils(context)
    def project=context.testCase.testSuite.project

    def testStepCount= testRunner.testCase.getTestStepCount();
    log.info testStepCount
    def request=project.getTestSuiteAt(0).getTestCaseAt(1).getTestStepAt(4).getProperty(“Request”).getValue().toString()

    XWPFDocument docx = new XWPFDocument(new FileInputStream(“c:\\Inputparagraph.docx”));

    FileOutputStream out = new FileOutputStream(new File(“C:\\createparagraph00.docx”));

    XWPFParagraph p2 = docx.createParagraph();
    XWPFRun r2 = p2.createRun();
    r2.setText(request);
    docx.write(out);
    out.close();

    ====================
    At present Output is coming below:

    Denver London

    ================
    OUTPUT SHOULD COME LIKE BELOW:


    Denver

    London

  11. achin says:

    hi PB,
    I am new in soapUI so i havn’t much idea for soapUI tool. So here i need to automate REST API.
    please help me to solve my problem.
    this is my first test step, i have json request, i passed all parameter and now i got my response as well, so in response there is Token id, or other information is generated. i need only token to id to next step.i added step property transfer and i have generated Xpath for this token id but i don’t know how to fill it in next test step.
    check the example:- i have generated Xpath for “id”: “a88ddbf2c28c4536a3bd8d59befff7mq”

    i.e- declare namespace ns1=’http://URL/abc/ab1′;
    //ns1:token[1]/ns1:id[1]

    now in need to pass this id to my next request:-

    {
    “auth”: {
    “tenantName”: “abc”,
    “token”: {
    “id”: “cbe6a5ed0b3e4f71bccaa51402e09479” here i need to paste that id automatically
    }
    }
    }

    is there any process in property transfer or using groovy script to pass this id.
    please help me asap.

  12. Sachin says:

    How to get the count of number of Child Nodes inside a response tag?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s