Showing posts with label API Automation Testing. Show all posts
Showing posts with label API Automation Testing. Show all posts

How to test Preemptive Authentication in Rest Assured

  



What is Preemptive Authentication?


Preemptive authentication in APIs is an optimization technique where the client (like a browser or an application) sends authentication credentials with the very first request to a protected resource, before the server has explicitly asked for them.

It's based on the assumption that the resource is protected and will require credentials. This contrasts with the more common challenge-response (or reactive) authentication, where the client first makes an unauthenticated request, the server responds with an error (e.g., HTTP 401 Unauthorized) and a challenge (ex: a WWW-Authenticate header), and then the client makes a second, authenticated request.


More about Preemptive Authentication

1. Mechanism
  • Client's First Request: The client includes the authentication header (e.g., Authorization: Basic [credentials] or Authorization: Bearer [token]) in the initial HTTP request.
  • Server Processing: The server receives the request, checks the credentials in the header, validates them, and if successful, processes the request and returns the requested data.
  • Efficiency Gain: If the credentials are valid, the entire transaction is completed in a single round trip between the client and the server.

2. Advantages
  • Reduced Latency and Improved Performance: The primary benefit is eliminating the extra round trip required for the initial challenge and the subsequent authenticated request. This is particularly noticeable in high-latency networks.
  • Fewer Requests: It reduces the total number of HTTP requests and responses by one per resource access, saving bandwidth and server load.

3. Disadvantages
  • Unnecessary Transmission: If the resource ends up not being protected or doesn't require the specific credentials sent, the authentication information (which can be sensitive) was transmitted for no reason.
  • Security Concerns with Basic Auth: If used with Basic Authentication (where credentials are sent in a trivially reversible Base64 format), it makes the credentials more vulnerable if the communication is not encrypted with TLS/SSL (HTTPS), as they are sent even when not strictly needed.
  • Complex Scenarios: It can complicate scenarios involving proxy servers or complex Single Sign-On (SSO) systems where the initial authentication context might change.












To use preemptive basic auth in Rest Assured:

  • Use .auth().preemptive().basic(username, password)
  • This sends the Authorization header directly with the GET request.
  • You can validate response data with assertions.



API to be tested:

https://postman-echo.com/basic-auth

This endpoint requires Basic Authentication

Username: "postman"

Password: "password"













Java Code using Rest Assured:

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

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

public class PreemptiveAuthTest {

    public static void main(String[] args) {

        // Base URI
        RestAssured.baseURI = "https://postman-echo.com";

        // Preemptive Basic Auth GET Request
        given()
            .auth().preemptive().basic("postman", "password")
        .when()
            .get("/basic-auth")
        .then()
            .statusCode(200)
            .body("authenticated", equalTo(true))
            .log().all();
    }
}



Code Explanation:

(a) Set the base URI
(b) Sens the API request
(c) Handle Preemptive authentication by code: auth().preemptive().basic("postman", "password")
(d)  get response of the API and validate by equalTo()
(e) Log response on console



Output:

Once the API is successfully authenticated, we will get below response in JSON form.

{
  "authenticated": true
}



Suggested Posts:

1. Test OAuth2 in RestAssured
2. Validate Request and Response by POJO in RestAssured
3. Test Form Authentication in RestAssured
4. Validate Keys in API in RestAssured
5. Validate XML Schema 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

First Rest Assured Code to Test API

 



To test any API using Rest Assured, you need to follow these steps:

1. Setup

Before writing any Rest Assured test, we need to set up:
  • A Java project (Maven or Gradle is preferred).
  • Add the Rest Assured dependency in pom.xml or build.gradle.
  • Optionally add TestNG or JUnit as the testing framework.

2. Import Required Classes
  • In a Rest Assured test, you typically import:
  • Rest Assured methods for sending requests.
  • Assertions from TestNG/JUnit to validate the response.

3. Define the Base URI
  • You specify the API endpoint you want to test.
  • Example: If you are testing a sample API like https://reqres.in/api/users, this becomes your base URI.

4. Send a Request

You make a request to the API:
  • GET request to fetch data.
  • POST request to send data.
  • PUT/PATCH request to update data.
  • DELETE request to remove data.
The request can include headers, query parameters, or body depending on the API requirements.


5. Capture the Response

When the API responds, Rest Assured stores details such as:
  • Status code (200, 201, 400, 404, etc.)
  • Response body (JSON, XML, text, etc.)
  • Headers (content-type, server info, etc.)
  • Response time

6. Validate the Response

Assertions are applied to verify if the API behaves as expected. Typical checks are:
  • Status code is correct (e.g., 200 for success).
  • Response body contains expected values (e.g., user name, ID).
  • Headers are correct (e.g., content-type is application/json).
  • Response time is within acceptable limits.

7. Organize into a Test Case

The above steps (setup → request → response → validation) are wrapped inside a test method using TestNG or JUnit. This test can then be executed like any other automated test case.

Below we are automating GET API from reqres.in 

























Add 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> <!-- Latest version -->
    <scope>test</scope>
  </dependency>
</dependencies>



Take a simple example of API: 
https://reqres.in/api/users


Rest Assured Code:

To get Status code of given API:

	@Test
	public void test() {
		
		Response response = RestAssured.get("https://reqres.in/api/users?page=2");
		System.out.println(response.statusCode());
		
	}



To log all response on console:

	@Test
	public void test1() {
		RestAssured.baseURI = "https://reqres.in/api/";
		RestAssured.given().get("users?page=2").then().statusCode(200).log().all();
	}



Code Explanation:


LinePurpose
baseURISets the base URL.
given()Prepares request specification.
when().get()Triggers GET request.
then()Begins response verification.
log().all()Logs complete request/response.
statusCode(200)Asserts HTTP status.


Suggested Posts:

1. Execute Playwright Script on Chrome Browser
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