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

How to test Digest Auth by using Rest Assured

 



What is Digest Authentication?

  • Digest Authentication is a security mechanism used by servers to verify the identity of a client (user or system) before allowing access to protected resources.
  • Unlike Basic Authentication (where username and password are sent in plain text encoded with Base64)

Digest Authentication is more secure because:

  • It applies a hashing algorithm (like MD5/SHA) to the credentials before sending them over the network.
  • The server sends a nonce (a random value) to the client.
  • The client combines the nonce, username, password, HTTP method, and requested URI → then hashes them → and sends the hashed value back.
  • The server performs the same hashing process and compares results. If they match → authentication succeeds.

How to test Digest Authentication in Rest Assured

In Rest Assured, testing Digest Authentication involves these steps:

1. Specify authentication type as Digest
  • Instead of default/basic authentication, explicitly tell Rest Assured to use digest authentication.
2. Provide credentials
  • Pass the username and password required by the server for authentication.
3. Send the request
  • Rest Assured automatically performs the handshake with the server (sending nonce, hashing, etc.).
4. Validate the response
  • Once authenticated, the server will return the protected resource.
  • You can then test the response body, status code, or headers to confirm access was granted.



API Endpoint for Testing:

https://httpbin.org/digest-auth/auth/user/passwd


This endpoint expects:

  • Username: user

  • Password: passwd

















Steps to Use Digest Auth in Rest Assured:


Maven dependencies:

<!-- Maven Dependency -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.4.0</version>
    <scope>test</scope>
</dependency>




Java Code: Digest Auth with Rest Assured

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

public class DigestAuthExample {

    public static void main(String[] args) {

        RestAssured.baseURI = "https://httpbin.org";

        given()
            .auth()
            .digest("user", "passwd") // Digest Auth
        .when()
            .get("/digest-auth/auth/user/passwd")
        .then()
            .statusCode(200)
            .body("authenticated", equalTo(true))
            .body("user", equalTo("user"))
            .log().all(); // Print full response
    }
}


Code explanation:

(a) Set base URI
(b) Set request by digest authentication code
(c) Get response and log response on console.



Output:

{
  "authenticated": true,
  "user": "user"
}

Above is the response of API which is logged on console.


Suggested Posts:

1. Overview of RestAssured
2. Features of RestAssured
3. Test DELETE API in RestAssured
4. First RestAssured Code to Test API
5. How to Test Basic Authentication in RestAssured

How to Test a PUT API by Rest Assured






What is a PUT API?

  • PUT is an HTTP method used to update an existing resource on the server.
  • It can also be used to create a resource if it doesn’t exist, but typically it’s for updates.
  • The client sends the complete updated data to the server at a specified URL (endpoint).
  • Idempotent: Calling the same PUT request multiple times will have the same effect as calling it once.


Example scenario:
  • Suppose you have a user with id = 5.
  • A PUT request to /users/5 with new data (like updated name and job) will update the user’s information on the server.

How to Test a PUT API in Rest Assured
  • Set the Base URI: Define the server address where your API is hosted.
  • Specify the Endpoint: Use the URL of the resource you want to update.
  • Prepare the Request Body: Create a JSON object containing the updated data (like new name, job, or other attributes).
  • Send PUT Request: Send the PUT request along with the JSON body to the server.
  • Validate Response:
Status Code: Usually 200 OK or 204 No Content.
Response Body: Check if it contains the updated data or confirmation.
Headers: Verify content type, server info, etc.
  • Optional: You can perform a GET request afterward to ensure that the resource has been updated correctly.


To test a PUT API using Rest Assured in Java, you'll follow these steps:













Steps to test PUT API using Rest Assured

  • Add dependencies (Maven or Gradle)
  • Set the Base URI
  • Create the JSON request body using JSONObject
  • Send PUT request using given()
  • Validate the response

The endpoint we'll use:
https://reqres.in/api/users/2 — This updates user with ID 2.











Maven Dependency

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230227</version>
    </dependency>
</dependencies>



Java Code using Rest Assured & JSONObject

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.json.JSONObject;

import static io.restassured.RestAssured.given;

public class PutApiTest {

