Rest-Assured Automation Using Java

Rest-Assured Automation Using Java

Part-4

A blog for Day 4 (Part 4): Validating and Extracting Data from API Responses in Rest Assured

In this blog, we'll be diving into the details of how to validate and extract data from API responses using Java and the Rest Assured library.

  1. Validating Response Status Codes: When testing an API, one of the most important things to check is the response status code. The status code lets you know whether the request was successful or not. In Rest Assured, you can use the "assertThat" method along with the "statusCode" method to validate the response status code. Here's an example:

int statusCode = given().get("https://api.example.com").then().statusCode().then().statusCode()); assertThat(statusCode, equalTo(200));

This code sends a GET request to the specified URL and stores the response status code in the "statusCode" variable. The "assertThat" method then checks that the "statusCode" is equal to 200, which is the standard HTTP status code for a successful request. If the status code does not match the expected value, the test will fail.

  1. Extracting Data from the Response: In addition to validating the response status code, you may also want to extract specific values from the response for further processing or validation. Rest Assured provides a convenient way to extract data from the API response using the "jsonPath" method. Here's an example:

String id = given().get("https://api.example.com").then().extract().jsonPath().getString("id").then().extract().jsonPath().getString("id"));

This code sends a GET request to the specified URL and extracts the value of the "id" field from the response using the "JSON path" method. The extracted value is then stored in the "id" variable. You can use this variable in later tests or for other purposes.

It's important to note that the "JSON path" method only works with JSON responses. If your API returns XML, you'll need to use a different method to extract data from the response.

In the next part of this series, we'll cover how to set up and run automated tests using Rest Assured. Stay tuned!