Bird
Raised Fist0
Spring Bootframework~10 mins

@PutMapping and @DeleteMapping in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @PutMapping and @DeleteMapping
Client sends HTTP PUT request
↓
@PutMapping method matches URL
↓
Method updates resource
↓
Return updated resource or status
↓
Client sends HTTP DELETE request
↓
@DeleteMapping method matches URL
↓
Method deletes resource
↓
Return deletion confirmation or status
The flow shows how HTTP PUT and DELETE requests are handled by Spring Boot methods annotated with @PutMapping and @DeleteMapping to update or delete resources.
Execution Sample
Spring Boot
@PutMapping("/items/{id}")
public Item updateItem(@PathVariable int id, @RequestBody Item newItem) {
    // update logic
    return updatedItem;
}

@DeleteMapping("/items/{id}")
public void deleteItem(@PathVariable int id) {
    // delete logic
}
This code updates an item with PUT and deletes an item with DELETE based on the item id.
Execution Table
StepRequest TypeURLMethod MatchedAction TakenResponse
1PUT/items/5@PutMapping("/items/{id}")Update item with id=5Return updated item
2DELETE/items/3@DeleteMapping("/items/{id}")Delete item with id=3Return deletion confirmation
3PUT/items/10@PutMapping("/items/{id}")Update item with id=10Return updated item
4DELETE/items/99@DeleteMapping("/items/{id}")Delete item with id=99Return deletion confirmation
5GET/items/5No matchNo action404 Not Found
💡 Execution stops when no matching mapping is found or after response is sent.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
idN/A531099N/A
newItemN/AProvided in PUT bodyN/AProvided in PUT bodyN/AN/A
itemsCollectionInitial itemsItem 5 updatedItem 3 deletedItem 10 updatedItem 99 deletedFinal state
Key Moments - 3 Insights
Why does a GET request to /items/5 not match @PutMapping or @DeleteMapping?
Because @PutMapping and @DeleteMapping only handle PUT and DELETE HTTP methods respectively, not GET. See execution_table row 5 where GET has no match.
What happens if the item id does not exist when updating or deleting?
The method can return a 404 Not Found or handle the error internally. This is not shown in the table but is common practice.
How does Spring know which method to call for a request?
Spring matches the HTTP method (PUT or DELETE) and the URL pattern to the annotated method, as shown in execution_table steps 1-4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response when a DELETE request is sent to /items/3?
AReturn updated item
BReturn deletion confirmation
C404 Not Found
DNo action
💡 Hint
Check execution_table row 2 under Response column.
At which step does the PUT request update the item with id=10?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 3 for PUT requests and id values.
If a GET request is sent to /items/5, what will happen according to the execution_table?
ANo match, 404 Not Found
BDelete item with id=5
CUpdate item with id=5
DReturn deletion confirmation
💡 Hint
See execution_table row 5 for GET request handling.
Concept Snapshot
@PutMapping and @DeleteMapping handle HTTP PUT and DELETE requests.
Use @PutMapping("/path/{id}") to update a resource by id.
Use @DeleteMapping("/path/{id}") to delete a resource by id.
Spring matches request method and URL to call the correct handler.
Return updated resource or confirmation status after action.
Full Transcript
This visual execution shows how Spring Boot handles HTTP PUT and DELETE requests using @PutMapping and @DeleteMapping annotations. When a client sends a PUT request to a URL like /items/5, Spring calls the method annotated with @PutMapping matching that URL pattern. The method updates the item with id 5 and returns the updated item. Similarly, a DELETE request to /items/3 calls the @DeleteMapping method to delete the item with id 3 and returns a confirmation. If a request uses a different HTTP method like GET, no matching method is found, resulting in a 404 Not Found. Variables like the item id and the collection of items change as updates and deletions happen. This step-by-step trace helps beginners see how Spring routes requests and changes state.

Practice

(1/5)
1. What is the primary purpose of the @PutMapping annotation in Spring Boot?
easy
A. To handle HTTP GET requests for retrieving data
B. To handle HTTP PUT requests for updating existing resources
C. To handle HTTP POST requests for creating new resources
D. To handle HTTP DELETE requests for removing resources

