Extraction from JSON in Rest Assured

When working with REST APIs, especially in testing scenarios, extracting specific values from JSON responses is a common task. Rest Assured, a popular Java library for testing RESTful services, makes it easy to perform assertions and validate responses. In this post, we'll explore how to extract values from JSON responses using Rest Assured, which can be incredibly useful for API testing.

What is Rest Assured?

Rest Assured is a Java-based library designed for testing REST APIs. It provides a domain-specific language (DSL) that simplifies the process of creating HTTP requests, sending them, and validating responses. Built with simplicity in mind, Rest Assured makes it easy to perform a wide range of operations on APIs, from sending basic GET requests to extracting values from complex JSON structures.

Basic Setup

To get started with Rest Assured, make sure you include the following dependencies in your pom.xml:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.0.1</version>

    <scope>test</scope>

</dependency>

You can use other versions as well, but version 5.x and above are compatible with Java 11+ and bring several improvements.

Simple JSON Response Extraction

Let's start with a basic example of extracting data from a JSON response. Suppose we send a GET request to an endpoint that returns the following JSON response:

{

    "id": 101,

    "name": "John Doe",

    "email": "johndoe@example.com",

    "address": {

        "street": "123 Main St",

        "city": "New York",

        "zip": "10001"

    }

}

Extracting Single Values

With Rest Assured, extracting a single value from the JSON response is straightforward:

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;


public class JsonExtractionExample {


    public static void main(String[] args) {

        String baseUrl = "https://api.example.com/users/101";

        

        int id = 

            given()

                .get(baseUrl)

            .then()

                .extract().path("id");

        

        System.out.println("ID: " + id);

    }

}

In this example, we extracted the id value from the JSON response using .extract().path("id"). This approach allows us to retrieve the value of a specified key and store it in a variable.

Extracting Nested Values

In cases where the JSON structure is nested, you can specify the path to reach the desired value. For example, to extract the city from the address field:

String city = 

    given()

        .get(baseUrl)

    .then()

        .extract().path("address.city");


System.out.println("City: " + city);

Here, we used address.city to access the nested city field within the address object.

Extracting Multiple Values

Sometimes, you may want to extract multiple values or lists of values. Consider a JSON response that returns an array of user objects:

{

    "users": [

        {"id": 101, "name": "John Doe"},

        {"id": 102, "name": "Jane Smith"},

        {"id": 103, "name": "Emily Davis"}

    ]

}

To extract all user names from this JSON:
List<String> names = 
    given()
        .get("https://api.example.com/users")
    .then()
        .extract().path("users.name");

System.out.println("Names: " + names);

This example uses users.name, where users is the array and name is the key we want to extract. Rest Assured returns all values for the name key in a List<String>.

Advanced JSONPath Expressions

Rest Assured supports JSONPath, which enables complex expressions to filter and retrieve data from JSON documents. For instance, let's say we have a JSON structure with user details and we only want to extract users older than a certain age:

{

    "users": [

        {"id": 101, "name": "John Doe", "age": 25},

        {"id": 102, "name": "Jane Smith", "age": 30},

        {"id": 103, "name": "Emily Davis", "age": 22}

    ]

}

To extract the names of users older than 24:

List<String> names = 
    given()
        .get("https://api.example.com/users")
    .then()
        .extract().path("users.findAll { it.age > 24 }.name");

System.out.println("Users older than 24: " + names);

The expression users.findAll { it.age > 24 }.name uses JSONPath filtering to find all users whose age is greater than 24 and then extracts the name fields.

Extracting Values and Validating in One Step

Rest Assured also allows for simultaneous extraction and validation. For example, if you want to validate that the id is 101 while extracting it:

int id = 

    given()

        .get(baseUrl)

    .then()

        .assertThat().body("id", equalTo(101))

        .extract().path("id");


System.out.println("Validated ID: " + id);

This approach combines validation (using assertThat()) with extraction (.extract().path("id")), which is useful for scenarios where you need both extraction and assertion.

Followers