Junior — Middle
Which HTTP method do you use for partial or full data updates in REST API?
sobes.tech AI
Answer from AI
The following HTTP methods are typically used for updating data in REST API:
-
PUT — used for full resource updates. The client sends a complete representation of the resource, and the server replaces the existing resource with the new state.
-
PATCH — used for partial resource updates. The client sends only the fields that need to be changed, and the rest remain unchanged.
Example:
- To replace the entire user object, use PUT.
- To change only one field, such as email, use PATCH.
In Java, these methods can be handled using annotations in controllers, for example, in Spring:
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
// full update logic
}
@PatchMapping("/users/{id}")
public ResponseEntity<User> partialUpdateUser(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
// partial update logic
}
Thus, for full updates — PUT, for partial updates — PATCH.