@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

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:

See also