Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Headers in Ready API
2.1.
Adding Header to Request 
2.2.
Saving Response Header Value to Property
2.3.
Adding Hashed Authentication Header to Request
3.
Generate Random Identifier using Groovy Script
4.
Using JDBC Driver to connect Database
5.
Log Results using Ready API
6.
Modifying Responses using Groovy Script
7.
Parsing JSON and XML using Groovy Scripts
8.
Frequently Asked Questions 
8.1.
What types of reports is ReadyAPI able to provide?
8.2.
What is the use of Ready API?
8.3.
What makes a ready API different from a REST API?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Responses and parsing in Ready API

Author Ayush Mishra
0 upvote

Introduction 

ReadyAPI is a user-friendly no-code API testing tool that aims to speed up your testing procedures. Automate and scale the end-to-end testing of various API types. Give your development teams quick and reliable integrations by enabling virtualization.

Responses and Parsing in Ready API


In this blog, we will intensely discuss Responses and parsing in Ready API. Let's start going!

Headers in Ready API

In this part of "Responses and parsing in Ready API,"  we will see Groovy Script work with HTTP headers. Groovy scripts allow you to change request headers and retrieve header information from responses.

Adding Header to Request 

RequestFilter.filterRequest event handler scripts can allow adding a header to Request.

The below given an example adds a custom HTTP header to request from within the event handler:-

// Calling the request headers
def header = request.requestHeaders

// Creating custom header
header.put( "X-tokenHeader", "value") // Replace values with according to need

// Adding the customize header to request headers
request.requestHeaders = header

Saving Response Header Value to Property

The below given an example explains how to use a custom HTTP header in event handler requests:-

// Replace names of a property and test step according to to need

// Getting the header value
def header_Value = testRunner.testCase.getTestStepByName("CreatePartner").httpRequest.response.responseHeaders["Location"]

// Saving the value to a test case property
testRunner.testCase.setPropertyValue( "MyHeader", header_Value.toString() )

Adding Hashed Authentication Header to Request

The below given an example explains how to use a Hashed Authentication HTTP header in event handler requests:-

import com.eviware.soapui.support.types.StringToStringMap
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.security.Timestamp
import java.util.Date


key = "123"
secret = "123"

// Getting a timestamp

date= new java.util.Date()
timestamp = (date.getTime() / 1000)

// Getting a hashed signature

signature = null

toBeHashed = key + secret + timestamp
MessageDigest md = MessageDigest.getInstance("SHA-512")
byte[] bytes = md.digest(toBeHashed.getBytes("UTF-8"))
StringBuilder sb = new StringBuilder()

for(int i=0; i< bytes.length ;i++)
	{
      sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1))
	}

signature = sb.toString()

// Complete the header value
authHeaderValue = "EAN APIKey=" + key + ",Signature=" + signature + ",timestamp=" + timestamp

// Obtain the list of request headers
header = request.getRequestHeaders()

// Add a header to the request
StringToStringMap headermap = new StringToStringMap(header)

if (headers.containsKeyIgnoreCase("authorization") )
	{
   		headermap.replace("authorization", authHeaderValue)
	} 
else
	{
    	headermap.put("authorization", authHeaderValue)
	}
request.requestHeaders = headermap

Generate Random Identifier using Groovy Script

In this part of “Responses and parsing in Ready API,”  we will see Groovy Script to generate values with the Universally Unique Identifier (UUID).

The below given an example explains how to generate a UUID:-

// Generating random variable value
def var = UUID.randomUUID()

// Logging the variable
log.info var

 

To generate the UUID in the string, we will use the below code:-

// Generate a random item identifier
log.info "Item: ${java.util.UUID.randomUUID()}"

Using JDBC Driver to connect Database

In this part of "Responses and parsing in Ready API,"  we will see how to register the JDBC  driver and connect to the Database using Groovy Script.

The below given example explains how to register the driver and connect to the Database using Groovy Script:-

// Import the Groovy class required to work with SQL databases
import groovy.sql.Sql

// Setting up the database connection properties

def url = 'jdbc:mysql://mydatabase.com/DatabaseVariable' /* IMPORTANT: must start with jdbc:mysql:// */
def user = 'DatabaseUser'
def password = 'DatabasePassword'
def driver = 'com.mysql.jdbc.Driver'

