Introduction
In this article, we will learn about the Test Automation tool Rest Assured library, which is based on Java.
What is Rest Assured?
Rest Assured is a Java-based open-source library that provides a domain-specific language (DSL) for writing automated tests for RESTful APIs. It simplifies the process of sending HTTP requests, verifying responses, and extracting data from API responses in a structured manner.
Advantages of using Rest assured
- Request Specification: Rest Assured allows you to define common properties for requests, such as headers, query parameters, authentication, etc., which can be reused across multiple test cases.
- Response Validation: Rest Assured provides various methods for validating API responses, such as verifying status codes, response headers, response bodies (including JSON and XML parsing), and more.
- Support for Authentication: Rest Assured supports different types of authentication methods, including basic authentication, digest authentication, OAuth, and more.
- Support for Data-Driven Testing: Rest Assured integrates well with test frameworks like TestNG and JUnit, allowing you to parameterize and execute tests with different data sets.
- Integration with BDD Frameworks: Rest Assured can be easily integrated with Behavior-Driven Development (BDD) frameworks like Cucumber, enabling you to write API tests using Gherkin syntax.
Pre-requisite
- Java JDK needs to be installed
- Eclipse IDE needs to be installed
- Should know the basics of API Testing
Step to create a Maven project
- Open the Eclipse IDE.
- Click File new-->Project---->Other--->Expand the maven folder--->select Maven Project
- Choose the desired location of the project, or you can set the default location of the project.
- Check the check box to create a simple project(skip archetype selection)
- If you do not check this check box, the Maven will ask you to select the archetype solution which you want to build.
- Click the next button.
- Provide the group Id and Artifact Id and click finish.
- A Maven project will be created. It will take a few minutes.
A pom.xml file will be generated, which contains all the metadata regarding the project.
We can add the dependencies and plugins needed for your maven project inside the pom.xml file.
Dependencies needed to be added in the pom.xml are.
- Hamcrest
- Rest Assured
- TestNG
- log4j(Additional dependency which i added)
Dependencies
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.20.0</version>
<scope>test</scope>
</dependency>
</dependencies>
You can also refer to my article if you have any doubts about setting up a Maven project.
First api automation test
As you know, we have different http methods for requests, in this article, we will learn how to hit a get http request using Rest Assured.
In Rest Assured, we can write API Automation tests in two ways
1. Using Request specification
First, we need to store the base URI,
RestAssured is a class inside that class. There is a static string called base URI which stores the base URI value.
Note. Create a package inside the src/test/java folder and then create a class inside the package and then start writing tests using TestNG annotations.
Next is providing the requested specification.
- The request specification tells us the request type which is sent to the server.
- Rest Assured library provides an interface called RequestSpecification for this purpose.
The variable httpRequest stores the request so that we can modify it if required, like adding authentication details, adding headers, etc
Using the httpRequest reference, we call the request type, whether it's get, post, put, delete, etc. This will return, hit the API, and gives the response, which we store in the response object.
@Test
public void getrequest() {
// Specify the base URL to the RESTful web service
RestAssured.baseURI = "https://reqres.in/api/users/2";
// Get the RequestSpecification of the request to be sent to the server.
RequestSpecification httpRequest = RestAssured.given();
// specify the method type (GET) and the parameters if any.
//In this case the request does not take any parameters
Response response = httpRequest.request(Method.GET, "");
// Print the status and message body of the response received from the server
System.out.println("Status received => " + response.getStatusLine());
System.out.println("Response=>" + response.prettyPrint());
}
BDD Style of writing
First, we need to store the base URI,
RestAssured is a class inside that class. There is a static string called base URI which stores the base URI value.
Next, we need to use the pattern,
- Given: Here is the given section, all the preconditions for the http request should be provided, like request headers, path param, query param, authentication, etc.
- When: Here in the when section, we need to specify which http method we are going to call, whether it is get post put or delete. In this part, the actual api call will happen with the respective http method which you are providing.
- Then: Here in the then section, we get the response of the http request and then apply assertions.
Important note
- We can apply assertions using the Hamcrest matches, or we can use the TestNG assertions to apply assertions as well.
- These are given when then keywords can be used only when you import the static hamcrest packages in your test file.
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
Code explained with comments
1. Get API Calls made and asserting using the hamcrest matchers library.
package com.apidemoautomation;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Getapi {
@Test
public void getapi() {
//Storing the base uri
RestAssured.baseURI="https://reqres.in/api/users/2";
//In one line you can see that we have made a get call and using the hamcrest matchers and asserting that the status code is 200. The log().all() will log all the response logs in the console.
given().when().get().then().assertThat().statusCode(200).log().all();
}
}
2. Get API Calls made and asserting using the TestNG library.
package com.apidemoautomation;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Getapi {
@Test
public void getapi() {
//storing the base uri
RestAssured.baseURI="https://reqres.in/api/users/2";
//using the given then pattern and then i am extract the response using response method and storing in variable
Response response = given().when().get().then()
.extract().response();
//using the assert class in the testng i am putting assertion
Assert.assertEquals(200, response.statusCode());
}
}
Post Request
In order to perform the post request, the code almost remains the same, except we need to call the post method instead of the get method, and since the post method takes the json payload, we need to specify it in the given section.
We need to specify the content type(JSON) as well in the given section.
code explained with comments
@Test
public void createsource() {
//storing the base uri
RestAssured.baseURI = "https://reqres.in/";
//storing the json payload in the string
String requestBody = "{\n" +
" \"email\": \"[email protected]\",\n" +
" \"password\": \"cityslicka\"\n" +
"}";
// See below we have called the post method in when section which accepts the endpoint as parameter and in the given section we need to provide the json payload in the body method
Response res = given().contentType(ContentType.JSON).
body(requestBody).
when().
post("api/login").
then().log().all()
.extract().
response();
//applying assertion on response code
Assert.assertEquals(200, res.statusCode());
}
Put Request
In order to perform the put request, the code almost remains the same, except we need to call the put method instead of the get method, and since the put method takes the json payload, we need to specify it in the given section.
We need to specify the content type(JSON) as well in the given section.
code explained with comments
@Test
public void putrequest() {
//storing the base uri
RestAssured.baseURI = "https://reqres.in/";
String payload = "{\n" +
" \"name\": \"morpheus\",\n" +
" \"job\": \"zion resident\"\n" +
"}";
/* See below we have called the put method in when section which accepts the endpoint as parameter and in the given section
* we need to provide the json payload in the body method
*/
Response response = given()
.contentType(ContentType.JSON)
.body(payload)
.when()
.put("api/users/2")
.then()
.extract().response();
//apply assertion on the response status code
Assert.assertEquals(200, response.statusCode());
}
Delete Request
In order to perform the delete request, the code almost remains the same, except we need to call the delete method instead of the get method.
Code explained with comments
@Test
public void deleterequest() {
//storing base uri
RestAssured.baseURI = "https://reqres.in/api/users/2";
/* See below we have called the delte method in when section
*
*/
Response response = given()
.when()
.delete()
.then()
.extract().response();
//apply assertion on the response status code
Assert.assertEquals(204, response.statusCode());
}
Summary
I hope this article will be helpful in understanding how to set up a Rest assured project and write API automation tests using the rest assured library.
Thanks, Happy learning.