@RequestMapping and @GetMapping
The mapping annotations say which requests a controller method answers: the HTTP method, the path, and optional conditions on the Content-Type, the Accept header and other headers.
Why
Each endpoint is one method with one annotation, so the routes of an API can be read off the controller. The router compares every request with these mappings, picks the most specific one, and answers the standard errors when none fits: 404 for an unknown path, 405 for a known path with another method, 415 for a body type the method does not read, 406 for an Accept it cannot answer.
The annotations
| Annotation | HTTP method |
|---|---|
@GetMapping |
GET (and HEAD) |
@PostMapping |
POST |
@PutMapping |
PUT |
@PatchMapping |
PATCH |
@DeleteMapping |
DELETE |
@RequestMapping |
any method, chosen with method:; on a class, the base path |
Each has two constructors, because Dart does not allow an optional positional parameter next to named ones:
@GetMapping('/path'): the path only. Without a path,@GetMapping()maps the base path itself.@GetMapping.of(path: '/path', produces: ..., consumes: ..., headers: [...]): every attribute by name.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
class Book {
const Book({required this.isbn, required this.title});
final String isbn;
final String title;
}
@RestController()
@RequestMapping('/api/books') // the prefix of every method below
class BookController {
// GET /api/books
@GetMapping()
List<Book> all() => const [Book(isbn: '978-0', title: 'Dune')];
// GET /api/books/978-0
@GetMapping('/{isbn}')
Book find(@PathVariable() String isbn) => Book(isbn: isbn, title: 'Dune');
// POST /api/books, only with a JSON body.
@PostMapping.of(consumes: MediaType.applicationJson)
Book create(@RequestBody() Book book) => book;
// PUT /api/books/978-0 replaces the book.
@PutMapping('/{isbn}')
Book replace(@PathVariable() String isbn, @RequestBody() Book book) => book;
// PATCH /api/books/978-0 changes some fields.
@PatchMapping('/{isbn}')
Map<String, Object?> update(
@PathVariable() String isbn,
@RequestBody() Map<String, Object?> changes,
) => changes;
// DELETE /api/books/978-0 → 204
@DeleteMapping('/{isbn}')
@ResponseStatus(HttpStatus.noContent)
void delete(@PathVariable() String isbn) {}
// GET /api/books/export with Accept: text/csv (or */*, or no Accept):
// both methods match, and this one has more conditions, so it wins.
@GetMapping.of(path: '/export', produces: 'text/csv')
String csv() => 'isbn,title\n978-0,Dune\n';
// With Accept: application/json the CSV method is left out: JSON.
@GetMapping('/export')
List<Book> json() => all();
// Version 2 of a method, chosen by a header.
@GetMapping.of(path: '/{isbn}/summary', headers: ['X-Api-Version=2'])
String summaryV2(@PathVariable() String isbn) => 'v2 $isbn';
@GetMapping.of(path: '/{isbn}/summary', headers: ['X-Api-Version!=2'])
String summary(@PathVariable() String isbn) => 'v1 $isbn';
// A method without a shortcut annotation: HEAD.
@RequestMapping.of(path: '/{isbn}/exists', method: HttpMethod.head)
ResponseEntity<void> exists(@PathVariable() String isbn) =>
ResponseEntity.status(HttpStatus.ok).build();
}
On the class, @RequestMapping.of adds conditions for every method:
// Every method reads and writes JSON and needs the API key header.
@RestController()
@RequestMapping.of(
path: '/api/v2',
produces: MediaType.applicationJson,
consumes: MediaType.applicationJson,
headers: ['X-Api-Key'],
)
class V2Controller {
@GetMapping('/ping')
Map<String, String> ping() => {'status': 'ok'};
}
Attributes
Every mapping annotation has these attributes; method only on @RequestMapping.of.
| Name | Type | Default | Meaning |
|---|---|---|---|
path |
String |
'' |
The path pattern, relative to the class's @RequestMapping. Empty: the base path itself. It may hold {variables}, wildcards and ${...} placeholders. Positional in the short constructor. |
method |
HttpMethod |
HttpMethod.get |
Only @RequestMapping.of: the HTTP method (get, head, post, put, patch, delete, options, trace). Fixed by the shortcut annotations. Ignored on a class. |
produces |
String? |
null |
The media types of the response, one or a comma-separated list. The method is chosen only when Accept allows one of them (else a 406), and the body is written with it. null: any Accept. |
consumes |
String? |
null |
The media types of the request body, one or a comma-separated list. The method is chosen only when the Content-Type is one of them (else a 415). null: any body. |
headers |
List<String> |
const [] |
Conditions on the request headers (see below). When no method meets them, a 400. |
@RequestMapping('/path') (the short form) maps GET. It is the usual form on a class, where only the path counts.
Paths
Paths are path patterns (PathPattern of spring_web_dart), matched against the request path without the query string and without server.context-path.
| Pattern | Matches |
|---|---|
/books |
the path itself. A trailing slash matters: /books/ is another path, as in Spring 6. |
/books/{isbn} |
one segment, captured as isbn and decoded |
/books/{isbn:\d+} |
one segment that matches the regular expression, captured |
/files/{*path} |
the rest of the path, captured with its leading / (at the end only) |
/static/** |
zero or more segments (at the end only) |
/b?ok |
?: one character of a segment |
/*.json |
*: zero or more characters of a segment |
- Combining. The class path and the method path are joined:
@RequestMapping('/api/books')and@GetMapping('/{isbn}')give/api/books/{isbn}. A missing leading/is added. - Placeholders.
${...}in a path is filled from the configuration at startup:@GetMapping(r'${shop.api.base:/api}/books'). The same works inproducesandconsumes. Write such paths as raw strings (r'...') so Dart does not read$itself. - Matrix parameters are left out of the matching, as in Spring:
/books/1111;v=1matches/books/{isbn}withisbn1111. - Unsafe paths never arrive. The server answers a path with an encoded
/,\or NUL (%2F,%5C,%00), a.or..segment hidden by matrix parameters (/files/..;/secret), or a%escape that is not UTF-8 with a 400, before any filter. So..%2F..%2Fsecretnever reaches a path variable. - A malformed pattern stops the start:
**or{*name}before the end, unbalanced braces, an invalid regular expression, a variable used twice (see Startup checks).
Header conditions
Each entry of headers is one condition, in Spring's syntax. The class's entries and the method's entries add up.
| Entry | The request must |
|---|---|
'X-Api-Key' |
have the header |
'!X-Debug' |
not have the header |
'X-Api-Version=2' |
have the header with exactly this value |
'X-Api-Version!=2' |
not have the header with this value (a missing header passes) |
A request that matches the path, the method and the media types but no header condition gets a 400 Unsatisfied header conditions.
Media types
consumesis compared with the request'sContent-Type; a type such asapplication/*includesapplication/json. A request without aContent-Typeis compared asapplication/octet-stream, as in Spring. The 415 answer has anAcceptheader that lists the types the path reads.producesis compared with the request'sAccept. A request withoutAccept(or with one that does not parse) accepts everything. The 406 answer's detail lists the types the path writes:Acceptable representations: [text/csv].- The written type. For a mapping with
produces, the response'sContent-Typeis the first of its types that the client accepts, in the order of the client'sqvalues. See Results. - On a class and a method, the method's
producesorconsumesreplaces the class's; it does not add to it. - Media type constants are on
MediaType:applicationJson,applicationProblemJson,applicationNdjson,applicationOctetStream,applicationFormUrlencoded,multipartFormData,textPlain,textHtml,textEventStream,imagePngand more.
Which mapping wins
For a request, the router:
- keeps the mappings whose pattern matches the path. None: the next handler mapping is asked (the WebSocket endpoints, the static resources), then a 404
No endpoint GET /x.; - keeps those of the request's HTTP method; a
GETmapping also answersHEAD. None: a 405 with anAllowheader (or, forOPTIONS, a 200 withAllow); - keeps those whose
consumesincludes theContent-Type(else 415); - keeps those whose
producessuitsAccept(else 406); - keeps those whose
headersconditions hold (else 400); - takes the most specific pattern: a pattern without
**or{*name}before one with them, then the one with fewer variables and wildcards, then the one with the longer fixed text. So/books/newwins over/books/{isbn}. For equal patterns, the mapping with more conditions (produces,consumes,headers) wins.
Rules:
HEADruns theGETmethod. The handler writes as usual; the body is dropped andContent-Lengthis kept.OPTIONSto a mapped path without anOPTIONSmapping is answered with200andAllow, listing the mapped methods,HEADwhen there is aGET, andOPTIONS.- CORS pre-flights (
OPTIONSwithOriginandAccess-Control-Request-Method) are answered from the CORS rules, never passed to a method (see CORS). - Two methods mapping the same request (the same method, pattern and conditions) stop the start with
Ambiguous mapping. - One mapping per method. Several mapping annotations on one method stop the start; use
@RequestMapping.offor the other HTTP methods. - Any method may stream. A
POSTcan answer with server-sent events as well as aGET(see Server-sent events).
To see every mapping at startup, set logging.level.spring.web.mvc=trace: one line per mapping (Mapped GET /api/books/{isbn} -> BookController.find), after the count at debug level (12 mappings in 'requestMappingHandlerMapping'). At debug level each request also logs the chosen method (Mapped to BookController#find()).
In Spring (Java)
@RestController
@RequestMapping("/api/books")
class BookController {
@GetMapping("/{isbn}")
Book find(@PathVariable String isbn) { ... }
@GetMapping(path = "/export", produces = "text/csv")
String csv() { ... }
@RequestMapping(path = "/{isbn}/exists", method = RequestMethod.HEAD)
ResponseEntity<Void> exists(@PathVariable String isbn) { ... }
}
Differences that matter:
- Attributes other than the path need the
.ofconstructor:@GetMapping.of(path: '/export', produces: 'text/csv'). produces,consumesandmethodtake one value (a comma-separated list for media types), not arrays.pathtakes one pattern, not several.paramsconditions (params = "version=2") are not supported.- More mistakes stop the start (see Startup checks).