Interview #107: RestAssured: How do you extract specific data from a JSON or XML response?

Interview #107: RestAssured: How do you extract specific data from a JSON or XML response?

RestAssured is a popular Java-based library used for testing RESTful APIs. One of its key features is the ability to extract specific data from API responses, whether they are in JSON or XML format. Extracting data is essential for validation, data-driven testing, and chaining requests dynamically.

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

RestAssured provides various techniques for extracting response data, including JSONPath, XMLPath, and Deserialization into Java Objects. This guide explains these methods in detail with examples.

1. Extracting Data from a JSON Response

1.1 Using JSONPath to Extract Data

JSONPath is a powerful way to query JSON responses, similar to how XPath works for XML. In RestAssured, JsonPath helps extract specific values or entire sections from the JSON response.

Example JSON Response

{
  "id": 101,
  "name": "John Doe",
  "email": "[email protected]",
  "address": {
    "city": "New York",
    "zipcode": "10001"
  },
  "phoneNumbers": ["123-456-7890", "987-654-3210"]
}        

Extracting Specific Fields Using JSONPath

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

public class ExtractJsonData {
    public static void main(String[] args) {
        // Send API request and get response
        Response response = RestAssured.get("https://api.example.com/users/101");

        // Convert response to JSONPath object
        JsonPath jsonPath = response.jsonPath();

        // Extract values
        int id = jsonPath.getInt("id");  // Extract integer
        String name = jsonPath.getString("name");  // Extract string
        String email = jsonPath.getString("email");
        String city = jsonPath.getString("address.city");  // Extract nested field
        String firstPhone = jsonPath.getString("phoneNumbers[0]");  // Extract first phone number

        // Print extracted values
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
        System.out.println("Email: " + email);
        System.out.println("City: " + city);
        System.out.println("First Phone Number: " + firstPhone);
    }
}        

1.2 Extracting a List from JSON

If a JSON response contains an array, you can extract it as a list.

import java.util.List;

List<String> phoneNumbers = jsonPath.getList("phoneNumbers");
System.out.println("Phone Numbers: " + phoneNumbers);        

?? Output:

Phone Numbers: [123-456-7890, 987-654-3210]        

1.3 Extracting Data Based on a Condition

If the JSON response contains multiple objects, you can filter data based on conditions.

Example JSON Response (List of Users)

{
  "users": [
    { "id": 101, "name": "John Doe", "age": 30 },
    { "id": 102, "name": "Jane Smith", "age": 25 },
    { "id": 103, "name": "Robert Brown", "age": 40 }
  ]
}        

Extracting Names of Users Older Than 30

List<String> names = jsonPath.getList("users.findAll { it.age > 30 }.name");
System.out.println("Users above 30: " + names);        

?? Output:

Users above 30: [John Doe, Robert Brown]        

2. Extracting Data from an XML Response

2.1 Using XMLPath to Extract Data

Similar to JSONPath, XMLPath is used to extract data from XML responses.

Example XML Response

<user>
    <id>101</id>
    <name>John Doe</name>
    <email>[email protected]</email>
    <address>
        <city>New York</city>
        <zipcode>10001</zipcode>
    </address>
    <phoneNumbers>
        <phone>123-456-7890</phone>
        <phone>987-654-3210</phone>
    </phoneNumbers>
</user>        

Extracting Specific Fields Using XMLPath

import io.restassured.path.xml.XmlPath;

Response response = RestAssured.get("https://api.example.com/users/101");

// Convert response to XMLPath object
XmlPath xmlPath = response.xmlPath();

// Extract values
String name = xmlPath.getString("user.name");
String city = xmlPath.getString("user.address.city");
String firstPhone = xmlPath.getString("user.phoneNumbers.phone[0]");

// Print extracted values
System.out.println("Name: " + name);
System.out.println("City: " + city);
System.out.println("First Phone: " + firstPhone);        

?? Output:

Name: John Doe
City: New York
First Phone: 123-456-7890        

2.2 Extracting a List from XML

List<String> phoneNumbers = xmlPath.getList("user.phoneNumbers.phone");
System.out.println("Phone Numbers: " + phoneNumbers);        

?? Output:

Phone Numbers: [123-456-7890, 987-654-3210]        

3. Extracting the Entire Response Body as a String

If you need to store the full response for logging or debugging purposes, you can extract it as a raw string.

String jsonResponse = response.getBody().asString();
System.out.println("Full JSON Response: " + jsonResponse);        

or for XML:

String xmlResponse = response.getBody().asString();
System.out.println("Full XML Response: " + xmlResponse);        

4. Extracting and Using Data in Assertions

You can extract data and use it for validation in test cases.

4.1 JSON Response Validation

response.then()
    .assertThat()
    .body("name", equalTo("John Doe"))
    .body("address.city", equalTo("New York"));        

4.2 XML Response Validation

response.then()
    .assertThat()
    .body("user.name", equalTo("John Doe"))
    .body("user.address.city", equalTo("New York"));        

5. Extracting and Using Data in Chained API Requests

Sometimes, you need to extract data from one API response and use it in another request.

Example: Extracting User ID and Using It in Another Request

int userId = jsonPath.getInt("id");

// Use extracted userId in the next API request
Response newResponse = RestAssured.get("https://api.example.com/orders?userId=" + userId);        

Conclusion

RestAssured provides multiple ways to extract data from JSON and XML responses using JsonPath and XmlPath. These extraction methods are useful for:

? Validating API responses

? Performing data-driven testing

? Chaining API requests dynamically

By mastering JSONPath and XMLPath, you can efficiently validate, manipulate, and use API response data in automated tests. ??


要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章