// Register the MySQL JDBC driver – required for Groovy to send requests to the database

com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( driver )

// Connecting to the SQL instance
def sql = Sql.newInstance(url, user, password, driver)

// Use the SQL instance
// ...
// Close the SQL instance
sql.close()

Log Results using Ready API

In this part of “Responses and parsing in Ready API,”  we will see how to log your test result in Ready API and extract details about test steps that satisfy specific requirements, etc.

The below given an example explains how to save the results of every test step:-

// Replace the path according to need
// Make sure the specified folder exists
filePath = 'c:/work/test-results/'

// Create output files
fos = new FileOutputStream( filePath + testStepResult.testStep.label + '.txt', true )

// Fill output files
pw = new PrintWriter( fos )
testStepResult.writeTo( pw )

// Close the output
pw.close()
fos.close()

 

The below given an example explains how to save the results of every test step in failed test cases:-

for ( testCaseResult in runner.results )
{
    // Get all test cases’ names from the suite
    testCaseName = testCaseResult.getTestCase().name
    log.info testCaseName


    // Check whether the case has failed
    if ( testCaseResult.getStatus().toString() == 'FAIL' )
    {
        // Log failed cases and test steps’ resulting messages
        log.info "$testCaseName has failed"
        for ( testStepResult in testCaseResult.getResults() )
        {
            testStepResult.messages.each() { msg -> log.info msg }
        }
    }
}

Modifying Responses using Groovy Script

In this part of “Responses and parsing in Ready API,”  we will use groovy scripts to perform various operations on responses, such as changing their content or logging the outcomes.

The below given an example explains how to modify a specific value across all response messages with the RequestFilter.afterRequest event handler:-

if( request.response == null )
	return

// Get the response content.
def content = context.httpResponse.responseContent

// Modify the content – replacing all 555 with 444.
content = content.replaceAll( "555", "444" )

// Override the response.
context.httpResponse.responseContent = content

Parsing JSON and XML using Groovy Scripts

In this part of “Responses and parsing in Ready API,”  we will use Groovy Scripts to parse JSON and XML in your requests and response.

Let's use an example where we have XML content in the request and JSON content in the response and want to verify that some values are equal.

{
"info" : {
"buildingStyle" : "MBH.1990",
"owner" : "MBH.1990",
"checkIn" : true,
"checkOut" : true
  }
}

 

Groovy Scripts to check whether specific values are equal or not is:- 

//Import packages that contain libraries needed to parse JSON and XML
import groovy.json.*
import groovy.util.*


//Parse JSON content in the request
def request = context.expand( '${REST Request#Request}' )
def parsedJson = new JsonSlurper().parseText(request)


//Parse XML content in the response
def response = context.expand( '${REST Request#Response}' )
def parsedXml = new XmlSlurper().parseText(response)


//Assert values in the request against values in the response
assert parsedJson.info.buildingStyle.toString() == parsedXml.BuildingStyle.text()
assert parsedJson.info.owner.toString() == parsedXml.Owner.text()
assert parsedJson.info.checkIn.toString() == parsedXml.CheckIn.text()
assert parsedJson.info.checkOut.toString() == parsedXml.CheckOut.text()

Frequently Asked Questions 

What types of reports is ReadyAPI able to provide?

ReadyAPI provides a range of pre-built reports and reporting templates in order to assist you in delivering the information that is most important to you. ReadyAPI offers a variety of export formats in addition to visual representations so that you can save or transfer your continuous integration findings into another system for analysis in the future.

What is the use of Ready API?

Agile and DevOps software teams can improve API quality by using ReadyAPI, which gives teams the ability to create, manage, and carry out automated functional, security, and performance tests through a single, centralized interface.

What makes a ready API different from a REST API?

REST-assured does not require licensing fees, whereas ReadyAPI! offers much more native performance. Any REST API can be tested if that's all you're doing.

Conclusion

Congratulations on finishing the blog! We have studied Responses and parsing in Ready API. We further looked at the header, generating identifiers, JDBC connection, Log results, Modifying Response, and parsing JSON and XML.

We sincerely hope that this blog has improved your understanding of Responses and parsing in Ready API, and if you want to learn more, then you can check articles on:-

Please refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Live masterclass