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
| Feature | PATCH | PUT |
|---|---|---|
| Updates | Partial fields | Entire resource |
| Idempotent | No | Yes |
| Payload size | Small (only changed fields) | Full resource |
| Missing fields | Unchanged | Set to null/default |
When to Use PATCH
- ✓Updating a user''s profile picture only
- ✓Changing an order status only
- ✓Toggling a feature flag
