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

```dart
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:

```dart
// 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 in `produces` and `consumes`. 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=1` matches `/books/{isbn}` with `isbn` `1111`.
- **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..%2Fsecret` never 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](startup-checks.md)).

## 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

- **`consumes`** is compared with the request's `Content-Type`; a type such as `application/*` includes `application/json`. A request without a `Content-Type` is compared as `application/octet-stream`, as in Spring. The 415 answer has an `Accept` header that lists the types the path reads.
- **`produces`** is compared with the request's `Accept`. A request without `Accept` (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's `Content-Type` is the first of its types that the client accepts, in the order of the client's `q` values. See [Results](results.md).
- **On a class and a method**, the method's `produces` or `consumes` replaces the class's; it does not add to it.
- Media type constants are on `MediaType`: `applicationJson`, `applicationProblemJson`, `applicationNdjson`, `applicationOctetStream`, `applicationFormUrlencoded`, `multipartFormData`, `textPlain`, `textHtml`, `textEventStream`, `imagePng` and more.

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

- **`HEAD`** runs the `GET` method. The handler writes as usual; the body is dropped and `Content-Length` is kept.
- **`OPTIONS`** to a mapped path without an `OPTIONS` mapping is answered with `200` and `Allow`, listing the mapped methods, `HEAD` when there is a `GET`, and `OPTIONS`.
- **CORS pre-flights** (`OPTIONS` with `Origin` and `Access-Control-Request-Method`) are answered from the CORS rules, never passed to a method (see [CORS](../cors.md)).
- **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.of` for the other HTTP methods.
- **Any method may stream.** A `POST` can answer with server-sent events as well as a `GET` (see [Server-sent events](../streaming/sse.md)).

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)

```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 `.of` constructor: `@GetMapping.of(path: '/export', produces: 'text/csv')`.
- `produces`, `consumes` and `method` take one value (a comma-separated list for media types), not arrays. `path` takes one pattern, not several.
- `params` conditions (`params = "version=2"`) are not supported.
- More mistakes stop the start (see [Startup checks](startup-checks.md)).

## See also

- [@PathVariable](path-variable.md)
- [Results](results.md)
- [Errors](../errors/index.md)
- [CORS](../cors.md)
- [Placeholders](../../spring-core-dart/config/placeholders.md)
