Playwright Java API Testing | How to test PATCH requests?

Published on October 5, 2024

In the previous tutorial blog, we discussed writing test automation scripts for PUT requests.

In this blog, we will be discuss and cover the following points with examples and writing test automation scripts:

  1. What is a PUT request?
  2. How to test PUT APIs using Playwright Java?

What is a PATCH Request?

A PATCH request is used for partially updating a resource. It is the same like PUT request, however the difference is that PUT requires the whole request body to be sent in the request, while using PATCH we can send only the required fields in the request that needs to be updated.

Another difference between PUT and PATCH request is that PUT request is always idempotent, that is, making the same request repeatedly does not change the state of the resource, whereas a PATCH request may not always be idempotent.

The following is an example of updating the order using PATCH request using the restful-ecommerce API. The same PATCH API will be further used in the blog to write the test automation scripts using tests using Playwright Java.

  1. PATCH /partialUpdateOrder/{id} — Partially updates the order using its Order ID

This API needs the id i.e. order_id as the PAth Parameter to check for the existing order to partially update it. The partial details of the order must be supplied in the JSON format in the request body. Since it is a PATCH request, we just need to send the fields that we need to update, rest all the details need not be supplied in the request.

Additionally as a security measure, a valid Authentication token must be supplied with the PATCH request, otherwise the request will fail.

The PATCH request will return the updated order details in the response with a status code 200.

In case the update using the PATCH request fails, based on the criteria the following status codes will be displayed:

  1. Status Code — 404 — If there are no order for the respective order_idsupplied to update the order
  2. Status Code — 400 — If the token authentication fails
  3. Status Code — 400 — If incorrect body/ no body is sent in the request
  4. Status Code — 403 — If the Token is not supplied while sending the request

How to test PATCH APIs using Playwright Java?

Playwright offers the required methods that allow performing API testing seamlessly. Let’s now delve in writing the API automation tests for PATCH API using Playwright Java.

Getting Started

Checkout this previous tutorial blog to know the details about prerequisite, setup and configuration of Playwright framework with Java.

Application Under test

The restful-ecommerce APIs that are free to use and are available over GitHub will be used in this demo.

Restful-Ecommerce — A simple demo node E-Commerce application for practising API Testing

The PATCH API — /partialUpdateOrder/{id} will be used for updating the order partially.

Test Scenario 1 — Update Order using PATCH

  1. Start the restful-ecommerce service
  2. Using POST request create some orders in the system
  3. Update the product_name, product_amt and qtyof order_id “1”
  4. Check that the status code 200 is returned in the response
  5. Check that the order details are correctly updated

Test Implementation

For updating the order partially, we need to send in the request body with partial fields to update and the authorization token. This token ensures that a valid user of the application is updating the order.

Generating the Authentication token

The token can be generated using the POST /authAPI endpoint.

This API endpoint needs the login credentials to be supplied in the request body. The valid login credentials are as follows:

  • username — “admin”
  • password — “secretPass123”

On passing these valid login credentials the API returns the JWT token in the response with status code 200.

We would be generating and using the token using the getCredentials() method from the TokenBuilder class that is available in the testdata package.

public static TokenData getCredentials() {
return TokenData.builder().username("admin")
.password("secretPass123")
.build();
}

This getCredentials() method returns a TokenData object containing the username and password fields.

@Getter
@Builder
public class TokenData {

private String username;
private String password;

}

Once the token is generated it can be used in the PATCH API request for updating the order partially.

Generating the test data for Updating Order

The next step is generating the request body with the required data to update the order partially.

As discussed in the earlier blog for POST request tutorial , we would be adding a new method getPartialUpdatedOrder() in the existing test data generator class OrderDataBuilder.

    public static OrderData getPartialUpdatedOrder() {
return OrderData.builder()
.productName(FAKER.commerce().productName())
.productAmount(FAKER.number().numberBetween(550,560))
.qty(FAKER.number().numberBetween(3, 4))
.build();

}

This method will use only 3 fields, those are product_name , product_amount and qty and accordingly use them to generate a new JSON object that would be passed on as the request body to the PATCH API request.

Update the order using PATCH request

We come to the final stage now where we would be testing the PATCH API request using Playwright Java.

Let’s create a new test method testShouldPartialUpdateTheOrderUsingPatch() in the existing HappyPathTests class.

@Test
public void testShouldPartialUpdateTheOrderUsingPatch() {

final APIResponse authResponse = this.request.post("/auth", RequestOptions.create().setData(getCredentials()));
final JSONObject authResponseObject = new JSONObject(authResponse.text());

final String token = authResponseObject.get("token").toString();
final OrderData partialUpdatedOrder = getPartialUpdatedOrder();

final int orderId = 1;
final APIResponse response = this.request.patch("/partialUpdateOrder/" + orderId, RequestOptions.create()
.setHeader("Authorization", token)
.setData(partialUpdatedOrder));

final JSONObject updateOrderResponseObject = new JSONObject(response.text());
final JSONObject orderObject = updateOrderResponseObject.getJSONObject("order");
assertEquals(response.status(), 200);
assertEquals(updateOrderResponseObject.get("message"), "Order updated successfully!");
assertEquals(orderId, orderObject.get("id"));
assertEquals(partialUpdatedOrder.getProductAmount(), orderObject.get("product_amount"));
assertEquals(partialUpdatedOrder.getQty(), orderObject.get("qty"));
}

This method will first hit the Authorization API to generate the token. The response from the Authorization API will be stored in the authResponseObject variable that will further be used to extract the value from the “token” field available in response.

The request body required to be sent in the PATCH API will be generated and will be stored in the partialUpdateOrder object. This is done so we could use this object further while validating the response.

Next, the token will be set in the setHeader() method and the request body object will be sent using the setData() method. The PATCH API request will be handled using the patch() method of the API that will allow updating the order partially.

Response body

{
"message": "Order updated successfully!",
"order": {
"id": 1,
"user_id": "1",
"product_id": "1",
"product_name": "Samsung Galaxy S23",
"product_amount": 5999,
"qty": 1,
"tax_amt": 5.99,
"total_amt": 505.99
}
}

The response received from this PATCH API will be stored in the response variable and will be used further to validate the response.

The last step is to perform assertions, the response from the PATCH API returns a JSON object that will be stored in the object named updateOrderResponseObject.

The message field is available in the main response body, hence it will be assertion using the updateOrderResponseObject calling the get() method that asks to return the value of the message field.

The JSON object order will be stored in the object named orderObject. The assertions for the fields will be done using the object orderObject .

The partialUpdateOrder object that actually stores the request body that we sent to partially update the order will be used for the expected values and the orderObject will be used for actual values finally performing the assertions.

Test Execution

We will be creating a new testng.xml file — testng-restfulecommerce-partialupdateorder.xml to execute the test sequentially, i.e. first calling the POST API test to generate orders and then calling the PATCH API test to partially update the order.


http://testng.org/testng-1.0.dtd">











The following test execution screenshot from IntelliJ IDE shows that the tests were executed successfully and partial update of the order was successful.

Summary

PATCH API requests allows updating the resource partially. It allows flexibility to update a particular resource as only the required fields can be easily updated using it. In this blog, we tested the PATCH API requests using Playwright Java.

Testing all the HTTP methods is equally important while performing API testing. We should perform isolated tests for each endpoint as well as perform end to end testing for all the APIs to make sure that all APIs of the application are well integrated with each other and run seamlessly.

Happy Testing!