Showing posts with label API Testing with Rest Assured. Show all posts
Showing posts with label API Testing with Rest Assured. Show all posts

How to test Basic Authentication by using Rest Assured

 



What is Basic authentication?

Basic authentication is a straightforward, widely supported, and non-interactive method for an API client (like a web browser or mobile app) to provide a user's credentials (typically a username and password) when making an API request. It's one of the simplest authentication schemes built into the HTTP protocol.


More about Basic Authentication

1. The Core Mechanism

Basic authentication works by combining the username and password into a single string, separating them with a single colon, like this: username:password.


2. Encoding

This combined string is then Base64 encoded. Base64 is an encoding scheme, not an encryption method; it is easily reversible and is used primarily to ensure that the credentials can be transmitted across the internet without issues arising from special characters. It does not provide security or confidentiality.


3. The HTTP Header

The resulting Base64-encoded string is then included in the API request within the Authorization HTTP header. The header takes the format:

Authorization:Basic ⟨base64-encoded string⟩

For example, if the username is user and the password is pass, the combined string is user:pass. After Base64 encoding, this might become dXNlcjpwYXNz. The header sent in the request would be:

Authorization:Basic dXNlcjpwYXNz


4. Server-Side Verification

When the API server receives the request, it performs the following steps:

  • It checks for the Authorization header.
  • It verifies that the scheme is Basic.
  • It Base64-decodes the credential string to retrieve the original username:password.
  • It separates the username and password.
  • It attempts to validate these credentials against its user database.

If the credentials are valid, the server processes the API request. If they are invalid, the server typically responds with an HTTP status code of 401 Unauthorized and often includes a WWW-Authenticate header to prompt the client for correct credentials.


To use Basic Authentication in a GET API via Rest Assured, you need to include the username and password using auth().basic(username, password) in your request.









In Basic authentication:

  • The client sends the username and password encoded in Base64 in the request headers.

  • The format is:

Authorization: Basic Base64(username:password)



API to be tested:

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

Username: postman

Password: password












Maven Dependency:

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



Full Java Code

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

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

public class BasicAuthGetAPI {

    public static void main(String[] args) {
        // Set Base URI
        RestAssured.baseURI = "https://postman-echo.com";

        // Send GET request with basic auth
        Response response = given()
                .auth().basic("postman", "password") // Basic Auth
        .when()
                .get("/basic-auth") // GET Endpoint
        .then()
                .statusCode(200) // Check status code
                .body("authenticated", equalTo(true)) // Validate response body
                .extract().response();

        // Print the response
        System.out.println("Response:\n" + response.prettyPrint());
    }
}



Code Explanation:

(a) Set the bae URI
(b) Send GET request with basic authentication code
(c) Get response and validate with equalTo()
(d) Print the output in console



Output:

Got the response of the GET API in the JSON form as

{
  "authenticated": true
 
}




Suggested Posts:

1. Validate JSON Schema in RestAssured
2. Validate Request and Response by POJO in RestAssured
3. Extract Response by JSONPath in RestAssured
4. Validate Keys in API in RestAssured
5. Validate XML Schema in RestAssured

How to validate Request and Response by using POJO in Rest Assured

 



What is Request Validation?

  • Request Validation means verifying that the data you are sending to the API in the request (body, headers, parameters) is correct, structured properly, and matches the expected API contract.
  • Example: If an API expects a User object with fields {id, name, email}, your request body should have exactly these fields, with valid values.


When using POJO:
  • You first create a Java POJO class (Plain Old Java Object) with fields like id, name, email.
  • You create an object of this POJO and send it as a request body.
  • Since the POJO defines structure and types, it automatically validates that the request matches the expected schema before sending.

When using POJO:
  • You can map the API response directly into a POJO object.
  • Then validate fields using assertions.
  • If the API response is missing a field or has the wrong type, the mapping will fail or the assertions won’t match — this helps you ensure the response contract is correct.

What is Response Validation?
  • Response Validation means verifying that the API response you get back has the correct structure, keys, and values as per the expected contract.
  • Example: If the response should return a User object {id, name, email}, you validate whether the API actually returned all these fields with correct types and expected values.

How to Validate Request & Response using POJO in Rest Assured

1. Define POJO Classes
  • Create Java classes representing request and response objects.
  • Each class has private fields, constructors, getters, and setters.

