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.
{ "user": { "id": 101, "name": "Himanshu", "roles": ["admin", "editor"] } }
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.
- Apply JSONPath expressions (like data.id, user.name, etc.) on the response to extract specific values.
- Once extracted, the values can be: Verified against expected values (assertions), Reused in subsequent requests (chaining).
- 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".
https://reqres.in/api/users?page=2
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); } } }
| Task | JsonPath Expression |
|---|---|
| Total number of users | jsonPath.getInt("total") |
| Email of first user | jsonPath.getString("data[0].email") |
| List of all emails | jsonPath.getList("data.email") |
| ID of last user | jsonPath.getInt("data[-1].id") |
<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