REST Assured Tutorial 69 – Response Logging In Rest Assured

As a part of End to End REST Assured Tutorial , in this post We will learn :- How to log response specification in Rest Assured?

In last post, we have already learnt Logging request in Rest Assured. Let’s learn Logging Response in Rest Assured.

We can log response specification using log() method provided by ValidatableResponse interface. In fact ValidatableResponse extends ValidatableResponseOptions<ValidatableResponse,Response> interface. log() method returns  ValidatableResponseLogSpec interface reference that allows you to log different parts of the Response.

We have below methods for logging:-

  1. all() – Logs everything in the response, including e.g. headers, cookies, body. Pretty-prints the body if content-type is either either XML, JSON or HTML.
  2. all(boolean shouldPrettyPrint) – Logs everything in the response, including e.g. headers, cookies, body with the option to pretty-print the body if the content-type is either XML, JSON or HTML.
  3. everything() or everything(boolean shouldPrettyPrint) – Same as all() and all(boolean shouldPrettyPrint).
  4. headers() – Logs only the headers.
  5. cookies() – Logs only the cookies.
  6. ifValidationFails() – Logs everything if a test validation fails.
  7. ifValidationFails(LogDetail logDetail) – Logs with the supplied log detail only if the validation fails.
  8. ifValidationFails(LogDetail logDetail,boolean shouldPrettyPrint) – Logs all parameters only if the validations fail.

Rest Assured Code:-

package LoggingInRestAssured;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;

public class LoggingResponse {

	@Test
	public void logResponse() {
		
		// There is no need to add escape character manually. Just paste string within double 
		// quotes. It will automatically add escape sequence as required. 
		String jsonString = "{\r\n" + 
				"    \"firstname\" : \"Jim\",\r\n" + 
				"    \"lastname\" : \"Brown\",\r\n" + 
				"    \"totalprice\" : 111,\r\n" + 
				"    \"depositpaid\" : true,\r\n" + 
				"    \"bookingdates\" : {\r\n" + 
				"        \"checkin\" : \"2018-01-01\",\r\n" + 
				"        \"checkout\" : \"2019-01-01\"\r\n" + 
				"    },\r\n" + 
				"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				"}";
		
		// Creating an object of RequestSpecBuilder
		RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
		// Setting Base URI
		reqBuilder.setBaseUri("https://restful-booker.herokuapp.com");
		// Setting Base Path
		reqBuilder.setBasePath("/booking");
		reqBuilder.setContentType(ContentType.JSON);
		// Setting pay load
		reqBuilder.setBody(jsonString);
		
		// Getting RequestSpecification reference using builder() method
		RequestSpecification reqSpec = reqBuilder.build();
		
		// Getting ValidatableResponse
		ValidatableResponse validatableResponse = RestAssured.given(reqSpec).post().then();
		// Logging response
		System.out.println("################Logging everything of response################");
		validatableResponse.log().all();
		System.out.println("################Logging response status code################");
		validatableResponse.log().status();
		System.out.println("################Logging response body################");
		validatableResponse.log().body();
		System.out.println("################Logging cookies of response################");
		validatableResponse.log().cookies();
		System.out.println("################Logging headers of response################");
		validatableResponse.log().headers();		
		
	}
}

Output:-

[RemoteTestNG] detected TestNG version 7.0.0
################Logging everything of response################
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-SIrSqXzFCWI4yhlnSZi17vIdi4o"
Date: Wed, 11 Mar 2020 18:06:42 GMT
Via: 1.1 vegur

{
    "bookingid": 13,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
################Logging response status code################
HTTP/1.1 200 OK
################Logging response body################
{
    "bookingid": 13,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
################Logging cookies of response################

################Logging headers of response################
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-SIrSqXzFCWI4yhlnSZi17vIdi4o"
Date: Wed, 11 Mar 2020 18:06:42 GMT
Via: 1.1 vegur
PASSED: logResponse

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

In BDD Style:-

package LoggingInRestAssured;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;

public class LoggingResponseInBDDStyle {

	@Test
	public void logResponse() {
		
		// There is no need to add escape character manually. Just paste string within double 
		// quotes. It will automatically add escape sequence as required. 
		String jsonString = "{\r\n" + 
				"    \"firstname\" : \"Jim\",\r\n" + 
				"    \"lastname\" : \"Brown\",\r\n" + 
				"    \"totalprice\" : 111,\r\n" + 
				"    \"depositpaid\" : true,\r\n" + 
				"    \"bookingdates\" : {\r\n" + 
				"        \"checkin\" : \"2018-01-01\",\r\n" + 
				"        \"checkout\" : \"2019-01-01\"\r\n" + 
				"    },\r\n" + 
				"    \"additionalneeds\" : \"Breakfast\"\r\n" + 
				"}";
		
		// Creating an object of RequestSpecBuilder
		RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
		// Setting Base URI
		reqBuilder.setBaseUri("https://restful-booker.herokuapp.com");
		// Setting Base Path
		reqBuilder.setBasePath("/booking");
		reqBuilder.setContentType(ContentType.JSON);
		// Setting pay load
		reqBuilder.setBody(jsonString);
		
		// Getting RequestSpecification reference using builder() method
		RequestSpecification reqSpec = reqBuilder.build();
		
	
		RestAssured.
		   given(reqSpec)
		     .post()
		   .then()
		      //################Logging everything of response################
		      .log().all()
		      //################Logging response body################
		      .log().body()
		      //################Logging headers of response################
		      .log().headers()
		      //################Logging cookies of response################
		      .log().cookies()
		      //################Logging response status code################
		      .log().status()
		      .assertThat()
		      .statusCode(200);
		
	}
}

Output:-

[RemoteTestNG] detected TestNG version 7.0.0
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-/h+hXkhVYUVpjJBSFQdxRxTcyB8"
Date: Wed, 11 Mar 2020 18:10:11 GMT
Via: 1.1 vegur

{
    "bookingid": 14,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
{
    "bookingid": 14,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2018-01-01",
            "checkout": "2019-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 195
Etag: W/"c3-/h+hXkhVYUVpjJBSFQdxRxTcyB8"
Date: Wed, 11 Mar 2020 18:10:11 GMT
Via: 1.1 vegur

HTTP/1.1 200 OK
PASSED: logResponse

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================


Note:- There is a same method named “log()” to log request and response. Whether it will give you next method to log request or response, depends on where you are using. You can observe that while logging Request , I used log() method before calling HTTP method but while logging Response, I used log() method after calling HTTP method.

You can clone/download example repo here.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

Leave a Reply

Your email address will not be published. Required fields are marked *