Ravi Sharma
API Automation Using Rest -assured With Live Example
What is rest assured?
- Rest -assured is a java library that provides multiple classes, interfaces, and methods by which we can test a RESTful API.
- We can handle all HTTP requests such as GET, POST, PUT, DELETE, OPTIONS, etc, and validate the response also.
- For assertion, it allows us to use TestNG, Junit, and AssertJ testing libraries, etc.
- It is the best choice for API Automation because it easily integrates with Cucumber, Serenity, Logger, and other additional libraries which makes the process easy.
Requirements:
- Java (Version >= 8)
- IntelliJ IDEA (I’m using this IDE but we can use other IDE also such as Eclipse, NetBeans, etc)
- POSTMAN Tool
- Dependencies: Rest Assured, Cucumber, SLF4J Logger, JUnit, GSON, Or Jackson Databind Library
Live Example:
Here, I’m going to automate Shopify order creation API with the help of rest assured and other additional libraries which I have mentioned above in the requirements.
Step 1: Test the desired API using POSTMAN before starting automation.
- Go to your Shopify store and create a private app on your store Click Here
- Get the API key after creating a private app
Select the HTTP method “POST” and enter this request URL
- “https://litmusbox-6.myshopify.com/admin/api/2021-07/orders.json”
- Enter the “X-Shopify-Access-Token” as key and API key as the value in the header in POSTMAN
- Go to the Shopify developer site and understand the order creation process Click Here
- To get “variantId” value, please go to edit the product page of your product and add “.json” in URL, and hit the enter button
- Please find the “Id” key under the “variants” and this is your “variantId”
- Open your postman enter the JSON structure in the body in POSTMAN
JSON:
{
“order”: {
“line_items”: [
{
“variant_id”: 41198603108501,
“quantity”: 10
}
]
}
}
- Click on the “Send” button, verify the response and check the created order on the store
Step 2 Create Maven Project in your IDE
- Please follow the image step by step
- Click on “File” on the left corner of the IDE and click on “New”>Project
- Select “Maven” on “New Project” window and click on “Next” button
- Enter the project name in the “Name” field and you can update your project location as per your need and click on “Finish” button
- You can see that project has been created
Step 3: Install all needed dependencies using pom.xml in your project.
- Please add rest-assured, cucumber, junit, logger, and gson dependencies using pom.xml
Rest-Assured:
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.9.0</version>
</dependency
Cucumber:
<dependency>
<groupId>net.serenity-bdd</groupId>
<artifactId>serenity-cucumber</artifactId>
<version>1.9.51</version>
</dependency>
Logger:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.0-alpha4</version>
</dependency>
GSON:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
JUnit:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
- Pom.xml file will be look like this after adding all the above dependencies
Step 4: Setup your project directory for managing the files
- Please follow a proper project structure and for reference please follow the image
Step 5: Create the feature file and write the test scenario and steps
- Please create a feature file with “.feature” extension in the feature package
- Please write scenarios in the form of given, when, and then Click Here
Example:
Feature: Allow user to create order on Shopify store
As a user,
I want to create an order on my Shopify store
Scenario: To check that user is able to create order on his store with credentials
When User enters valid order details
| variant_id | quantity |
| 41198603108501 | 10 |
And User makes request to create order with order details
Then Order should be created on his shopify store
Step 6: Create a step file that covers all the steps and scenarios
- Please click on any step, press “Alt+Enter” and click on “Create all step definitions”
- Please enter a valid step file name, select valid package, and click on “OK” button
Step 7: Create model files for managing request and response
- Please go to http://pojo.sodhanalibrary.com/ , enter the order JSON in textarea , click on “Submit” button, and POJO will be created
- Please create the request models with the help of generated POJO files
OrderCreationRequestModel.java
Order.java
Line_items.java
Note: In auto-generated POJO, the “Integer” value can be considered as “String” so please update datatype accordingly in the project.
- For the response to the model, please copy the order creation response from POSTMAN and using the above website create response models
OrderCreationResponseModel.java
Order.java
Line_items.java
Note: Many response POJO files will be generated but I have taken only important files.
Step 8: Write the code in step file and run the scenarios from feature file
- Please write the code in steps file as given below and run the feature file
package demo.project.step;
import com.google.gson.Gson;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import demo.project.model.orderCreationModel.request.Line_items;
import demo.project.model.orderCreationModel.request.Order;
import demo.project.model.orderCreationModel.request.OrderCreationRequestModel;
import demo.project.model.orderCreationModel.response.OrderCreationResponseModel;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class orderCreationOnShopifyStore {
private final Logger log = LoggerFactory.getLogger(“Logger”);
private final Gson gson = new Gson();
private OrderCreationRequestModel orderCreationRequestModel = new OrderCreationRequestModel();
private OrderCreationResponseModel orderCreationResponseModel = new OrderCreationResponseModel();
private Order order = new Order();
private RequestSpecification httpRequest = RestAssured.given();
private Response jsonResponse;
@When(“^User enters valid order details$”)
public void userEntersValidOrderDetails(List<Line_items> line_itemsList) {
if (line_itemsList != null) {
order.setLine_items(line_itemsList);
orderCreationRequestModel.setOrder(order);
}
}
@And(“^User makes request to create order with order details$”)
public void userMakesRequestToCreateOrderWithOrderDetails() {
httpRequest
.header(“Content-Type”, “application/json”)
.header(“X-Shopify-Access-Token”, “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”);
jsonResponse = httpRequest
.body(gson.toJson(orderCreationRequestModel))
.post(“https://litmusbox-6.myshopify.com/admin/api/2021-07/orders.json”);
}
@Then(“^Order should be created on his shopify store$”)
public void orderShouldBeCreatedOnHisShopifyStore() {
try {
Assert.assertTrue(jsonResponse.getStatusCode() >= 200);
orderCreationResponseModel = gson.fromJson(jsonResponse.prettyPrint(), OrderCreationResponseModel.class);
Assert.assertEquals(orderCreationRequestModel.getOrder().getLine_items().get(0).getVariant_id(), orderCreationResponseModel.getOrder().getLine_items().get(0).getVariant_id());
Assert.assertEquals((int) orderCreationRequestModel.getOrder().getLine_items().get(0).getQuantity(), orderCreationResponseModel.getOrder().getLine_items().get(0).getQuantity());
log.info(“Assertion have been passed successfully.”);
} catch (Exception exception) {
exception.printStackTrace();
log.error(“Exception has been occurred !!!”);
} finally {
orderCreationRequestModel = null;
orderCreationResponseModel = null;
order = null;
httpRequest = null;
jsonResponse = null;
log.info(“Memory has been clean successfully.”);
}
}
}
- Added one more scenario:
- After running the feature file response will be appear in “run” window
- We can see that two order has been created on the Shopify store.
Conclusion:
- In this way, we can automate the order creation API.
- Every organization has its own testing standards so you can manage the project accordingly but most of the time flow will be the same.
- I have used several libraries such as Rest Assured, Cucumber, SLF4J Logger, JUnit, GSON, so if you want to understand these libraries in-depth then you can click on their title and you will redirect to their tutorial page.
Did you find this blog post helpful? If yes then please like it and share it.