Controller annotations

These annotations turn a class into a web controller and decide how its answers and errors look. The web server (spring_boot_starter_web) reads them; they live in this package so that other packages can see them without depending on the server.

Why

A library that adds endpoints, or a tool that lists an application's API, needs the annotations but not a running server. Keeping them here keeps those dependencies light.

Example

@RestController()
@RequestMapping('/api/books')
@CrossOrigin(origins: ['https://shop.neon.books']) // the shop's pages may call it
class BookController {
  BookController(this.books);

  final BookService books;

  // POST /api/books answers 201 Created instead of 200.
  @PostMapping()
  @ResponseStatus(HttpStatus.created)
  Future<Book> create(@RequestBody() Book book) => books.create(book);

  // A book that is already there becomes a 409 for every method above.
  @ExceptionHandler()
  ProblemDetail duplicate(DuplicateBookException e) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.conflict, e.message);
}

The annotations

Annotation On Spring Meaning
@RestController([name]) class @RestController A bean whose mapped methods answer requests; the return value is the response body.
@RequestMapping('/api/books') class the same The path prefix of every method, and produces, consumes, headers for all of them.
@ResponseStatus(HttpStatus.created, reason: ...) method, controller class the same The status of a normal answer. With reason, the result is ignored and the answer is an error with the reason as its detail.
@ExceptionHandler([types]) method the same Handles exceptions thrown by the controller's methods (by every controller's, in an advice). The exception parameter's type picks them, or types, matched by exact runtime type.
@ControllerAdvice([name]), @RestControllerAdvice([name]) class the same Exception handlers for every controller, tried in @Order.
@CrossOrigin(origins:, originPatterns:, methods:, allowedHeaders:, exposedHeaders:, allowCredentials:, allowPrivateNetwork:, maxAge:) class, method the same Lets web pages of other origins call the controller (CORS). maxAge is in seconds.

@CrossOrigin() with no arguments allows every origin, the method the handler is mapped to (DELETE for a @DeleteMapping, GET alone for a @GetMapping), every request header, no credentials, and a pre-flight cache of 30 minutes, as in Spring.

How the server applies them is described in the web starter: @RestController, @ExceptionHandler, @ControllerAdvice, CORS.

In Spring (Java)

@RestController
@RequestMapping("/api/books")
@CrossOrigin(origins = "https://shop.neon.books")
class BookController { ... }

The same annotations. @ExceptionHandler(types) matches by exact runtime type: Dart cannot test at run time whether one Type is a subtype of another.

See also