How to extract Response in Rest Assured by JSONPath

  

What is JsonPath?

JsonPath is similar to XPath for XML, but is used to extract data from JSON. Rest Assured provides built-in support for it.


Steps to Extract Response Using JsonPath in Rest Assured:

  • Send GET Request – Use given().get(...).
  • Extract Response – Use .extract().response().
  • Use JsonPath – Use response.jsonPath() to extract values.

URL:

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





Sample Java Code using Rest Assured:


import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;

import java.util.List;

public class JsonPathExample {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in";

        // Step 2: Send GET request and get response
        Response response = RestAssured
                .given()
                .when()
                .get("/api/users?page=2")
                .then()
                .statusCode(200)
                .extract()
                .response();

        // Step 3: Parse response with JsonPath
        JsonPath jsonPath = response.jsonPath();

        // Step 4: Extract specific values
        int total = jsonPath.getInt("total");
        int perPage = jsonPath.getInt("per_page");
        String firstEmail = jsonPath.getString("data[0].email");
        List<String> allEmails = jsonPath.getList("data.email");

        // Step 5: Print the extracted values
        System.out.println("Total users: " + total);
        System.out.println("Users per page: " + perPage);
        System.out.println("First user's email: " + firstEmail);
        System.out.println("All emails:");
        for (String email : allEmails) {
            System.out.println(email);
        }
    }
}




Common JsonPath Queries:


TaskJsonPath Expression
Total number of usersjsonPath.getInt("total")
Email of first userjsonPath.getString("data[0].email")
List of all emailsjsonPath.getList("data.email")
ID of last userjsonPath.getInt("data[-1].id")





Maven Dependencies:


<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

No comments:

Post a Comment