Video in progress
When do you use @GetMapping, @PostMapping, @PutMapping and @DeleteMapping?
These are shorthand forms of @RequestMapping, each bound to one HTTP method. GET reads, POST creates a new resource, PUT replaces it completely, DELETE removes it.
📖 Answer
@RestController
@RequestMapping("/api/books")
class BookController {
@GetMapping("/{id}") // get a book
BookDto get(@PathVariable Long id) { ... }
@PostMapping // create a new book
ResponseEntity<BookDto> create(@RequestBody NewBook req) { ... }
@PutMapping("/{id}") // replace the book completely
BookDto replace(@PathVariable Long id, @RequestBody NewBook req) { ... }
@DeleteMapping("/{id}") // delete
void delete(@PathVariable Long id) { ... }
}
@GetMapping("/x") really means @RequestMapping(value = "/x", method = RequestMethod.GET), just easier to read. For partial updates there's also @PatchMapping.
Things to remember:
- GET must not change anything: browsers, proxies and crawlers will happily resend it;
- don't send a body with GET; make filters query parameters;
- for a request with the wrong method, Spring returns
405 Method Not Allowedby itself.
Sign up to mark studied questions and save your progress.