How to Validate Keys in API in Rest Assured

 



To validate that a JSON response body contains a specific key using hasKey() from Hamcrest Matchers in Rest Assured, 

follow this step-by-step guide using the endpoint:


1. Send API Request

  • Use Rest Assured to send an HTTP request (GET, POST, etc.) to the API endpoint.
  • Capture the response in a Response object

2. Extract JSON Response

  • Convert the response body into a JSON object using Rest Assured’s inbuilt methods.
  • This allows easy access to keys and values.

3. Check for Key Existence
  • Extract the JSON as a map or use JSONPath.
  • Validate whether specific keys are present in the response.
  • Example: If response has { "id": 101, "name": "Alex" }, you should check whether keys id and name exist.

4. Assertion for Keys
  • Use assertions (assertThat, containsKey, hasKey) to ensure that expected keys exist in the response.
  • This guarantees that the API contract is maintained.

5. Validate Nested Keys
  • For JSON objects with nested structures, you can use dot notation in JSONPath to check sub-keys.
  • Example: "address.city" should exist inside "address".

6. Schema Validation (Optional)
  • Instead of validating keys one by one, you can use a JSON Schema file.
  • Schema validation ensures all required keys are present with correct data types.









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






Goal: Validate that the JSON response has a key like "page""data", etc.


Code Example in Java (Rest Assured + Hamcrest hasKey())

import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class HasKeyExample {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://reqres.in";

        given()
        .when()
            .get("/api/users?page=2")
        .then()
            .statusCode(200)
            .body("$", hasKey("page"))          // top-level key
            .body("$", hasKey("per_page"))      // another top-level key
            .body("$", hasKey("data"))          // array of users
            .body("support", hasKey("url"))     // nested key inside "support"
            .body("support", hasKey("text"));   // another nested key
    }
}




Code explanation: 

(a) In main method, set base URI
(b) Send request to api and get response.
(c) In response body, we have to use hasKey() to validate Json keys as shown in the code.


Explanation:

  • "$" refers to the root of the JSON response.
  • hasKey("keyName") checks if a key exists at that JSON level.
  • body("support", hasKey("url")) checks if the support object has a url key.



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

Below is the json resposne of the API, having json elements like key-value pairs of page,per_page,total,etc.

{
    "page": 2,
    "per_page": 6,
    "total": 12,
    "total_pages": 2,
    "data": [...],
    "support": {
        "url": "https://reqres.in/#support-heading",
        "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
    }
}



Maven Dependencies

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
</dependency>


Suggested Posts:

1. Validate API Response from Database in RestAssured
2. Validate JSON Schema in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Keys in API in RestAssured
5. How to Test SOAP API in RestAssured