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
- Convert the response body into a JSON object using Rest Assured’s inbuilt methods.
- This allows easy access to keys and values.
- 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.
- Use assertions (assertThat, containsKey, hasKey) to ensure that expected keys exist in the response.
- This guarantees that the API contract is maintained.
- For JSON objects with nested structures, you can use dot notation in JSONPath to check sub-keys.
- Example: "address.city" should exist inside "address".
- 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 } }
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.
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!" } }
<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