    public static void main(String[] args) {

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

        // Step 2: Create JSON body using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "Software Engineer");

        // Step 3: Send PUT request and get the response
        Response response = given()
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .when()
                .put("/users/2")
                .then()
                .statusCode(200)  // Verifying status code
                .extract()
                .response();

        // Step 4: Print response
        System.out.println("Response Body:");
        System.out.println(response.getBody().asPrettyString());
    }
}



Code Explanation:

LinePurpose
RestAssured.baseURISets the base server endpoint
JSONObjectBuilds the request payload
given().header().body()Prepares the request with header & body
.put("/users/2")Sends PUT request to /users/2
.statusCode(200)Asserts response code is 200 OK
.response()Extracts full response
.asPrettyString()Converts raw response to formatted JSON string


Response:

Put respond with status code of 204 or 200, that means API executes successfully and performed update operation.

{
    "name": "Himanshu",
    "job": "Software Engineer",
    "updatedAt": "2025-07-28T13:48:32.054Z"
} 



Suggested Posts:

1. Test Digest Auth by RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test OAth2 in RestAssured
4. Validate Request and Response in POJO by RestAssured
5. How to Test Basic Authentication in RestAssured

How to Test a POST API by Rest Assured

 



What is a POST API?

  • A POST API is an HTTP endpoint that allows a client to send data to the server.
  • The data is usually sent in the request body in formats like JSON, XML, or form data.
  • Common uses of POST APIs:

Creating a new resource (e.g., creating a new user in a system).
Submitting forms (login, registration, etc.).
Sending files or data for processing.


How to Test a POST API in Rest Assured

When testing a POST API in Rest Assured, you typically perform these steps:

1. Set the Base URI
  • Define the API host (e.g., https://reqres.in).
2. Define the Request Body
  • Prepare the JSON (or other format) data that you want to send.
3. Send the POST Request
  • Use Rest Assured to send the request to the endpoint (e.g., /api/users).
4. Validate Response Status Code
  • Check if the response code is correct (usually 201 Created for a successful POST).
5. Verify Response Body
  • Ensure the response contains the expected data (like the new id or confirmation message).
6. Check Response Headers (Optional)
  • Validate Content-Type, Location, etc., to ensure proper response formatting.


To test a POST API using Rest Assured with a JSONObject in Java, follow these steps:










Step-by-Step Implementation

1. Add Rest Assured Dependency

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

    <!-- JSON Library -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
    </dependency>
</dependencies>


API to be tested: 

POST https://reqres.in/api/users


















Sample request body:

{
  "name": "Himanshu",
  "job": "QA Engineer"
}



Expected response (201 Created):

{
  "name": "Himanshu",
  "job": "QA Engineer",
  "id": "123",
  "createdAt": "2025-07-28T..."
}



3. Java Code to Test POST API using JSONObject

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.http.ContentType;
import org.json.JSONObject;

public class PostAPITest {

    public static void main(String[] args) {

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

        // Step 2: Create Request Payload using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "QA Engineer");

        // Step 3: Make POST Request
        Response response = RestAssured
            .given()
                .contentType(ContentType.JSON)
                .body(requestBody.toString())
                .log().all()
            .when()
                .post("/users")
            .then()
                .log().all()
                .statusCode(201)
                .extract().response();

        // Step 4: Print Response Fields
        System.out.println("ID: " + response.jsonPath().getString("id"));
        System.out.println("Created At: " + response.jsonPath().getString("createdAt"));
    }
}



Code Explanation:

LinePurpose
RestAssured.baseURISets the base URL.
JSONObjectBuilds the JSON body using key-value pairs.
given().contentType().body()Prepares the request with headers and body.
post("/users")Sends POST request to the endpoint.
statusCode(201)Verifies the response status.
response.jsonPath()Extracts values from JSON response.



Sample Output:

Request method:	POST
Request URI:	https://reqres.in/api/users
Request body:
{
    "name": "Himanshu",
    "job": "QA Engineer"
}
Response Status Code: 201
Response body:
{
    "name": "Himanshu",
    "job": "QA Engineer",
    "id": "867",
    "createdAt": "2025-07-28T14:30:55.098Z"
}


Suggested Posts:

1. Test Digest Auth by RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Overview of RestAssured Framework
5. How to Test Basic Authentication in RestAssured