Extracting response using JSON in RestAssured - Notes By ShariqSP

Extracting Data Using JSONPath with Java, RestAssured, and TestNG

This section demonstrates how to test REST APIs using RestAssured, JSONPath, and TestNG. With TestNG, you can structure your API tests effectively while leveraging RestAssured for data extraction and validation.

Example: TestNG with RestAssured

We'll query the endpoint http://apitesting.shariqsp.com:8080/api/companies and use JSONPath to extract and validate specific data.

TestNG Test Class

                  
              import io.restassured.RestAssured;
              import io.restassured.response.Response;
              import io.restassured.path.json.JsonPath;
              import org.testng.Assert;
              import org.testng.annotations.BeforeClass;
              import org.testng.annotations.Test;
              
              import java.util.List;
              
              public class CompaniesApiTest {
              
                  // Base URI setup
                  @BeforeClass
                  public void setup() {
                      RestAssured.baseURI = "http://apitesting.shariqsp.com:8080/api/companies";
                  }
              
                  @Test
                  public void testExtractCompanyNames() {
                      // Send GET request and extract response
                      Response response = RestAssured
                              .given()
                              .get()
                              .then()
                              .statusCode(200) // Validate status code
                              .extract()
                              .response();
              
                      // Parse response with JSONPath
                      JsonPath jsonPath = response.jsonPath();
              
                      // Extract company names
                      List companyNames = jsonPath.getList("$[*].name");
                      System.out.println("Company Names: " + companyNames);
              
                      // Assert at least one company is returned
                      Assert.assertTrue(companyNames.size() > 0, "No companies found in response.");
                  }
              
                  @Test
                  public void testExtractSamsungDevicePrices() {
                      // Send GET request and extract response
                      Response response = RestAssured
                              .given()
                              .get()
                              .then()
                              .statusCode(200) // Validate status code
                              .extract()
                              .response();
              
                      // Parse response with JSONPath
                      JsonPath jsonPath = response.jsonPath();
              
                      // Extract Samsung device prices
                      List samsungPrices = jsonPath.getList("$[*].mobileItems[?(@.brand=='Samsung')].price");
                      System.out.println("Samsung Device Prices: " + samsungPrices);
              
                      // Assert that the Samsung prices are not empty
                      Assert.assertTrue(samsungPrices.size() > 0, "No Samsung devices found.");
                  }
              
                  @Test
                  public void testGalaxyS23UltraAvailability() {
                      // Send GET request and extract response
                      Response response = RestAssured
                              .given()
                              .get()
                              .then()
                              .statusCode(200) // Validate status code
                              .extract()
                              .response();
              
                      // Parse response with JSONPath
                      JsonPath jsonPath = response.jsonPath();
              
                      // Extract store availability for Galaxy S23 Ultra
                      List stores = jsonPath.getList("$[*].mobileItems[?(@.model=='Galaxy S23 Ultra')].availability[*].store");
                      System.out.println("Galaxy S23 Ultra Stores: " + stores);
              
                      // Assert at least one store is available
                      Assert.assertTrue(stores.size() > 0, "Galaxy S23 Ultra is not available in any store.");
                  }
              }
                  
                

Explanation

  • @BeforeClass: Sets the base URI for RestAssured to avoid redundancy.
  • @Test: Annotates individual test cases for validation and extraction.
  • JSONPath Queries: Use JSONPath expressions to extract specific data points:
    • $[*].name - Extracts all company names.
    • $[*].mobileItems[?(@.brand=='Samsung')].price - Extracts the prices of Samsung devices.
    • $[*].mobileItems[?(@.model=='Galaxy S23 Ultra')].availability[*].store - Lists stores where "Galaxy S23 Ultra" is available.
  • Assertions: Validates extracted data to ensure the API returns expected results.

Run Instructions

  1. Add dependencies for RestAssured and TestNG to your pom.xml:
                          
                  <dependencies>
                      <dependency>
                          <groupId>io.rest-assured</groupId>
                          <artifactId>rest-assured</artifactId>
                          <version>5.3.0</version>
                      </dependency>
                      <dependency>
                          <groupId>org.testng</groupId>
                          <artifactId>testng</artifactId>
                          <version>7.7.0</version>
                          <scope>test</scope>
                      </dependency>
                  </dependencies>
                          
                        
  2. Run the test using your IDE or build tool (e.g., Maven).

Using RestAssured and TestNG together provides a robust framework for automated API testing and data validation.