Showing posts with label Rest Assured Framework. Show all posts
Showing posts with label Rest Assured Framework. Show all posts

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

How to test API Response by Rest Assured

  



What is an API Response?

  • When you send a request to an API (like GET, POST, PUT, DELETE), the server processes it and sends back a response.
  • An API Response generally contains:

Status Line → Includes status code (e.g., 200 OK, 404 Not Found, 500 Internal Server Error) and protocol version.

Response Headers → Provide metadata about the response (e.g., Content-Type, Server, Cache-Control).

Response Body → The actual data returned (in JSON, XML, or HTML). Example: user details, order status, product list, etc.


How to Test API Response using Rest Assured

Rest Assured is a Java-based library for testing REST APIs. It provides a fluent interface to validate API responses.


When testing an API response with Rest Assured, you typically check:

1. Response Status Code

  • Verify that the returned status code matches the expected one.
  • Example: A successful request should return 200, creating a resource might return 201, and invalid requests might return 400 or 404.


2. Response Headers
  • Validate that important headers are present and contain correct values.
  • Example: Content-Type should be application/json.

3. Response Body Content
  • Check if the data returned in the body is correct.
  • Example: For a user API, ensure the returned user’s id, name, or email matches what you expect.

4. Response Time / Performance

  • Measure how long the API took to respond.
  • Example: The response time should be within 2 seconds.


5. Schema Validation
  • Verify that the response structure matches the expected JSON or XML schema.
  • Example: Ensures fields like id, name, and email exist and are of the correct data type.

6. Error Handling
  • Check how the API behaves when invalid requests are sent.
  • Example: If you send a request with missing data, the API should return a proper error code and message.


In below example, we are going to test response of API.











This is the API we are going to test: 

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













Below are maven dependencies:

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

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.9.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>




Java Code:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ResponseBodyContainsTest {

    @Test
    public void testResponseBodyContains() {
        // Set the base URI
        RestAssured.baseURI = "https://reqres.in";

        // Send GET request and capture response
        Response response = RestAssured
                .given()
                .when()
                .get("/api/users?page=2")
                .then()
                .statusCode(200) // Validate status code
                .extract()
                .response();

        // Convert response body to String
        String responseBody = response.asString();

        // Print for reference
        System.out.println("Response Body:\n" + responseBody);

        // Use contains() to validate specific strings
        Assert.assertTrue(responseBody.contains("George"), "Expected name not found in response");
        Assert.assertTrue(responseBody.contains("email"), "Expected 'email' field not found in response");
        Assert.assertTrue(responseBody.contains("janet.weaver@reqres.in") == false, "Unexpected email found in response");
    }
}



Code explanation:

1. Set the base URI
2. Send GET request and extract response
3. Convert response body to string type
4. Print response body
5. Use contains() to validate string


Important Points:
  • .contains() is case-sensitive.
  • You can test for presence/absence of any string that should/shouldn't be in the response.
  • Prefer this method for quick validations; for structured validations, use JSON path instead.


Suggested Posts:

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

How to Test Response Headers of API by Rest Assured




What are Response Headers?

When a client (like a browser or an API testing tool) makes an HTTP request to a server, the server responds with:

  • Status Line → (status code like 200 OK, 404 Not Found, etc.)
  • Response Headers → Metadata about the response.
  • Response Body → The actual content/data returned (like JSON, HTML, XML).


Response Headers are key–value pairs that provide additional information about the response.
Examples:
  • Content-Type → format of response body (application/json, text/html, etc.).
  • Content-Length → size of the response body in bytes.
  • Server → server type (e.g., Apache, Nginx).
  • Cache-Control → caching policies.
  • Set-Cookie → cookies sent by the server.
  • Date → time when the response was generated.

Why Test Response Headers in API Testing?

Testing headers is important because they:

  • Ensure correct data format → e.g., Content-Type must be application/json if API promises JSON.
  • Security checks → headers like Strict-Transport-Security, X-Content-Type-Options, etc. help secure APIs.
  • Performance checks → Cache-ControlExpires help manage caching.
  • Compliance checks → some APIs must include custom headers for authorization, tracking, etc.
  • Troubleshooting → headers help identify server/software versions or errors.











Steps to test response headers using Rest Assured:

  • Set Base URI using RestAssured.baseURI
  • Send GET Request using given().get(endpoint)
  • Extract Headers from the response
  • Verify Specific Headers using assertions



Maven Dependency for Rest Assured

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



Java Code: Get and Test Response Headers

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.http.Headers;
import io.restassured.http.Header;

public class GetResponseHeaders {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Send GET request
        Response response = RestAssured
                .given()
                .get("/users?page=2");

        // Step 3: Print all headers
        Headers allHeaders = response.getHeaders();
        System.out.println("===== All Response Headers =====");
        for (Header header : allHeaders) {
            System.out.println(header.getName() + ": " + header.getValue());
        }

        // Step 4: Get a specific header
        String contentType = response.getHeader("Content-Type");
        String server = response.getHeader("Server");

        System.out.println("\nContent-Type: " + contentType);
        System.out.println("Server: " + server);

