Skip to main content

Get JSON Array size and its element using JsonPath in REST Assured

Consider in below example you want to retrieve no of user on page 2 and email of first user. In below example data is an array and it has 6 element. So, size of array should return 6 and email of first user returns "michael.lawson@reqres.in"

Endpointhttps://reqres.in/api/users?page=2

Response:

{
  "page": 2,
  "per_page": 6,
  "total": 12,
  "total_pages": 2,
  "data": [
    {
      "id": 7,
      "email": "michael.lawson@reqres.in",
      "first_name": "Michael",
      "last_name": "Lawson",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"
    },
    {
      "id": 8,
      "email": "lindsay.ferguson@reqres.in",
      "first_name": "Lindsay",
      "last_name": "Ferguson",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"
    },
    {
      "id": 9,
      "email": "tobias.funke@reqres.in",
      "first_name": "Tobias",
      "last_name": "Funke",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"
    },
    {
      "id": 10,
      "email": "byron.fields@reqres.in",
      "first_name": "Byron",
      "last_name": "Fields",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"
    },
    {
      "id": 11,
      "email": "george.edwards@reqres.in",
      "first_name": "George",
      "last_name": "Edwards",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"
    },
    {
      "id": 12,
      "email": "rachel.howell@reqres.in",
      "first_name": "Rachel",
      "last_name": "Howell",
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"
    }
  ],
  "ad": {
    "company": "StatusCode Weekly",
    "url": "http://statuscode.org/",
    "text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
  }
}

Solution

public class ReqRes 
{	
	@BeforeClass
	public void setup()
	{
		RestAssured.baseURI = "https://reqres.in/";
		RestAssured.basePath = "api";
	}
	
	@Test(enabled=true)
	public void ArraySizeAndElemenets()
	{
		Response res = given()
			.queryParam("page", "2")
		.when()
			.get("/users/");
			
		JsonPath js = new JsonPath(res.asString());
		
		//Retrieve size of array
		int size = js.getInt("data.size()");
		System.out.println("Array size is: "+size);
		
		// Retrieve email of first user
		String firstUserEmail = js.getString("data[0].email");
		System.out.println("First user email is: "+firstUserEmail);
	}
}
Video Tutorial

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.