When you start writing APIs with Spring Boot, you’ll often run into samples that mix @RequestMapping and @GetMapping, and it’s easy to wonder, “So which one should I actually use?”
The short answer: @GetMapping and @PostMapping are composed annotations that give you a shorter way to write @RequestMapping(method = ...). Put @RequestMapping on the class for the shared path and @GetMapping and friends on the methods, and that pattern covers almost every case.
This article focuses on mapping, which ties a URL, HTTP method and Content-Type to a handler. We’ll cover how paths are combined, the attributes that narrow a match, and how to fix the 404, 405, 415 and 406 errors and the Ambiguous mapping failure that mappings can cause. The examples assume Spring Boot 3.x (Spring Framework 6).
We’ll assume your class is annotated with @RestController. If you haven’t set up the dependencies yet, start with the guide to spring-boot-starter-web.
@GetMapping Is Shorthand for @RequestMapping(method = GET)
If you open the source of @GetMapping, you’ll see this (excerpt):
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
@AliasFor(annotation = RequestMapping.class)
String[] value() default {};
// path, params, headers, consumes, produces も同様
}
@RequestMapping(method = RequestMethod.GET) is applied as a meta-annotation. Attributes such as value and produces are passed straight through to @RequestMapping via @AliasFor. That means these two behave the same way:
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> findAll() { ... }
@GetMapping("/users")
public List<User> findAll() { ... }
Because @Target is METHOD only, you can’t put @GetMapping on a class. That’s why you use @RequestMapping for the class-level prefix.
Be careful: if you leave out method on @RequestMapping, it matches every HTTP method. A handler meant for GET could then be called with DELETE as well, so it’s safer to use the composed annotations on methods.
Quick Reference: Which Annotation to Use
| HTTP Method | Annotation | Typical Use | Example Success Status |
|---|---|---|---|
| GET | @GetMapping | Retrieve | 200 |
| POST | @PostMapping | Create | 201 |
| PUT | @PutMapping | Full update | 200 / 204 |
| PATCH | @PatchMapping | Partial update | 200 / 204 |
| DELETE | @DeleteMapping | Delete | 204 |
The rule is “@RequestMapping on the class, composed annotations on the methods.” About the only time you’d use @RequestMapping on a method is the unusual case where one handler needs to accept several HTTP methods.
For how to return status codes, see the @ResponseStatus article. For a working implementation of all four endpoints from start to finish, see the CRUD tutorial.
How Class and Method Paths Are Combined
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping // GET /api/users
public List<User> findAll() { ... }
@GetMapping("/{id:\\d+}") // GET /api/users/1(数字のみ、後述)
public User findById(@PathVariable Long id) { ... }
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) // POST /api/users
public User create(@RequestBody User user) { ... }
@DeleteMapping("/{id:\\d+}") // DELETE /api/users/1
public void delete(@PathVariable Long id) { ... }
}
The class-level and method-level paths are concatenated. Writing "users" is treated the same as "/users", so you don’t need to worry about the leading slash. If you leave the path off the method, it matches the prefix itself. You can also list several paths, as in @GetMapping({"/me", "/current"}).
consumes and produces, on the other hand, are overridden rather than combined. Even if the class declares produces, a value set on the method replaces it, and only the method’s value applies. params and headers add both sets of conditions together, so keep the two behaviors separate in your head.
Writing Path Patterns
Since Spring Boot 2.6, PathPatternParser has been the default path parser. These are the patterns you’ll use most often (class prefix omitted):
@GetMapping("/{id}") // /1 も /abc も一致
@GetMapping("/{id:\\d+}") // 数字のみ。/abc は404
@GetMapping("/*/summary") // 1セグメント分の任意の文字列
@GetMapping("/files/**") // 残りのパスすべて(末尾でのみ使える)
@GetMapping("/files/{*path}") // 残りのパスを変数 path で受け取る
The UserController above uses {id:\\d+} because a plain /{id} would also match unrelated URLs such as /api/users/export. If IDs are always numeric, restricting the pattern prevents accidents.
The older AntPathMatcher let you put ** in the middle of a pattern, as in /a/**/b, but Boot 3’s PathPatternParser rejects it with an error. Watch out for this when you copy patterns from older articles.
Reading path variable values into method arguments is covered in How to Receive Request Parameters, so we’ll skip it here.
Trailing Slashes No Longer Match in Spring Boot 3
In Boot 2, a request to /api/users/ still matched /api/users. Starting with Spring Framework 6 (Boot 3), it no longer matches by default and you get a 404. If you suddenly see 404s right after migrating, check this first. Suffix pattern matching, which matched URLs with extensions like /users.json, has also been removed.
The usual fix is to correct the URL on the client side. If you really need to accept both, declare them explicitly:
@GetMapping({"", "/"}) // /api/users と /api/users/ の両方
public List<User> findAll() { ... }
The setting that turns trailing slash matching back on globally is deprecated and scheduled for removal, so it’s best not to depend on it.
Narrowing Matches with params and headers
You can route requests to the same path to different handlers based on query parameters or headers.
@GetMapping(path = "/search", params = "type=admin")
public List<User> searchAdmins() { ... }
@GetMapping(path = "/search", params = "type=member")
public List<User> searchMembers() { ... }
@GetMapping(path = "/report", headers = "X-API-Version=2")
public Report reportV2() { ... }
Prefixing a parameter with !, as in params = "!debug", makes the condition “this parameter is absent.”
When a condition isn’t met, a headers mismatch gives a 404, but a mismatch on params alone gives a 400 (UnsatisfiedServletRequestParameterException). If the path is right but you get a 400, check your params. Header-based versioning is covered in the API versioning strategies article.
Controlling Content-Type with consumes and produces
These two are easy to confuse. consumes is a condition on the request’s Content-Type, and produces sets the response format. produces is matched against the request’s Accept header.
@GetMapping(path = "/export", produces = MediaType.APPLICATION_JSON_VALUE)
public List<User> exportJson() { ... }
@GetMapping(path = "/export", produces = "text/csv")
public String exportCsv() { ... }
For the same path, a request with Accept: text/csv is routed to the CSV version. Using MediaType constants instead of string literals helps prevent typos (text/csv has no constant, so it’s a string here). You can also write negations such as consumes = "!text/plain".
Reproducing 404, 405, 415 and 406 with curl
The status code usually tells you which condition failed to match. Use curl -i so you can see the headers too.
# 404: 末尾スラッシュ(Boot 3)
$ curl -i http://localhost:8080/api/users/
HTTP/1.1 404
# 405: GETとDELETEしかないパスにPOST
$ curl -i -X POST http://localhost:8080/api/users/1
HTTP/1.1 405
Allow: GET,DELETE
# 415: Content-Type忘れ(curl -d はform形式で送る)
$ curl -i -X POST http://localhost:8080/api/users -d '{"name":"taro"}'
HTTP/1.1 415
# 406: producesにないAcceptを要求
$ curl -i http://localhost:8080/api/users/export -H 'Accept: application/xml'
HTTP/1.1 406
| Status | Common Causes | Fix |
|---|---|---|
| 404 | Typo in the path, missing prefix, trailing slash, headers mismatch | Compare the URL against the mapping |
| 405 | Wrong HTTP method | Check the Allow header for the accepted methods |
| 415 | Content-Type doesn’t match consumes or @RequestBody | Add -H 'Content-Type: application/json' |
| 406 | Accept doesn’t match produces | Fix the Accept header or add to produces |
If you want a consistent JSON format for error responses, see the article on unified error responses.
Reading and Fixing Ambiguous Mapping at Startup
If two handlers are mapped to the same path and the same method, the application fails at startup.
@GetMapping
public List<User> findAll() { ... }
@GetMapping // コピペで残ったメソッド
public List<User> findAllV2() { ... }
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'userController' method
com.example.demo.UserController#findAllV2()
to {GET [/api/users]}: There is already 'userController' bean method
com.example.demo.UserController#findAll() mapped.
You need to read three parts. After Cannot map is the method Spring tried to register, to {...} shows the conflicting condition, and after There is already is the method that was already registered. To resolve it, either use different paths or differentiate the conditions with params, headers or produces. If one of them is leftover from copy-pasting, just delete it.
For narrowing down other startup errors as well, see Troubleshooting Spring Boot Startup Failures.
Testing Mapping Errors with MockMvc
To avoid accidentally introducing 405 or 415 errors when you change mappings, lock in the expected behavior with regression tests.
@WebMvcTest(UserController.class)
class UserControllerMappingTest {
@Autowired
MockMvc mockMvc;
@Test
void postToIdIsNotAllowed() throws Exception {
mockMvc.perform(post("/api/users/1"))
.andExpect(status().isMethodNotAllowed())
.andExpect(header().string("Allow", containsString("GET")));
}
@Test
void createWithTextIsUnsupported() throws Exception {
mockMvc.perform(post("/api/users")
.contentType(MediaType.TEXT_PLAIN).content("taro"))
.andExpect(status().isUnsupportedMediaType());
}
@Test
void exportAsXmlIsNotAcceptable() throws Exception {
mockMvc.perform(get("/api/users/export").accept(MediaType.APPLICATION_XML))
.andExpect(status().isNotAcceptable());
}
}
If your controller depends on a Service, provide a mock with @MockitoBean. The basics of @WebMvcTest are covered in Testing Controllers with MockMvc.
Summary
@GetMapping and its siblings are shorthand for @RequestMapping(method = ...), so put @RequestMapping on the class and the composed annotations on the methods.
When an error shows up, suspect the path for a 404, the HTTP method for a 405, consumes for a 415, produces for a 406, and a duplicate mapping for a startup failure. Once you can work backward from the status code to the cause, you’ll spend far less time stuck on mapping problems.
Next, try building a real API with How to Receive Request Parameters or the CRUD tutorial.
Notes:
- Internal links: I left every internal link exactly as it was. They all still point to
/ja/pages. If English versions exist, you may want to change them to/en/. - Code comments: Code blocks are unchanged, so their comments are still in Japanese (for example
// 数字のみ、後述).