API Automation Testing: Headers, Cookies & Parameters with Rest Assured

API Automation Testing: Rest Assured Framework - Comprehensive Overview

Rest Assured Framework Overview

In API automation testing, ensuring proper handling of headers, cookies, and parameters is essential for accurately simulating real-world API interactions. These elements carry crucial information between the client and the server, influencing the behavior and outcome of API requests and responses. Rest Assured provides convenient methods for setting headers, adding cookies, and specifying various types of parameters. API automation allows the execution of a large number of test cases in a short amount of time, reducing the overall testing cycle.

API Automation Testing: Rest Assured Framework - Comprehensive Overview

Headers:

Headers are a part of the HTTP request that contains additional information about the request. They are small pieces of information carrying significant weight in determining how data is transmitted, processed, and secured across the web. Headers are key-value pairs, where the key is a string that describes the type of information being provided, and the value is the actual data being provided.

Components of Headers:

Cookies:

Cookies are small pieces of data stored on the client’s side by the web server. They are used to maintain user session state, track user behavior, and store user preferences. Cookies are sent by the client to the server with every subsequent request, allowing the server to identify and personalize the user experience.

Importance of Cookies in API Testing:

Parameters:

Parameters are additional details included in the URL along with the request.

Types of Parameters:

Example:

Retrieve the details of the employee whose id is “123”.

“api/employees/{id}”

Here {Id} is a path parameter. 

Example: To fetch details of employee id 123, the request will be: “api/employees/123”

Query parameters appear after the question mark symbol ‘?’ in the URL. 

These parameters help to get specific data from the API.

Example 1:

Retrieve a list of employees whose designation is QA Engineer.

/employee?designation=qa

In the above example, ?designation=qa is the query parameters.

The question mark denotes the start of a query parameter. There can be multiple query parameters in the URL. It can be achieved by separating parameters through an ‘&’ sign.

Example 2:

Retrieve a list of employees whose designation is QA Engineer and experience is 3 years.

/ employee?designation=qa&exp=3

Uses of Query Parameters:

Example: Query parameters help you navigate to the pages by telling the API which page of results you want to see and how many items to show per page.

Project Configuration:

In this project, we are using TestNG 7.10.0, Selenium 4.20.0, Rest Assured 4.4.0, and Maven archetype 4.0.0. TestNG is used as a test runner as it helps in running the test scripts.

Step 1: Set Up Your Environment

Step 2: Create a New Maven Project

Step 3: Select Maven Archetype:

Step 4: Configure Selenium WebDriver Dependency:

Step 5: Create Test Class to test query parameters

The code below utilizes the RestAssured library to test an API with query parameters.
Here, page=2 is a query parameter. This api will fetch the details of users in responses from page no 2.

The image below contains the response  where we can see the query parameter has been passed through the URL.

  1. public class QueryParameterTest(): It declares a Java class name.
  2. @Test: This annotation denotes that the following method is a test case to be executed by the testing framework (Here,TestNG framework has been used).
  3. public void verifyQueryParameters() : This method contains the actual test logic. It’s named verifyQueryParameters().
  4. SoftAssert softAssert = new SoftAssert(): This creates an instance of SoftAssert. Soft assertions allow the test to continue running even if one or more assertions fail.
  5. String baseUrl =”https://gorest.co.in”: This variable holds the base URL of the API.
  6. String endpoint = “/public/v2/users”: This variable holds the specific endpoint of the API being tested.
  7. String page = “2”: This variable holds a query parameter value for the page number.
  8. Response response = RestAssured.given(): It starts the construction of an HTTP request. Then, various methods (baseUri(), queryParam(), headers(), header()) are chained to it to specify details like the base URI, query parameters, and headers. Finally, the request is sent using the .when().get(endpoint) chain, which sends a GET request to the specified endpoint. The response is then captured and stored in the response variable.
  9. .then().log().all().extract().response(): This logs all details of the response and extracts it.
  10. int statusCode = response.getStatusCode(): This retrieves the status code from the response.
  11. softAssert.assertEquals(statusCode, 200, “Response code is not 200”): This checks if the status code equals 200. If it doesn’t, it will record a failure with the message “Response code is not 200”. However, because it’s a soft assertion, the test will continue even if this assertion fails.
  12. softAssert.assertAll(): This line ensures that all soft assertions are evaluated. If any of them fail, it will throw an assertion error at the end of the test.

Step 6: Create Test Class as mentioned in step-5 to test path parameter

The code below utilizes the RestAssured library to test an API with path parameters.
Here, {userId} is a path parameter. It will fetch the details of the user for the mentioned user Id.

In the above code, .pathParam(“userId”,userId) is used to specify a path parameter named “userId” and its corresponding value. The first argument is the name of the path parameter, and the second argument is the value you want to assign to it.

Step 7:Create Test Class as mentioned in Step-5, to set cookies.

Please refer to the image below for the code, to set the cookies of the given url.

Step 8: Configure TestNG

To configure testng.xml, Right click on Project→TestNG→ Convert to Testng (Please refer image given below)

Once the TestNg.xml file is created. Include Test classes in the xml file.

Here in the XML configuration file below, defines a TestNG suite named “Suite” with one test named “Test”, which includes three test classes: “PathParameterTest”, “QueryParameterTest”, and “RestAssuredCookieTest”. When executed, TestNG will run the tests defined in these classes according to the specified settings.

Step 9: Run the Test:

Right click on testng.xml file→Run as→TestNg Suite (Refer below image)

That’s it! We have created a RestAssured program using Selenium WebDriver in Java to test an API. This program sends an HTTP GET request to the specified endpoint, extracts response details, and performs Selenium actions on a webpage. Finally, it asserts the API response status code using TestNG assertions.

Conclusion:

Mastering the intricacies of headers, cookies, and parameters is paramount for ensuring the efficiency and accuracy of API automation testing. With Rest Assured as your ally, harnessing the power of automation becomes more accessible than ever.

At Mobisoft Infotech, we understand the importance of robust testing methodologies in delivering high-quality software solutions. Our expertise in API testing, coupled with cutting-edge tools like Rest Assured, empowers businesses to achieve seamless integration, superior performance, and unparalleled user experiences.

Explore our comprehensive range of services, including Automation Testing Services, to embark on a journey of innovation and excellence in software development. Partner with us today and unlock the full potential of your digital initiatives.

To download the source code for the sample , please click here.

Author's Bio

Purva Kadam

Purva Kadam is a QA at Mobisoft Infotech, Has 4 years of hands-on experience in Manual/Automation testing. My focus is on leveraging automation tools and best practices to streamline testing processes and deliver reliable, high-performing software solutions. My journey in automation testing is a commitment to pushing the boundaries of whats possible.

Exit mobile version