Hello readers! Welcome to my blog! This article focuses on one of the API testing tools, which is Rest Assured. We will also study specifications in Rest Assured. We will mainly concentrate on RequestSpecification/ResponseSpecification in REST Assured. Let’s see all these things in more detail.
What is API?
So, what exactly is a REST API? A REST API, or RESTful API, serves as a standardised interface that enables the access and manipulation of data, content, algorithms, media, and other digital resources via web URLs. REST APIs have become the predominant choice for web services due to their simplicity and uniformity.
Why is API?
When a client interacts with a REST API, it sends a request to the server using standard HTTP methods such as GET, POST, PUT, or DELETE. In response, the server returns a resource, which can take various forms, including HTML, XML, images, or JSON. Among these formats, JSON has emerged as the most widely used due to its lightweight nature and ease of integration with modern web applications.
Prerequisites
Java
IDE(Eclipse)
Build Tool(Maven)
Framework (TestNG)
Specifications in REST Assured
We can use specification objects to avoid duplicate request parameters and responses in case we are working on multiple tests. We can use the same object every time we make a different request. We have to do it in case of numerous RESTful requests and response validations.
This approach not only reduces redundancy but also enhances maintainability. If we need to update a parameter or response structure, we can do so in one place, and all tests that reference that specification object will automatically reflect the changes. This is particularly beneficial in larger projects where multiple tests may interact with similar endpoints.
Following are the two types of specification builder Java classes:
RequestSpecification (RequestSpecBuilder)
ResponseSpecification (ResponseSpecBuilder)
RequestSpecification in REST Assured
Rest Assured provides the interface of the RequestSpecification. You can use it to retrieve repetitive actions. The action can be anything like setting up the base URL, HTTP verbs, headers, etc. These actions may be identical for multiple calls of Rest.
You can use the retrieved common code in different requests. It reduces the number of lines in the code. This eventually helps in increasing maintainability.
Let's try to understand this with an example.
Example:
Now, let’s move on to an example. In this example, let's assume that we have two test cases. These test cases will help in testing an API endpoint. Here I am using PetStore API
TestCase1
Here, This method POST request to the “/v2/pet” endpoint to create a new pet with the given details.
Testcase2
Here,This method sends a PUT request to the “/v2/pet” endpoint to update an existing pet identified by the id obtained from the PostPetApi method.
If we observe the above two test case examples, we can see that there are common elements in the request execution and assertions.Instead of having to duplicate response expectations and/or request parameters for different tests we can re-use an entire specification.
RequestSpecification (RequestSpecBuilder)
ResponseSpecification (ResponseSpecBuilder)
RequestSpecBuilder/ResponseSpecBuilder and RequestSpecification/ResponseSpecification ,These are components of the RestAssuredAPI components.RequestSpecBuilder/ResponseSpecBuilder is a builder class to construct and configure RequestSpecification/ResponseSpecification interface to represent all HTTP Request/Response configurations(Headers,BaseURL..etc).
requestSpec/resSpec are the variables that holds an instance of RequestSpecification/ResponseSpecification, which can be re used in multiple requests.
In the below pictures, you can see that we have taken the common request/response setup. We have put this setup in a separate base test case. We are doing this using the RequestSpecification/ResponseSpecification interface. Now, we can use this setup in actual test cases. This helps us overcome redundancy. It also enhances the maintainability and reusability of the code.
Code Implementation of RestAssured Specifications to handle HTTP requests and responses by defining requestSpec and resSpec in @BeforeClass method .In that way we set up the common configuration for once and use these settings in multiple test methods like 'PostPetApi' and 'PutApi'.Like this we can implement same for all our CRUD operations.
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
public class Specifications {
long Pid;
RequestSpecification requestSpec;
ResponseSpecification resSpec;
@BeforeClass
public void setBaseUrl() {
ResponseSpecBuilder responsebuilder = new ResponseSpecBuilder();
responsebuilder.expectStatusCode(200);
responsebuilder.expectContentType("application/json");
resSpec = responsebuilder.build();
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setAccept("application/json");
builder.setBaseUri("https://petstore.swagger.io");
builder.setContentType("application/json");
requestSpec = builder.build();
}
@Test
public void PostPetApi() {
String BodyJson = "{" + " \"id\": 0," + " \"category\": {" + " \"id\": 0," + " \"name\": \"cow\"" + " },"
+ " \"name\": \"puppy\"," + " \"photoUrls\": [" + " \"string\"" + " ]," + " \"tags\": [" + " {"
+ " \"id\": 0," + " \"name\": \"string\"" + " }" + " ]," + " \"status\": \"pending\"" + "}";
Response response = given().spec(requestSpec).body(BodyJson).expect().spec(resSpec).when().post("/v2/pet");
System.out.println(response.asPrettyString());
Pid = response.path("id");
System.out.println("Pid: " + Pid);
}
@Test(dependsOnMethods = "PostPetApi")
public void PutApi() {
String BodyJson = "{" + " \"id\": 0," + " \"category\": {" + " \"id\": 0," + " \"name\": \"peacock\""
+ " }," + " \"name\": \"puppy\"," + " \"photoUrls\": [" + " \"string\"" + " ]," + " \"tags\": ["
+ " {" + " \"id\": 0," + " \"name\": \"moonoo\"" + " }" + " ]," + " \"status\": \"pending\""
+ "}";
Response response = given().spec(requestSpec).body(BodyJson).expect().spec(resSpec).when().put("/v2/pet");
System.out.println(response.asPrettyString());
System.out.println("Pid: " + Pid);
response.then().body("category.id", equalTo(0)).body("name", equalTo("puppy"));
}
}
Reference Links:
1.Will give you brief details about RestAssured specifications.
2. A Licensed free API to practice all RESTful APIs interactions.