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

How to test Form Authentication by using rest Assured

 



What is Form Authentication?

  • Form Authentication is a type of authentication where the user provides credentials (like username and password) through an HTML form (usually a login page).
  • The credentials are sent to the server (often via POST request) → if valid, the server creates a session (often maintained using cookies or tokens) → and the client can then access protected resources.
This is different from Basic/Digest authentication, where credentials are passed in HTTP headers.
Form-based login is very common in web applications.


How to test Form Authentication using Rest Assured
When testing Form Authentication in Rest Assured, the process usually looks like this:

1. Provide login credentials

  • Supply the username and password that the login form requires.

2. Tell Rest Assured the login form details
  • Specify the login page (form action URL), and the parameter names for username and password fields (e.g., username, password).

3. Send login request
  • Rest Assured submits the credentials just like a browser submitting a login form.

4. Handle cookies/session

  • Once the server authenticates, it typically returns a session cookie or auth token.

  • Rest Assured automatically manages these cookies so subsequent requests can use the authenticated session.

5. Access protected resources
  • Now you can send API requests that require authentication and verify the response.







How Form Auth Works in Rest Assured:


Rest Assured provides:

.formAuth(loginUrl, usernameField, passwordField, username, password)


This simulates a form-based login by:

  • Making a POST request to the login URL
  • Submitting the credentials using field names (like usernamepassword)
  • Then it stores session/cookie for further requests like GETPOST, etc.

Sample API for Form Auth

We will use: https://the-internet.herokuapp.com/login (a public test site)

  • Login URLhttps://the-internet.herokuapp.com/authenticate

  • Username Field Name: username

  • Password Field Name: password

  • Username: tomsmith

  • Password: SuperSecretPassword!


















Java Code with Rest Assured:

import io.restassured.RestAssured;
import io.restassured.filter.session.SessionFilter;
import static io.restassured.RestAssured.*;

public class FormAuthExample {
    public static void main(String[] args) {

        // Create session filter to maintain session across requests
        SessionFilter session = new SessionFilter();

        // Step 1: Log in using form-based auth
        given()
            .baseUri("https://the-internet.herokuapp.com")
            .filter(session)
            .formParam("username", "tomsmith")
            .formParam("password", "SuperSecretPassword!")
        .when()
            .post("/authenticate")
        .then()
            .statusCode(302);  // Expect redirect on successful login

        // Step 2: Access GET API after login
        given()
            .baseUri("https://the-internet.herokuapp.com")
            .filter(session)
        .when()
            .get("/secure")
        .then()
            .statusCode(200)
            .log().body();  // Print response to confirm access
    }
}


Code explanation:

(a) Create session filter and maintain session across requests
(b) Login using form based authentication
(c) Access GET API after login
(d) Print the response on console


Maven Dependencies

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


Suggested Posts:

1. Test Status Line of API in RestAssured
2. Test Form Authentication 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 Status Line of API by Rest Assured

 



What is the Status Line of an API?

  • The status line is the first line of the HTTP response sent by the server.
  • It provides three parts:

HTTP Version → Example: HTTP/1.1 or HTTP/2
Status Code → Example: 200, 404, 500
Reason Phrase → Example: OK, Not Found, Internal Server Error

Example of a status line:
HTTP/1.1 200 OK

In this,
  • HTTP/1.1 → HTTP protocol version
  • 200 → Status code (success)
  • OK → Reason phrase

How to Test Status Line of API in Rest Assured

When testing an API’s status line using Rest Assured, you:
  • Send the API Request (GET, POST, etc.).
  • Extract the Status Line from the response.
  • Verify the Status Line against the expected value.

What to Check in Status Line:
  • Ensure HTTP version is correct (e.g., HTTP/1.1).
  • Ensure status code is as expected (e.g., 200).
  • Ensure reason phrase is correct (e.g., OK).


To test the status line of a GET API using Rest Assured in Java, you need to understand what a status line is and how to retrieve it.
















Example:

HTTP/1.1 200 OK


Steps to Test Status Line Using Rest Assured

  • Set the base URI.
  • Use given() to prepare the request.
  • Use .when().get() to make the GET call.
  • Use .then().statusLine() to verify the status line.
  • You can also extract the status line using .extract().statusLine().

API to be automated: 
https://reqres.in/api/users?page=2


Maven Dependencies:

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





Java Code Using Rest Assured to Test Status Line

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

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

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

        // Send GET request and validate status line
        given()
            .when()
            .get("/api/users?page=2")
            .then()
            .assertThat()
            .statusLine("HTTP/1.1 200 OK");  // Validate full status line

        // Optionally, print the actual status line
        Response response = get("/api/users?page=2");
        String actualStatusLine = response.getStatusLine();
        System.out.println("Status Line is: " + actualStatusLine);
    }
}



Code explanation:

1. Set the base URI
2. Send GET API request
3. validate status line
4. Print the actual status line on console