2. Request Validation
  • Create an object of the Request POJO.
  • Populate it with required values.
  • Pass it to the Rest Assured request body.
  • The POJO ensures the structure of the request matches what the API expects.

3. Send Request
  • Rest Assured converts the POJO into JSON and sends it to the API.

4. Response Validation
  • Deserialize the API response back into the Response POJO.
  • Validate fields by comparing actual values against expected ones.
  • If a key is missing or data type mismatches, deserialization or assertion will fail.

Here’s how you can create a POJO classsend a POST request to https://reqres.in/api/users, and validate the response and status code using Rest Assured in Java.









1. POJO Class for Request

Below is POJO class of API request, having two attributes that are name and job. In POJO class below, we have parameterized constructor of the class and respective getter and setter methods for the attributes.

public class User {
    private String name;
    private String job;

    public User() {}

    public User(String name, String job) {
        this.name = name;
        this.job = job;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}



2. POJO Class for Response

Below is POJO class of API response, having four attributes that are name, job, id and createdAt. In POJO class below, we have respective getter and setter methods for the attributes.

public class UserResponse {
    private String name;
    private String job;
    private String id;
    private String createdAt;

    public UserResponse() {}

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
}


 
3. Rest Assured Test Code

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

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

        // Request Body
        User user = new User("Himanshu", "Engineer");

        // POST Request
        Response response = given()
                .contentType(ContentType.JSON)
                .body(user)
            .when()
                .post("/users")
            .then()
                .statusCode(201)
                .body("name", equalTo("Himanshu"))
                .body("job", equalTo("Engineer"))
                .extract().response();

        // Deserialize Response to POJO
        UserResponse userResp = response.as(UserResponse.class);

        // Print Response Fields
        System.out.println("ID: " + userResp.getId());
        System.out.println("Created At: " + userResp.getCreatedAt());
    }
}



Code explanation:

(a) Set base URI of the API.
(b) Create object of request POJO class User.java, by putting values  - Himanshu, Engineer in User constructor.
(c) Set POST request to the API
(d) De serialize response to the POJO class
(e) Print response fields on console.



Maven Dependencies

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.16.1</version>
    </dependency>
</dependencies>


Suggested Posts:

1. Test Basic Authentication of API 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 a Single Response Header by Rest Assured

 



What is response header in API?

A response header in an API is metadata returned by the server along with the body of the response. It provides additional information about the response, such as:

  • Content-Type → tells the format of the response (e.g., application/json, text/html).
  • Content-Length → specifies the size of the response body.
  • Server → identifies the server software handling the request.
  • Cache-Control → gives caching directives to the client.
  • Set-Cookie → passes cookies from server to client.

These headers don’t contain the main data (which is usually in the response body), but they are critical for understanding how to interpret and handle the response.


When testing with Rest Assured, you usually verify that:

1. The response contains a specific header

  • Example: Check if the header Content-Type is present.
2. The header has the expected value
  • Example: Verify that Content-Type equals application/json.
3. The header value matches certain conditions
  • Example: Check if the value starts with application/.
In Rest Assured, testing a single response header means making an API request, capturing the response, and then asserting the value of that particular header against the expected outcome.








We want to:

  • Send a GET request to https://reqres.in/api/users?page=2
  • Extract and validate a specific response header (example: Content-Type)

Below is the screenshot of response of API: https://reqres.in/api/users?page=2













To test a single response header in a GET API using Rest Assured in Java, you can follow these steps:

  • Set the base URI
  • Send a GET request
  • Extract the specific header
  • Validate it using assertion



Sample Java Code Using Rest Assured

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class GetResponseHeaderTest {

    public static void main(String[] args) {
        
        // Step 1: Set base URI
        RestAssured.baseURI = "https://reqres.in";

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

        // Step 3: Print and verify a single header, e.g. Content-Type
        String contentType = response.getHeader("Content-Type");
        System.out.println("Content-Type header is: " + contentType);

        // Step 4: Assert the header
        assertThat("Header validation failed", contentType, equalTo("application/json; charset=utf-8"));
    }
}


Code explanation:
  • Set base URI
  • Send GET request and get response from API
  • Print a single response header names content type
  • Assert the response header


Maven Dependency:

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


Suggested Posts:

1. Test Single Response Header in RestAssured
2. Test Digesh Auth in 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 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