        // Step 5: Validate headers using assertions
        if (!"application/json; charset=utf-8".equals(contentType)) {
            throw new AssertionError("Expected Content-Type not found!");
        }

        if (!"cloudflare".equalsIgnoreCase(server)) {
            throw new AssertionError("Expected Server header value not found!");
        }

        System.out.println("\n Header validations passed successfully!");
    }
}


Code explanation:

1. Set Base URI
2. Send GET Request
3. Print all headers on console
4. Get a specific header
5. Validate headers using assertions



Output:

===== All Response Headers =====
Date: Mon, 28 Jul 2025 14:00:00 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: cloudflare
...

Content-Type: application/json; charset=utf-8
Server: cloudflare

Header validations passed successfully!


Useful Methods in Rest Assured

  • response.getHeaders() – Gets all headers
  • response.getHeader("Header-Name") – Gets a specific header
  • response.header("Header-Name") – Alias for getHeader


Suggested Posts:

1. Test PUT API in RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test DELETE API in RestAssured
4. How to Test SOAP API by RestAssured
5. How to Test Basic Authentication in RestAssured

How to Test GET API by Rest Assured

 



What is Rest Assured?

  • Rest Assured is a Java-based library used for testing RESTful APIs.
  • It provides a domain-specific language (DSL) that makes writing HTTP request tests simple and readable.
  • You can use it to send requests like GET, POST, PUT, DELETE, etc., and then validate responses (status code, headers, body, etc.).
  • It integrates well with JUnit, TestNG, Maven, and CI/CD tools.

To test a GET API using Rest Assured in Java, you can follow the steps below. We'll walk through the process and test the endpoint:









API Endpointhttps://reqres.in/api/users

This API returns paginated user data in JSON format.















Basic Steps to Test GET API

  • Add Rest Assured dependency in your pom.xml (if using Maven).
  • Set the Base URI.
  • Send the GET request.
  • Validate the Response (status code, headers, body).
  • Log response (optional but useful for debugging).


Maven Dependency (pom.xml):

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



Java Code to Test GET API

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

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

public class GetUserApiTest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in";

        // Step 2: Send GET request and validate
        given()
            .log().all()  // Logs the request details
        .when()
            .get("/api/users?page=2")  // Endpoint
        .then()
            .log().all()  // Logs the response details
            .assertThat()
            .statusCode(200)  // Validate HTTP Status code
            .body("data", notNullValue())  // Validate response body contains 'data'
            .body("data.size()", greaterThan(0))  // Validate non-empty data
            .body("data[0].id", notNullValue());  // Validate user id present
    }
}



Explanation of Code:

LinePurpose
baseURISets the base URL for the request.
given()Prepares request specification.
log().all()Logs all request and response data for visibility.
get()Triggers the GET request to the specified endpoint.
then()Begins response verification.
statusCode(200)Verifies the status code is 200 (OK).
body(...)Verifies the presence and contents of specific JSON fields.



Response Validation:

Below is the screenshot of code which is validating GET API response.







In above screenshot, data is json array, and code is validating that data contains any values or not or we can say it is null or not. In the second line we are verifying size of array data is greater than 0 or not and in third line we are verifying, first element of data array that is id, is null or contains any value.


Sample JSON Output from API

{
  "page": 2,
  "per_page": 6,
  "data": [
    {
      "id": 7,
      "email": "michael.lawson@reqres.in",
      "first_name": "Michael",
      "last_name": "Lawson",
      ...
    }
  ]
}


Suggested Posts:

1. Validate Keys in API in RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Test DELETE API in RestAssured
5. How to Test Basic Authentication in RestAssured

Features of Rest Assured Framework

 



What is Rest Assured?

  • Rest Assured is an open-source Java library designed specifically for testing RESTful web services (APIs).
  • It simplifies the process of sending HTTP requests (like GET, POST, PUT, DELETE) and validating responses without requiring a lot of boilerplate code.
  • Instead of writing complex HTTP client code, testers can write concise, readable, and maintainable API tests.
  • It provides a domain-specific language (DSL) for writing readable, maintainable, and expressive API test cases.


Why Rest Assured is Used
  • To automate API testing efficiently.
  • To verify functionality, performance, and security of APIs.
  • To reduce manual testing effort (compared to tools like Postman).
  • To ensure APIs return correct status codes, headers, and data.








Below are some key features of Rest Assured Framework:


FeatureDescription
HTTP Methods SupportSupports GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.
Request CustomizationAllows adding headers, query parameters, path parameters, cookies, and body data easily.
Response ValidationProvides easy methods for verifying status code, headers, content types, response body, etc.
JSON & XML ParsingBuilt-in support for parsing and asserting on JSON and XML responses.
AuthenticationSupports Basic, Digest, Form, OAuth1, OAuth2, and custom authentication.
IntegrationCan be used with JUnit, TestNG, Cucumber, and other Java testing tools.
LoggingSupports logging request and response data for debugging purposes.
Schema ValidationCan validate responses against JSON/XML schema.
Serialization/DeserializationEasily works with POJOs using libraries like Jackson or Gson.


Suggested Posts:

1. Test SOAP API in RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Test DELETE API in RestAssured
5. How to Test Status Line of API by RestAssured