Ravi Krishna
Ravi Krishna

Reputation: 11

How to Display Json Array Response body in console using Rest Assured concept

[
    {
        "bookId": 8,
        "bookName": "social",
        "authorId": 7,
        "authorName": "Ram",
        "publisherId": 6,
        "publisherName": "potho",
        "genre": "nature",
        "price": 1000,
        "numberOfPages": 1000
    }
]

The above response body, I want to display in console using with rest assured concept. please tell me code

Upvotes: -1

Views: 2732

Answers (2)

Ashwini Jalnekar
Ashwini Jalnekar

Reputation: 1

For this type of response you can simply add curly braces around the response body and add a parameter e.g. responseStr in below example and then you can convert that string to a proper Json Response and later use it as Array as I have given in below code block:

response = "{\"responseStr\":"+response+"}";
            System.out.println("Response :"+response);
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = (JSONArray)jsonObject.get("responseStr");
            
            for(int i=0;i<jsonArray.length();i++) {
                JSONObject jsonObject1 = (JSONObject)jsonArray.getJSONObject(i);
          }```

Upvotes: 0

Navpreet Singh
Navpreet Singh

Reputation: 151

  1. Create a method that calls the api (define preconditions in given() part and endpoint in the when() part).
  2. Do not include assertions in this method.
  3. Save the response variable (of type Response).
  4. Add line to print api response body on console.

Please find the sample code :
Response response = given()
.log().all()
.headers(headers)
.when()
.get("https://www.your_endpoint.com/new");
System.out.println("API response body = " + response.getBody().asString());

NOTE : logging is generally preferred over printing to console.
Try using log4j to log and replace "System.out.println" with "logger.info"

Upvotes: 2

Related Questions