@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:

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

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

Which mapping wins

For a request, the router:

  1. 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.;
  2. keeps those of the request's HTTP method; a GET mapping also answers HEAD. None: a 405 with an Allow header (or, for OPTIONS, a 200 with Allow);
  3. keeps those whose consumes includes the Content-Type (else 415);
  4. keeps those whose produces suits Accept (else 406);
  5. keeps those whose headers conditions hold (else 400);
  6. 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/new wins over /books/{isbn}. For equal patterns, the mapping with more conditions (produces, consumes, headers) wins.

Rules:

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:

See also