Solution

  1. Step 1: Understand HTTP methods

    HTTP PUT is used to update existing data on the server.
  2. Step 2: Match annotation to HTTP method

    @PutMapping maps HTTP PUT requests to controller methods.
  3. Final Answer:

    To handle HTTP PUT requests for updating existing resources -> Option B
  4. Quick Check:

    @PutMapping = update data [OK]
Hint: Put means update existing data via HTTP PUT [OK]
Common Mistakes:
  • Confusing @PutMapping with @PostMapping
  • Thinking @PutMapping creates new data
  • Mixing HTTP methods like GET or DELETE
2. Which of the following is the correct syntax to define a method that deletes a resource by ID using @DeleteMapping?
easy
A. @DeleteMapping("/items/{id}") public void deleteItem(int id) {}
B. @DeleteMapping("/items") public void deleteItem(int id) {}
C. @DeleteMapping("/items/{id}") public void deleteItem(@PathVariable int id) {}
D. @DeleteMapping("/items") public void deleteItem(@RequestParam int id) {}

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    @DeleteMapping("/items/{id}") public void deleteItem(@PathVariable int id) {} -> Option C
  4. Quick Check:

    Delete by ID needs @PathVariable and matching URL [OK]
Hint: Use @PathVariable with URL {id} in @DeleteMapping [OK]
Common Mistakes:
  • Omitting @PathVariable annotation
  • Using @RequestParam instead of @PathVariable for path params
  • Not matching method parameter to URL placeholder
3. Given the following Spring Boot controller method, what will happen when a PUT request is sent to /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);
}
medium
A. The user with ID 5 will be updated with the JSON data and returned
B. A new user will be created ignoring the ID in the URL
C. The request will fail because @RequestBody is missing
D. The user ID will not be set and cause an error

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The user with ID 5 will be updated with the JSON data and returned -> Option A
  4. Quick Check:

    PUT updates resource with URL ID and JSON body [OK]
Hint: PUT with @RequestBody updates resource using URL ID [OK]
Common Mistakes:
  • Assuming PUT creates new resource instead of updating
  • Ignoring @PathVariable ID and using JSON ID only
  • Missing @RequestBody causing request failure
4. Identify the error in this Spring Boot controller method intended to delete a user by ID:
@DeleteMapping("/users")
public void deleteUser(@PathVariable int id) {
    userService.deleteById(id);
}
medium
A. The URL does not include the path variable placeholder {id}
B. The method should use @RequestParam instead of @PathVariable
C. The method should return a value instead of void
D. The @DeleteMapping annotation is missing

Solution

  1. Step 1: Check URL and method parameters

    The method expects @PathVariable int id but URL is "/users" without {id} placeholder.
  2. Step 2: Understand path variable binding

    Without {id} in URL, Spring cannot bind path variable, causing error.
  3. Final Answer:

    The URL does not include the path variable placeholder {id} -> Option A
  4. Quick Check:

    Path variable needs matching {id} in URL [OK]
Hint: Match @PathVariable with {id} in URL path [OK]
Common Mistakes:
  • Forgetting to add {id} in URL path
  • Using @PathVariable without URL placeholder
  • Confusing @RequestParam with @PathVariable
5. You want to implement a REST API in Spring Boot that updates a product's price only if the product exists, otherwise returns 404. Which combination of annotations and code best achieves this using @PutMapping?
hard
A. @PutMapping("/products/{id}") public Product updatePrice(@RequestParam int id, @RequestBody Product p) { p.setId(id); return productService.save(p); }
B. @PutMapping("/products") public Product updatePrice(@RequestBody Product p) { productService.save(p); return p; }
C. @PutMapping("/products/{id}") public void updatePrice(@PathVariable int id, @RequestBody Product p) { productService.save(p); }
D. @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()); }

Solution

  1. 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.
  2. 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().
  3. 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 D
  4. Quick Check:

    Check existence, update, return 404 if missing [OK]
Hint: Check existence first, then update and return ResponseEntity [OK]
Common Mistakes:
  • Not checking if product exists before update
  • Using @RequestParam instead of @PathVariable for ID
  • Not returning 404 when product missing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard