Video in progress
What is the difference between PUT and PATCH in a REST API, and how do you write them in Spring?
PUT replaces the resource completely: a field you didn't send becomes empty. PATCH changes only the fields that arrived. PUT is idempotent, while PATCH has no such guarantee.
📖 Answer
Say a user has name, email and phone.
PUT /users/7with the body{"name":"Ali","email":"a@x.uz"}: logicallyphoneshould now benull, because you provided a complete new representation of the resource.PATCH /users/7with the body{"phone":"+998..."}: only the phone changes, the rest stays.
@PutMapping("/{id}")
UserDto replace(@PathVariable Long id, @Valid @RequestBody UserForm form) {
return service.replace(id, form); // all fields are required
}
@PatchMapping("/{id}")
UserDto patch(@PathVariable Long id, @RequestBody UserPatch patch) {
return service.patch(id, patch); // null fields mean "don't change"
}
The trap with PATCH: if null arrives in the DTO, you can't tell whether it means "the field wasn't sent" or "clear it". If you need to, use Map<String, Object> or JsonNullable. Interviewers ask this question on purpose.
Idempotency: if you send the same PUT 5 times, the result is the same. With PATCH, if the operation is something like {"balance": "+100"}, the result changes every time.
Sign up to mark studied questions and save your progress.