Discover how a few simple annotations can save you hours of messy code and bugs!
Why @PutMapping and @DeleteMapping in Spring Boot? - Purpose & Use Cases
Imagine building a web app where you have to update or delete user data by manually parsing HTTP requests and writing complex code to handle each action.
Manually handling HTTP PUT and DELETE requests is error-prone, repetitive, and makes your code messy and hard to maintain.
@PutMapping and @DeleteMapping annotations in Spring Boot let you easily link HTTP PUT and DELETE requests to specific methods, making your code clean and clear.
if(request.getMethod().equals("PUT")) { updateUser(); } else if(request.getMethod().equals("DELETE")) { deleteUser(); }
@PutMapping("/user") public void updateUser() { ... } @DeleteMapping("/user") public void deleteUser() { ... }
This makes your web app respond correctly to update and delete actions with minimal code and clear structure.
When a user edits their profile or removes their account, @PutMapping and @DeleteMapping handle these requests smoothly behind the scenes.
Manually handling HTTP methods is complex and error-prone.
@PutMapping and @DeleteMapping simplify routing for update and delete actions.
They make your code cleaner, easier to read, and maintain.
Practice
@PutMapping annotation in Spring Boot?Solution
Step 1: Understand HTTP methods
HTTP PUT is used to update existing data on the server.Step 2: Match annotation to HTTP method
@PutMappingmaps HTTP PUT requests to controller methods.Final Answer:
To handle HTTP PUT requests for updating existing resources -> Option BQuick Check:
@PutMapping = update data [OK]
- Confusing @PutMapping with @PostMapping
- Thinking @PutMapping creates new data
- Mixing HTTP methods like GET or DELETE
@DeleteMapping?Solution
Step 1: Identify correct URL pattern and annotation
To delete by ID, URL should include path variable like /items/{id} and method parameter annotated with @PathVariable.Step 2: Check method signature matches path variable
@DeleteMapping("/items/{id}") public void deleteItem(@PathVariable int id) {} correctly uses @DeleteMapping with path and @PathVariable int id parameter.Final Answer:
@DeleteMapping("/items/{id}") public void deleteItem(@PathVariable int id) {} -> Option CQuick Check:
Delete by ID needs @PathVariable and matching URL [OK]
- Omitting @PathVariable annotation
- Using @RequestParam instead of @PathVariable for path params
- Not matching method parameter to URL placeholder
/users/5 with a valid JSON body?@PutMapping("/users/{id}")
public User updateUser(@PathVariable int id, @RequestBody User user) {
user.setId(id);
return userService.save(user);
}Solution
Step 1: Analyze method parameters and annotations
The method uses @PutMapping with path variable id and @RequestBody user object. It sets user ID from path.Step 2: Understand method behavior on PUT request
It updates the user ID to match URL, then calls save to update and returns updated user.Final Answer:
The user with ID 5 will be updated with the JSON data and returned -> Option AQuick Check:
PUT updates resource with URL ID and JSON body [OK]
- Assuming PUT creates new resource instead of updating
- Ignoring @PathVariable ID and using JSON ID only
- Missing @RequestBody causing request failure
@DeleteMapping("/users")
public void deleteUser(@PathVariable int id) {
userService.deleteById(id);
}Solution
Step 1: Check URL and method parameters
The method expects @PathVariable int id but URL is "/users" without {id} placeholder.Step 2: Understand path variable binding
Without {id} in URL, Spring cannot bind path variable, causing error.Final Answer:
The URL does not include the path variable placeholder {id} -> Option AQuick Check:
Path variable needs matching {id} in URL [OK]
- Forgetting to add {id} in URL path
- Using @PathVariable without URL placeholder
- Confusing @RequestParam with @PathVariable
@PutMapping?Solution
Step 1: Check for product existence before update
@PutMapping("/products/{id}") public ResponseEntity<Product> updatePrice(@PathVariable int id, @RequestBody Product p) { return productService.findById(id) .map(existing -> { existing.setPrice(p.getPrice()); productService.save(existing); return ResponseEntity.ok(existing); }) .orElse(ResponseEntity.notFound().build()); } uses productService.findById(id) to check if product exists, returning 404 if not.Step 2: Update price only if product found and return proper HTTP response
The map lambda updates the price on the existing product, saves it, and returns ResponseEntity.ok(existing); orElse returns notFound().Final Answer:
@PutMapping("/products/{id}") public ResponseEntity<Product> updatePrice(@PathVariable int id, @RequestBody Product p) { return productService.findById(id) .map(existing -> { existing.setPrice(p.getPrice()); productService.save(existing); return ResponseEntity.ok(existing); }) .orElse(ResponseEntity.notFound().build()); } -> Option DQuick Check:
Check existence, update, return 404 if missing [OK]
- Not checking if product exists before update
- Using @RequestParam instead of @PathVariable for ID
- Not returning 404 when product missing
Ready to prove it?
Pass the test and this pattern moves unknown
