How to extract Response in Rest Assured by JSONPath

  



What is JsonPath?

  • JSONPath is a query language (similar to XPath for XML) that allows you to navigate through a JSON response and extract specific values.
  • It helps testers pick out individual fields, nested objects, or arrays from a JSON response without having to parse the entire response manually.
Example JSON response:

{
  "user": {
    "id": 101,
    "name": "Himanshu",
    "roles": ["admin", "editor"]
  }
}


With JSONPath you could extract:

user.id → returns 101
user.name → returns "Himanshu"
user.roles[0] → returns "admin"








How to extract Response in Rest Assured by JSONPath

When you send a request with Rest Assured and get back a response:

1. Capture the response

  • First, the API response is stored in a variable.
2. Use JSONPath to extract fields
  • Apply JSONPath expressions (like data.id, user.name, etc.) on the response to extract specific values.
3. Assertions or Reuse
  • Once extracted, the values can be: Verified against expected values (assertions), Reused in subsequent requests (chaining).

Example in words:
  • If the response contains "id": 101, you can use JSONPath expression "id" to extract it.
  • If the response contains a nested object like "user.name", you can use that path to fetch the value.
  • If the response contains an array, you can specify the index, like "roles[1]" to fetch "editor".

URL:

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


Below is the screenshot of response of API: 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);
        }
    }
}


Code explanation:

(a) Set base URI
(b) Send request and get response from server
(c) parse response with JsonPath
(d) Extract specific values
(e) Print the extracted values



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>


Suggested Posts:

1. Test Form Authentication in RestAssured
2. Test Digesh Auth in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. How to Test Basic Authentication in RestAssured

How to Test a Single Response Header by Rest Assured

 



What is response header in API?

A response header in an API is metadata returned by the server along with the body of the response. It provides additional information about the response, such as:

  • Content-Type → tells the format of the response (e.g., application/json, text/html).
  • Content-Length → specifies the size of the response body.
  • Server → identifies the server software handling the request.
  • Cache-Control → gives caching directives to the client.
  • Set-Cookie → passes cookies from server to client.

These headers don’t contain the main data (which is usually in the response body), but they are critical for understanding how to interpret and handle the response.


When testing with Rest Assured, you usually verify that:

1. The response contains a specific header

  • Example: Check if the header Content-Type is present.
2. The header has the expected value
  • Example: Verify that Content-Type equals application/json.
3. The header value matches certain conditions
  • Example: Check if the value starts with application/.
In Rest Assured, testing a single response header means making an API request, capturing the response, and then asserting the value of that particular header against the expected outcome.








We want to:

  • Send a GET request to https://reqres.in/api/users?page=2
  • Extract and validate a specific response header (example: Content-Type)

Below is the screenshot of response of API: https://reqres.in/api/users?page=2













To test a single response header in a GET API using Rest Assured in Java, you can follow these steps:

  • Set the base URI
  • Send a GET request
  • Extract the specific header
  • Validate it using assertion



Sample Java Code Using Rest Assured

import io.restassured.RestAssured;
import io.restassured.response.Response;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class GetResponseHeaderTest {

    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()
                .extract()
                .response();

        // Step 3: Print and verify a single header, e.g. Content-Type
        String contentType = response.getHeader("Content-Type");
        System.out.println("Content-Type header is: " + contentType);

        // Step 4: Assert the header
        assertThat("Header validation failed", contentType, equalTo("application/json; charset=utf-8"));
    }
}


Code explanation:
  • Set base URI
  • Send GET request and get response from API
  • Print a single response header names content type
  • Assert the response header


Maven Dependency:

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


Suggested Posts:

1. Test Single Response Header in RestAssured
2. Test Digesh Auth in RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. How to Test Basic Authentication in RestAssured