PUT and DELETE Routes
PUT and DELETE are request methods that change things. PUT replaces a thing, and DELETE removes a thing.
Replace a task
This method takes PUT requests for /tasks. The body carries the full new task.
@PutMapping("/tasks")
public TaskForm replace(@RequestBody TaskForm form) {
return form;
}Remove a task
Send DELETE /tasks. The method answers with one word.
@DeleteMapping("/tasks")
public String remove() {
return "Deleted";
}Example
package com.example.demo;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
record TaskForm(String title, boolean done) {
}
@PutMapping("/tasks")
public TaskForm replace(@RequestBody TaskForm form) {
return form;
}
@DeleteMapping("/tasks")
public String remove() {
return "Deleted";
}
}Key points
- @PutMapping marks a method as the answer for PUT requests.
- @DeleteMapping marks a method as the answer for DELETE requests.
- PUT carries a full new version in the JSON body.
- DELETE usually carries no body.
- Use POST to make a thing, PUT to replace it, and DELETE to remove it.
In this example, the record TaskForm holds a title and a done flag. The controller has two routes. The first route answers PUT requests for /tasks. It reads the JSON body into a TaskForm and returns the same form. The second route answers DELETE requests for /tasks. It returns the word Deleted. The PUT request marks the task done, and the answer echoes the new task. The DELETE request gets Deleted back.
Note
A browser address bar always sends GET, so it cannot test PUT or DELETE.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which annotation marks a method for DELETE requests?