Output:

Status Line is: HTTP/1.1 200 OK



At a glance:
  • Use .statusLine("HTTP/1.1 200 OK") to validate the exact status line.
  • Use .getStatusLine() to fetch and print it.
  • This is useful to ensure your API response is well-formed and meets expectations.


Suggested Posts:

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

Rest Assured Framework Overview for API Testing




What is Rest Assured?

  • Rest Assured is a Java-based library designed to simplify the process of testing REST APIs.
  • Instead of manually sending HTTP requests and parsing responses, Rest Assured provides a fluent and easy-to-use API to handle all of that.
  • It integrates smoothly with JUnit or TestNG, so it fits into existing test automation frameworks.
  • It is widely used in test automation frameworks for API testing, especially in Java environments.

Why Do We Need Rest Assured?

When testing APIs, we need to:
  • Send Requests → GET, POST, PUT, DELETE, etc.
  • Validate Responses → status codes, headers, response time, and body data.
  • Handle Data Formats → JSON, XML, or plain text.
Without a framework, doing all this means writing a lot of boilerplate code (like setting up HTTP clients, handling JSON parsing, etc.).


Where It Fits in Testing
  • Functional Testing → Ensures API endpoints return correct responses.
  • Regression Testing → Quickly retest APIs when code changes.
  • Integration Testing → Check how APIs interact with databases, services, or other systems.
  • End-to-End Testing → APIs can be tested as part of larger workflows.

Why Rest Assured vs Other Options?

  • Compared to using Postman → Rest Assured allows automation, integration with CI/CD, and reusable test suites.
  • Compared to writing raw HTTP requests in Java → Rest Assured removes complexity by handling requests, responses, and validations out of the box.










Rest Assured Testing Lifecycle

1. Test Planning & Setup
  • Identify the API endpoints you want to test (e.g., /login, /users, /orders).
  • Understand the request types (GET, POST, PUT, DELETE, etc.).
  • Gather information about:
Base URI (server address)
Authentication (Basic, OAuth, etc.)
Request/response formats (JSON, XML).


2. Request Specification
  • Define the base URI and common headers (like Content-Type).
  • Prepare request payloads if the API requires input (e.g., JSON for POST requests).
  • Add authentication details if needed.
This step ensures consistency and avoids repeating setup for every test.


3. Send the Request
  • Use Rest Assured to send an HTTP request (GET, POST, PUT, DELETE, etc.) to the server.
  • The request is executed, and the API server processes it.

4. Receive the Response
  • Capture the response sent back by the server.
  • This includes:
Status code (200, 400, 404, 500, etc.)
Response body (JSON/XML data)
Response headers (content type, server details, etc.)
Response time (performance aspect).


5. Validation & Assertions
  • Verify the status code (e.g., 200 for success, 201 for resource creation).
  • Validate headers (e.g., Content-Type is application/json).
  • Assert on the response body:
Correct data returned?
Fields present or missing?
Values match expectations?


6. Test Reporting
  • Test results are logged (pass/fail).
  • If integrated with frameworks (TestNG/JUnit), detailed reports are generated.
  • Can also be hooked into CI/CD pipelines (like Jenkins, GitHub Actions) for automated reporting.

7. Test Maintenance & Reuse
  • Reuse request specifications for multiple test cases.
  • Update tests when API contracts change.
  • Keep validations flexible so they remain maintainable as APIs evolve.

The request is executed, and the API server processes it.

Common Use Cases

  • Functional testing of REST APIs
  • Integration testing
  • Regression testing
  • Automated tests in CI/CD pipelines
  • Validation of API contracts (schema testing)

Technologies/Tools Rest Assured Works Well With

  • Testing Frameworks: JUnit, TestNG, Cucumber
  • Build Tools: Maven, Gradle
  • Serialization Libraries: Jackson, Gson
  • Mocking Tools: WireMock, Mockito
  • CI Tools: Jenkins, GitHub Actions, GitLab CI

How Rest Assured Fits into Test Automation Framework

Rest Assured can be part of the test layer in a test automation framework where:

  • Test data is read from external sources (CSV, Excel, JSON, DB).
  • Test cases are written in BDD format (with Cucumber).
  • Assertions are performed on API responses.
  • Reports are generated using tools like Allure or Extent Reports.


Advantages

  • Simplifies REST API testing in Java
  • Readable, maintainable syntax
  • Rich feature set for validation and assertions
  • Seamless integration with Java ecosystem

Limitations

  • Supports only REST APIs (not SOAP)
  • Tied to Java ecosystem (not suitable for Python, JavaScript, etc.)
  • UI-less (not meant for front-end automation)


Suggested Posts:

1. Features of RestAssured Framework
2. First RestAssured Code to Test API
3. Test PUT API in RestAssured
4. Test DELETE API in RestAssured
5. How to Test Status Line of API by 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 checksCache-Control, Expires 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