@RestController
@RestController() marks a class whose methods answer HTTP requests: a REST controller. The class is a bean, and every method with a mapping annotation becomes an endpoint.
Why
It is the starting point of a web API. The class is a bean like any @Component, so its dependencies come through the constructor. The starter sends each request to the method whose mapping (@GetMapping, @PostMapping, ...) matches its method and path, fills the parameters from the request, and writes the return value as the body: JSON for an object, text for a String.
Use it for every class that answers HTTP. Keep the business logic in services and let the controller translate between HTTP and those services.
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;
}
@Service()
class BookService {
Future<Book> find(String isbn) async => Book(isbn: isbn, title: 'Dune');
}
@RestController()
@RequestMapping('/api/books')
class BookController {
BookController(this.books);
final BookService books;
// GET /api/books/978-0 answers the book as JSON.
@GetMapping('/{isbn}')
Future<Book> find(@PathVariable() String isbn) => books.find(isbn);
// A plain method without a mapping is not an endpoint.
String describe(Book book) => '${book.title} (${book.isbn})';
}
// An explicit bean name, for code that looks the bean up by name.
@RestController('adminBooks')
@RequestMapping('/admin/books')
class AdminBookController {
@GetMapping('/count')
int count() => 1;
}
@ResponseStatus on the class sets the status of every method that has none of its own:
// Every method of this controller answers 202 Accepted.
@RestController()
@RequestMapping('/api/jobs')
@ResponseStatus(HttpStatus.accepted)
class JobController {
@PostMapping()
void start() {}
// The method's own annotation wins.
@GetMapping('/health')
@ResponseStatus(HttpStatus.ok)
String health() => 'UP';
}
Parameters
| Name | Type | Default | Meaning |
|---|---|---|---|
name (positional) |
String? |
null |
The bean name. null gives the class name in lowerCamelCase (bookController). |
Rules
- Which methods are endpoints. A method is mapped when it carries one mapping annotation: @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @PatchMapping or @DeleteMapping. Two mapping annotations on one method stop the start. Methods with @ExceptionHandler answer the errors of this controller.
- A plain
@Controller()is mapped the same way. This server has no HTML views, so the return value is always the body.@RestControllersays the intent; pick either. - The class-level
@RequestMappinggives the path prefix of every method, and itsproduces,consumesandheaders(see @RequestMapping). - Class-level annotations apply to all methods, a method's own winning:
@ResponseStatus,@CrossOrigin(merged with the method's). - The controller is a singleton bean. One instance answers all requests, concurrently across
awaits, so keep request data in parameters and local variables, not in fields. - AOP applies. Methods are called on the bean as the container holds it, so advice on the controller (
@Cacheable, method validation,@PreAuthorizeof the security starter) runs. - The generator must see the class. It must be in the scanned code (
lib/and the directory ofmain), andbuild_runnermust run after you change it. The generator records each mapped method (its parameters, their annotations and the result type); the starter builds the routes from that record at startup. - Classes the methods take and return are described for JSON when they are in the same package. A class from another package needs its own introspection (
@Introspected()in that package, see JSON). - Mistakes stop the start, such as a path variable without a parameter (see Startup checks).
In Spring (Java)
@RestController
@RequestMapping("/api/books")
class BookController {
private final BookService books;
BookController(BookService books) { this.books = books; }
@GetMapping("/{isbn}")
Book find(@PathVariable String isbn) { return books.find(isbn); }
}
Differences that matter:
- In Spring a
@Controllerreturns a view name unless the method has@ResponseBody. Here there are no views:@Controllerand@RestControllerbehave the same. @RestControlleris a subclass ofControllerin Dart, where Spring uses meta-annotations.- The generator finds the methods at build time. A controller added at run time (a bean registered by code) is mapped only if its definition carries the method descriptions the generator writes.