</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

How to automate the PATCH method in Rest Assured?

Answer

Automating PATCH Method in Rest Assured

The HTTP PATCH method is used when a resource needs to be partially updated. This method is especially useful if a resource is large and the changes being made are small.

PATCH with JSON Body from File

Java
@Test(description = "Automate PATCH method and validate response")
public void methodValidationPATCH() throws IOException, ParseException {

    FileInputStream file = new FileInputStream(
        new File(System.getProperty("user.dir") + "\\TestData\\put.json")
    );

    Response resp = given()
                        .header("Content-Type", "application/json")
                        .body(IOUtils.toString(file, "UTF-8"))
                        .when()
                        .patch("https://reqres.in/api/users/2");

    assertEquals(resp.getStatusCode(), 200);
    assertEquals(resp.path("job"), "tester");
}

PATCH with Inline JSON (Partial Update)

Java
@Test
public void partialUpdateWithPATCH() {

    // Only updating the job field, not the name
    String partialBody = "{ \"job\": \"Lead SDET\" }";

    given()
        .contentType(ContentType.JSON)
        .body(partialBody)
        .when()
        .patch("https://reqres.in/api/users/2")
        .then()
        .statusCode(200)
        .body("job", equalTo("Lead SDET"));
}

BDD Style PATCH

Java
given()
    .contentType(ContentType.JSON)
    .body("{ \"status\": \"active\" }")
    .when()
    .patch("/api/users/5")
    .then()
    .statusCode(200)
    .body("status", equalTo("active"))
    .body("updatedAt", notNullValue());

PATCH vs PUT

FeaturePATCHPUT
UpdatesPartial fieldsEntire resource
IdempotentNoYes
Payload sizeSmall (only changed fields)Full resource
Missing fieldsUnchangedSet to null/default

When to Use PATCH

  • Updating a user''s profile picture only
  • Changing an order status only
  • Toggling a feature flag

Follow AutomateQA

Related Topics