Understanding PUT vs. PATCH in REST APIs with Spring Boot
Omar Ismail
Senior Software Engineer @ Digitinary | Java 8 Certified? | Spring & Spring Boot?????? | AWS? | Microservices ?? | RESTFul Apis & Integrations ?? FinTech ?? | Open Banking ?? | Digital Payments and Transformation??
Introduction
In RESTful APIs, both PUT and PATCH are used to update resources, but they serve different purposes. Understanding their differences is crucial to implementing efficient and correct API operations.
This article explores PUT vs. PATCH with unique Spring Boot examples to illustrate their impact on resource updates.
1. PUT vs. PATCH: Key Differences
1.1 PUT (Full Update)
Definition: Replaces an entire resource with a new representation. If a field is missing in the request, it will be removed (set to null).
1.2 PATCH (Partial Update)
Definition: Updates only the specified fields without affecting others.
2. Example Scenario: Employee Management System
Imagine we manage an Employee Profile System where employees have:
3. Implementing PUT and PATCH in Spring Boot
3.1 Employee Entity
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String department;
// Getters and Setters
}
3.2 Employee Repository
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
3.3 Employee Controller
@RestController
@RequestMapping("/employees")
public class EmployeeController {
private final EmployeeRepository employeeRepository;
@Autowired
public EmployeeController(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
// PUT: Full Update
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee updatedEmployee) {
return employeeRepository.findById(id).map(existingEmployee -> {
existingEmployee.setName(updatedEmployee.getName());
existingEmployee.setEmail(updatedEmployee.getEmail());
existingEmployee.setDepartment(updatedEmployee.getDepartment());
employeeRepository.save(existingEmployee);
return ResponseEntity.ok(existingEmployee);
}).orElse(ResponseEntity.notFound().build());
}
// PATCH: Partial Update
@PatchMapping("/{id}")
public ResponseEntity<Employee> partiallyUpdateEmployee(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
return employeeRepository.findById(id).map(existingEmployee -> {
updates.forEach((key, value) -> {
if (key.equals("name")) existingEmployee.setName((String) value);
if (key.equals("email")) existingEmployee.setEmail((String) value);
if (key.equals("department")) existingEmployee.setDepartment((String) value);
});
employeeRepository.save(existingEmployee);
return ResponseEntity.ok(existingEmployee);
}).orElse(ResponseEntity.notFound().build());
}
}
4. Testing PUT and PATCH Requests
4.1 PUT Example (Full Update)
Request:
PUT /employees/1
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]"
}
Response (After PUT):
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"department": null
}
Notice: Since we did not send department, it was set to null.
4.2 PATCH Example (Partial Update)
Request:
PATCH /employees/1
Content-Type: application/json
{
"email": "[email protected]"
}
Response (After PATCH):
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"department": "IT"
}
Notice: Only email was updated; department remained unchanged.
5. Best Practices and Considerations
5.1 When to Use PUT vs. PATCH?
? Use PUT when updating the entire resource (e.g., form submission, profile update). ? Use PATCH when updating specific fields (e.g., changing only an email or department).
5.2 Avoiding Common Mistakes
? PUT request missing fields leads to unintended data loss (e.g., null values). Always ensure all necessary fields are present. ? PATCH misuse can lead to inconsistencies if validation is not handled properly.
5.3 Enhancing PATCH with JSON Merge Patch
A more advanced way to handle PATCH updates is by using JSON Merge Patch, which allows specifying only modified fields:
@PatchMapping("/{id}")
public ResponseEntity<Employee> mergePatchEmployee(@PathVariable Long id, @RequestBody JsonMergePatch patch) {
return employeeRepository.findById(id).map(existingEmployee -> {
Employee patchedEmployee = applyPatchToEmployee(patch, existingEmployee);
employeeRepository.save(patchedEmployee);
return ResponseEntity.ok(patchedEmployee);
}).orElse(ResponseEntity.notFound().build());
}
6. Conclusion
Understanding the differences between PUT and PATCH ensures we use the right HTTP method for updating resources in RESTful APIs.
By implementing these strategies correctly, we ensure our Spring Boot APIs remain efficient, scalable, and maintainable. ??
?? What do you use more in your projects? PUT or PATCH? Let’s discuss in the comments!
#SpringBoot #Java #RESTAPI #HTTPMethods #BackendDevelopment #Microservices