
# @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](../../spring-core-dart/beans/component.md), 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

```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;
}

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

```dart
// 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](request-mapping.md). Two mapping annotations on one method stop the start. Methods with [@ExceptionHandler](../errors/exception-handler.md) 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. `@RestController` says the intent; pick either.
- **The class-level `@RequestMapping`** gives the path prefix of every method, and its `produces`, `consumes` and `headers` (see [@RequestMapping](request-mapping.md)).
- **Class-level annotations apply to all methods**, a method's own winning: `@ResponseStatus`, [`@CrossOrigin`](../cors.md) (merged with the method's).
- **The controller is a singleton bean.** One instance answers all requests, concurrently across `await`s, 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, `@PreAuthorize` of the security starter) runs.
- **The generator must see the class.** It must be in the scanned code (`lib/` and the directory of `main`), and `build_runner` must 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](../../spring-core-dart/json/index.md)).
- **Mistakes stop the start**, such as a path variable without a parameter (see [Startup checks](startup-checks.md)).

## In Spring (Java)

```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 `@Controller` returns a view name unless the method has `@ResponseBody`. Here there are no views: `@Controller` and `@RestController` behave the same.
- `@RestController` is a subclass of `Controller` in 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.

## See also

- [@RequestMapping and @GetMapping](request-mapping.md)
- [Results](results.md)
- [@ExceptionHandler](../errors/exception-handler.md)
- [@Controller in spring_core_dart](../../spring-core-dart/beans/controller.md)
- [@ComponentScan](../../spring-core-dart/beans/component-scan.md)
