Sub topic 4
Mapping HTTP methods with @GetMapping, @PostMapping and friends
This chapter assumes you can write a basic @RestController, know what GET, POST, PUT, PATCH and DELETE mean in HTTP, and have a Spring Boot web project that starts. You will learn how Spring MVC picks a controller method for a request, how the shortcut annotations relate to @RequestMapping, and which mistakes cause 404, 405 and 415 responses.
How Spring MVC chooses a method
Every incoming request passes through the DispatcherServlet. It asks a HandlerMapping which controller method should handle the request. In Spring Boot, the relevant implementation is RequestMappingHandlerMapping. It builds a registry at startup from every @RequestMapping and its shortcut annotations.
For each request, the registry compares the request against each mapping's conditions. A mapping can constrain:
- the URL path
- the HTTP method
- the
Content-Typeof the request body (consumes) - the
Acceptheader (produces) - required parameters and headers
If exactly one mapping matches, that method runs. If several match, Spring picks the most specific one. If none match, Spring responds with an error. The error depends on which condition failed.
This explains a common debugging question. A 405 means your path is right and your method is wrong. A 404 means no mapping has that path at all.
@RequestMapping and the shortcut annotations
@RequestMapping is the general annotation. It accepts a path and a list of HTTP methods:
@RequestMapping(path = "/api/books", method = RequestMethod.GET)Writing this on every method is verbose. Spring provides composed annotations that fix the method for you:
| Annotation | Equivalent to | Typical use |
|---|---|---|
| `@GetMapping` | `@RequestMapping(method = GET)` | Read a resource or a collection |
| `@PostMapping` | `@RequestMapping(method = POST)` | Create a resource |
| `@PutMapping` | `@RequestMapping(method = PUT)` | Replace a resource |
| `@PatchMapping` | `@RequestMapping(method = PATCH)` | Partially update a resource |
| `@DeleteMapping` | `@RequestMapping(method = DELETE)` | Remove a resource |
Use the shortcuts on methods. Use @RequestMapping on the class to set a shared base path, as the first example in this tutorial does with /api/books. Spring combines the class path and the method path, so @RequestMapping("/api/books") plus @GetMapping("/{id}") serves /api/books/{id}.
A complete CRUD controller
The following controller maps all five methods onto one resource. It builds on the BookController you have already seen. The service is assumed to expose search, get, create, replace, rename and delete methods.
import java.net.URI;
import java.util.List;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {}
public record RenameBookRequest(@NotBlank @Size(max = 200) String title) {}
public record BookResponse(long id, String title, String author) {}
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
public BookResponse replace(@PathVariable long id,
@Valid @RequestBody CreateBookRequest request) {
return service.replace(id, request);
}
@PatchMapping("/{id}")
public BookResponse rename(@PathVariable long id,
@Valid @RequestBody RenameBookRequest request) {
return service.rename(id, request.title());
}
@DeleteMapping("/{id}")
@ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void delete(@PathVariable long id) {
service.delete(id);
}
}Points to notice:
listandcreateboth use the path/api/books. They do not conflict because the HTTP method differs.get,replace,patchanddeleteshare/api/books/{id}. Again, the method separates them.deletereturnsvoid. Without@ResponseStatus, Spring would answer 200 with an empty body.204 No Contentis the more accurate choice, and@ResponseStatussets it.createreturnsResponseEntitybecause it needs aLocationheader. The next chapters coverResponseEntityin detail.
PUT versus PATCH
Both update a resource, but they promise different things.
- PUT replaces the whole resource. The client sends every field. If a field is missing, the server treats it as absent. PUT is idempotent: sending the same request twice leaves the same final state.
- PATCH changes only the fields the client sends. The request is smaller, but it is harder to implement correctly.
With a record like RenameBookRequest, PATCH is simple because it has one field. When a PATCH body can contain many optional fields, you cannot tell "field omitted" from "field set to null" using a plain DTO. Common solutions are a JSON Merge Patch library, or Optional-style wrapper types. Many teams avoid the problem by offering narrow, purpose-specific updates like the rename above.
Narrowing a mapping with consumes, produces and params
The shortcut annotations accept the same attributes as @RequestMapping. Three are useful in practice.
consumes limits the mapping to requests with a given Content-Type:
@PostMapping(path = "/import", consumes = "text/csv")
public ResponseEntity<Void> importCsv(@RequestBody String csv) {
// parse and store
return ResponseEntity.accepted().build();
}produces limits the mapping to requests whose Accept header allows the given type. It also sets the response Content-Type:
@GetMapping(path = "/{id}", produces = "application/json")
public BookResponse getJson(@PathVariable long id) {
return service.get(id);
}params requires a query parameter, or a specific value for one:
@GetMapping(params = "isbn")
public BookResponse byIsbn(@RequestParam String isbn) {
return service.findByIsbn(isbn);
}With this method added, GET /api/books?isbn=123 goes to byIsbn, while GET /api/books still goes to list. Spring prefers the mapping with more matching conditions.
Use these attributes sparingly. Two methods that differ only by params are harder to read than one method with an optional @RequestParam. Content negotiation gets its own chapter later in this tutorial.
Path patterns and ambiguity
A path can contain variables in braces. It can also contain wildcards:
/{id}matches one path segment./*matches one segment of any name./**matches zero or more segments, but only at the end of a pattern in Spring Boot 3.
When two patterns match the same URL, Spring chooses the more specific one. Given /api/books/featured and /api/books/{id}, a request to /api/books/featured goes to the literal path. A literal always beats a variable.
If two mappings are equally specific, Spring cannot choose. The application fails at startup with an IllegalStateException that says "Ambiguous mapping". This is a useful failure: you learn about the clash before any request arrives.
You can also restrict a variable with a regular expression:
@GetMapping("/{id:\\d+}")
public BookResponse getNumeric(@PathVariable long id) {
return service.get(id);
}Now /api/books/abc does not match this mapping and returns 404. Without the regex, Spring would try to convert abc to a long and fail with a 400 response. Decide which behavior you want.
Trailing slashes
In Spring Framework 6, which Spring Boot 3 uses, a mapping for /api/books no longer matches /api/books/. A client calling the version with a trailing slash gets a 404. Define the URLs your API exposes and document them. Do not rely on the old behavior.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 404 on a path you defined | Wrong base path, missing class-level `@RequestMapping`, or a trailing slash | Check the combined path. Use the startup log or Actuator mappings endpoint. |
| 405 Method Not Allowed | Path exists, but not for this HTTP method | Add the mapping or fix the client. The `Allow` response header lists supported methods. |
| 415 Unsupported Media Type | Client sent a body without `Content-Type: application/json`, or one that does not match `consumes` | Set the header in the client. |
| 406 Not Acceptable | `Accept` header asks for a type the method cannot produce | Remove the header or add a matching `produces`. |
| Startup failure: Ambiguous mapping | Two methods with identical conditions | Change one path, method or condition. |
| `@PathVariable` fails at runtime for a missing name | Variable name differs from the parameter name and the code was compiled without `-parameters` | Use `@PathVariable("id")`, or compile with `-parameters`. Spring Boot's Maven and Gradle plugins enable it by default. |
Choosing between PUT, PATCH and POST for updates
Use these criteria when you design an update endpoint:
- If clients always hold the full resource, use PUT. It is simple and idempotent.
- If clients change one or two fields, add PATCH with a small DTO, or a dedicated sub-resource such as
POST /api/books/{id}/rename. - If the operation is an action and not a state change, such as "publish" or "archive", a POST to an action path is more honest than forcing it into PUT or PATCH.
Consistency across your API matters more than strict adherence to any single rule.
Exercises
Exercise
A client sends DELETE /api/books/5 to a controller that only defines @GetMapping("/{id}") and @PutMapping("/{id}") for that path. Which status code does Spring return, and which response header tells the client what is allowed?
Show answer
Spring returns 405 Method Not Allowed. The path matches but no mapping handles DELETE. The Allow header lists the supported methods, here GET and PUT (plus HEAD and OPTIONS, which Spring adds for GET mappings).
Exercise
You have @GetMapping("/featured") and @GetMapping("/{id}") in the same controller under /api/books. A request arrives for /api/books/featured. Which method runs, and what happens at startup?
Show answer
The /featured method runs, because a literal path is more specific than a path variable. Startup succeeds because the two patterns are not equally specific, so there is no ambiguous mapping.
Exercise
Write a mapping for deleting a book that returns 204 No Content and takes the id from the path.
Show answer
@DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable long id) { service.delete(id); }