Sub topic 4
Mapping HTTP methods with @GetMapping, @PostMapping and friends
This chapter assumes you can write a basic @RestController and know what GET, POST, PUT, PATCH and DELETE mean in HTTP. It covers how Spring MVC picks a controller method from the HTTP method and the URL, and which errors to expect when the mapping is wrong.
From @RequestMapping to the shortcuts
@RequestMapping is the general mapping annotation. It accepts a path and an HTTP method:
@RequestMapping(path = "/api/books", method = RequestMethod.GET)If you leave out method, the handler matches every HTTP method. That is rarely what you want. Spring provides one shortcut annotation per method, and each is @RequestMapping with the method preset.
| Annotation | HTTP method | Typical use | Safe | Idempotent |
|---|---|---|---|---|
| `@GetMapping` | GET | Read a resource or a collection | Yes | Yes |
| `@PostMapping` | POST | Create a resource | No | No |
| `@PutMapping` | PUT | Replace a resource | No | Yes |
| `@PatchMapping` | PATCH | Change part of a resource | No | Not guaranteed |
| `@DeleteMapping` | DELETE | Remove a resource | No | Yes |
A safe method does not change server state. An idempotent method has the same effect whether you call it once or many times. Clients, proxies and retry logic rely on both properties, so choose the annotation that matches what your code does.
Combining class-level and method-level paths
A @RequestMapping on the class sets a prefix. The path on each method is appended to it.
package com.example.books;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list() {
return service.findAll();
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
return ResponseEntity.created(URI.create("/api/books/" + created.id())).body(created);
}
@PutMapping("/{id}")
public BookResponse replace(@PathVariable long id, @RequestBody CreateBookRequest request) {
return service.replace(id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) {
service.delete(id);
}
}The example assumes a BookService with findAll, get, create, replace and delete methods, and the CreateBookRequest and BookResponse records from the earlier chapters. The five handlers map to these requests:
GET /api/bookscallslist.GET /api/books/7callsget.POST /api/bookscallscreate.PUT /api/books/7callsreplace.DELETE /api/books/7callsdelete.
The same URL can appear on several methods because the HTTP method is part of the mapping key.
Narrowing a mapping with consumes and produces
Every mapping annotation accepts consumes and produces. These restrict the request Content-Type and the response media type.
@PostMapping(consumes = "application/json", produces = "application/json")A request with a different Content-Type gets 415 Unsupported Media Type. A request whose Accept header cannot be satisfied gets 406 Not Acceptable.
Common errors
- 405 instead of 404. The path exists, but not for that HTTP method. Check for a missing
@PostMappingor a wrong annotation. The response includes anAllowheader that lists the supported methods. - 404 on a trailing slash. Since Spring Framework 6,
/api/books/no longer matches/api/books. Call the exact path. - Ambiguous mapping at startup. Two methods with the same path, HTTP method and media types cause an
IllegalStateException. The application fails to start. - Using GET to change state. Crawlers, prefetching and caches may call GET without user intent. Use POST, PUT, PATCH or DELETE for any change.
- PUT used as a partial update. PUT replaces the whole resource. Use PATCH for partial changes.
Exercise
A client sends DELETE /api/books to the controller above and receives 405 Method Not Allowed. Why is it 405 and not 404, and what would you add if you wanted to support the request?
Show answer
The path /api/books is mapped, but only for GET and POST, so Spring finds a path match with no method match and returns 405. To support it, add a method annotated with @DeleteMapping (with no path) in BookController. First decide whether deleting the whole collection is something you want to allow.