top of page
Search
Writer's pictureCoding Camp

Reading JSON response using Rest Assured

To learn how to work on various scenarios and pass parameters in Rest Assured, check this link.



As we already saw how to pass parameters and run tests in rest assured in our previous blog, let us directly dive into how to read responses.


1.To Read status code from Response:


Code to get the status code from response is as follows,


import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;

public class ReadResponse {

	@Test
	public void readResponseoutput()
	{
	String url = "http://deckofcardsapi.com/api/new";
	given().when().get(url).then().log().all();
	int statuscode = given().when().get(url).getStatusCode();
	System.out.println("status code = "+statuscode);
	
	}
}

Rest Assured is a very straightforward language, and fetching status code is just as simple. Using getStatusCode() method we can easily get the status code form respose.


2. To Read Header from Response:


Fetching response status code is already covered in the above segment. It is worthy to note that to fetch different parts of the response, the keyword 'extract' is very important.


import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;

public class ReadResponse {

	@Test
	public void readResponseoutput()
	{
	String url = "http://deckofcardsapi.com/api/new";
	System.out.println("Header = "+ given().when().get(url).then().extract().headers() );
	}
}



3. To Read specific value from Json response:


The extract() method has more options to read different parts of response. One of which is extract().path()

import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;

public class ReadResponse {

	@Test
	public void readResponseoutput()
	{
	String url = "http://deckofcardsapi.com/api/new";
	System.out.println("deck_id = "+ given().when().get(url).then().extract().path("deck_id"));
	}
}

Inside path() method, we can mention the json path of the variable which we want to retrieve the value of.


4. To Read Content Type from Json:


Code:

import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;

public class ReadResponse {

	@Test
	public void readResponseoutput()
	{
	String url = "http://deckofcardsapi.com/api/new";
	System.out.println("ContentType = "+ given().when().get(url).then().extract().contentType());
	}
}

output:



Happy Testing!!!






20 views0 comments

Recent Posts

See All

Smallest String With A Given Numeric Value

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the...

留言


bottom of page