How to Test PATCH Requests Using Rest Assured

In API testing, the PATCH request method is crucial for updating partial resources, allowing you to modify only specific fields of an object rather than sending a complete update like PUT. Testing PATCH requests is essential in validating the flexibility and precision of APIs, especially when dealing with scenarios where only a portion of a resource is expected to change.

In this post, I’ll guide you through the process of testing a PATCH request using Rest Assured, a popular Java-based library for automating REST API testing. This tutorial will cover setting up the basics of Rest Assured, configuring your request, sending a PATCH request, and validating the response.

Prerequisites

  1. Java Development Kit (JDK): Ensure you have JDK 8 or higher installed.
  2. Maven: We’ll use Maven for dependency management.
  3. Rest Assured Library: Add the latest version of Rest Assured to your project dependencies.

Step 1: Set Up Rest Assured

Add the following Rest Assured dependency to your pom.xml file if you’re using Maven:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.3.0</version>

    <scope>test</scope>

</dependency>

You may also want to add JSON parsing dependencies if you plan on working with JSON data. Jackson or GSON libraries can handle JSON object serialization and deserialization, simplifying JSON payload manipulation.

Step 2: Define the Base URI

Set up the base URI for your tests using Rest Assured. The base URI is typically the root endpoint of your API, such as https://jsonplaceholder.typicode.com for a mock API. For example:

import io.restassured.RestAssured;


public class PatchRequestTest {

    static {

        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

    }

}

Step 3: Structure the PATCH Request

The PATCH request requires a payload with only the fields that you want to update. Let’s say we have a POST resource where we want to update just the title field.

Here's an example JSON body for a PATCH request to update the title of a post:

{

    "title": "Updated Title"

}

Step 4: Send the PATCH Request

The following code demonstrates how to construct and send the PATCH request. We’ll use the patch() method of Rest Assured, passing the endpoint of the specific resource we want to update:

import io.restassured.RestAssured;

import io.restassured.http.ContentType;

import io.restassured.response.Response;


import static io.restassured.RestAssured.given;

import static org.hamcrest.Matchers.equalTo;


public class PatchRequestTest {


    public static void main(String[] args) {


        // Define the request body

        String requestBody = "{ \"title\": \"Updated Title\" }";


        // Send the PATCH request

        Response response = given()

                                .contentType(ContentType.JSON)

                                .body(requestBody)

                            .when()

                                .patch("/posts/1"); // Assuming we are updating the post with ID 1


        // Print the response to the console

        System.out.println("Response Status Code: " + response.getStatusCode());

        System.out.println("Response Body: " + response.getBody().asString());


        // Assertions

        response.then().statusCode(200) // Verify that the status code is 200 (or the expected success code)

                        .body("title", equalTo("Updated Title")); // Check that the title was updated

    }

}

Here’s a breakdown of the code:

  • Content Type: The contentType(ContentType.JSON) method sets the Content-Type header to application/json, which is necessary for JSON data.
  • Body: The body(requestBody) method attaches the JSON payload to the request.
  • Endpoint: We’re using .patch("/posts/1") to target the resource at /posts/1.
  • Assertions: The response is checked for status code 200 and that the title field matches the updated value.

Step 5: Validate the Response

Response validation is essential to confirm that the PATCH request worked as expected. In our example, we validated:

  1. The status code is 200 (indicating success).
  2. The response body confirms the updated title.

You can add more validations as needed, such as checking other fields to confirm that only the intended fields were updated.

Additional Tips

1. Check for Different Status Codes: Aside from 200, other common codes are 204 for no content (indicating success but no response body) and 400 or 404 for errors. Handling these will make your tests robust.

2. Environment Configuration: Use properties files or environment variables to manage different environments (e.g., dev, staging, production) without hardcoding URLs or credentials.

3. Logging: Use .log().all() to log requests and responses for better debugging, especially during test failures. For example:

given()
    .contentType(ContentType.JSON)
    .body(requestBody)
    .log().all() // Logs request details
.when()
    .patch("/posts/1")
.then()
    .log().all(); // Logs response details

4. Parameterization: If you have multiple test cases or endpoints, consider parameterizing request bodies and endpoints to improve maintainability and reusability.

Followers