@PatchMapping in Spring Boot: What It Is and How to Use It
@PatchMapping in Spring Boot is an annotation used to handle HTTP PATCH requests, which update parts of a resource. It maps a method to a PATCH URL endpoint, allowing partial updates to data without replacing the entire resource.How It Works
Imagine you have a user profile with many details like name, email, and address. Sometimes you want to update just the email without changing other details. @PatchMapping helps with this by letting you send only the changes, not the whole profile.
When a client sends a PATCH request to your server, Spring Boot looks for a method marked with @PatchMapping that matches the URL. It then runs that method to update the resource partially. This is different from @PutMapping, which expects the full resource data to replace the old one.
This makes your app more efficient and user-friendly, especially when dealing with large data or slow networks.
Example
This example shows a simple Spring Boot controller method that updates a user's email using @PatchMapping. It receives the user ID in the URL and the new email in the request body.
import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @PatchMapping("/users/{id}") public String updateUserEmail(@PathVariable String id, @RequestBody String newEmail) { // Imagine updating the user's email in a database here return "User " + id + " email updated to " + newEmail; } }
When to Use
Use @PatchMapping when you want to update only some fields of a resource instead of replacing the whole thing. For example:
- Updating a user's email or phone number without changing their name or address.
- Changing the status of an order without resending all order details.
- Modifying a few settings in a large configuration object.
This helps reduce data sent over the network and avoids accidental overwrites of unchanged data.
Key Points
@PatchMappingmaps HTTP PATCH requests to controller methods.- It is used for partial updates of resources.
- It differs from
@PutMappingwhich replaces the entire resource. - Helps improve efficiency by sending only changed data.
- Works well for updating user profiles, settings, or statuses.
Key Takeaways
@PatchMapping handles HTTP PATCH requests for partial updates in Spring Boot.@PutMapping, which expects full resource data.