
# spring_boot_starter_web

`spring_boot_starter_web` is the HTTP server of Spring for Dart, the Dart port of Spring Boot's `spring-boot-starter-web` and of Spring MVC. You write controller classes whose methods carry annotations such as `@GetMapping('/books/{isbn}')`. The starter sends each request to the right method, fills its parameters from the path, the query, the headers and the body, and turns what it returns into the response.

## Why

A REST API needs the same work around every endpoint: parse the path, read the query, decode JSON, validate it, answer errors in one shape, write JSON back. Written by hand on `dart:io`'s `HttpServer`, this code grows with every endpoint. The starter does it for you:

- JSON in and out, through the `ObjectMapper` of `spring_core_dart`;
- validation of request bodies with `@Valid()`;
- errors as standard `ProblemDetail` bodies (RFC 9457, `application/problem+json`);
- server-sent events and NDJSON from a `Stream`;
- file uploads (`multipart/form-data`) and downloads with `Range` support;
- static files, such as a built Flutter web app, with caching headers;
- filters, interceptors, CORS and sessions.

Use it for a backend in Dart, or for a local server inside a Flutter app on mobile or desktop (a local API, a companion server). The server is `dart:io`'s `HttpServer`, behind a factory you can replace. The generator writes all routing code at build time, so there is no reflection at run time.

## Setup

```yaml
# pubspec.yaml
dependencies:
  spring_boot_starter_web: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # required: it describes the controllers
  spring_boot_starter_test: ^0.9.0     # MockMvc and springBootTest, for tests
  test: ^1.33.0
```

One import is enough. `package:spring_boot_starter_web/spring_boot_starter_web.dart` also exports `spring_boot_dart`, `spring_web_dart` (the annotations, `ResponseEntity`, `ProblemDetail`, the server request and response) and `spring_boot_starter_logging`. As with every Spring Boot starter, it is the only dependency the application needs.

## Example

A complete application in one file:

```dart
// bin/main.dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

import 'spring_gen/main.spring.dart';

class Book {
  const Book({required this.isbn, required this.title});

  final String isbn;
  final String title;
}

class NewBook {
  const NewBook({required this.isbn, required this.title});

  @NotBlank()
  @Size(min: 4, max: 13)
  final String isbn;

  @NotBlank()
  final String title;
}

@Service()
class BookService {
  final _books = <String, Book>{
    '978-0': const Book(isbn: '978-0', title: 'Dune'),
  };

  Book? find(String isbn) => _books[isbn];

  Book add(NewBook book) =>
      _books[book.isbn] = Book(isbn: book.isbn, title: book.title);
}

@RestController()
@RequestMapping('/api/books')
class BookController {
  BookController(this.books);

  final BookService books;

  // GET /api/books/978-0 → 200 {"isbn":"978-0","title":"Dune"}
  @GetMapping('/{isbn}')
  Book find(@PathVariable() String isbn) =>
      books.find(isbn) ??
      (throw ResponseStatusException(HttpStatus.notFound, 'No book $isbn'));

  // POST /api/books → 201 with a Location header; an invalid body is a 400.
  @PostMapping()
  ResponseEntity<Book> create(@RequestBody() @Valid() NewBook book) {
    final added = books.add(book);
    return ResponseEntity.created(Uri.parse('/api/books/${added.isbn}'))
        .body(added);
  }
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
```

```properties
# lib/resources/application.properties
server.port=8080
spring.main.register-shutdown-hook=true
```

`Book` and `NewBook` need no annotation for JSON. The generator describes the classes a controller takes and returns when they are in the same package, each for what the controller does with it: a class that is only returned gets its getters, a `@RequestBody` class its constructor and setters (and, with `@Valid()`, the getters of the properties that have constraints). A value the build cannot see, such as an `Object` written as JSON, needs `@Introspected()` on its class (see [JSON](../spring-core-dart/json/index.md)).

## Running it

```bash
dart run build_runner build   # writes bin/spring_gen/main.spring.dart
dart run bin/main.dart
```

Run `build_runner` again after you add or change annotations. When the context is ready, the server starts and logs, under the logger `spring.web.server`:

```text
INFO  Web server started on port 8080 (http)
```

Then:

```bash
curl localhost:8080/api/books/978-0
# {"isbn":"978-0","title":"Dune"}

curl -i localhost:8080/api/books/123
# HTTP/1.1 404 Not Found
# content-type: application/problem+json
# {"type":"about:blank","title":"Not Found","status":404,"detail":"No book 123","instance":"/api/books/123"}
```

What starts:

- **Nothing to switch on.** There is no `@EnableWebMvc`. Every `@RestController` (and every plain `@Controller`) of the scanned code is mapped, and the server starts once the context is ready.
- **The controllers are checked first.** A mistake in a mapping stops the start with a list of every problem (see [Startup checks](controllers/startup-checks.md)).
- **`Ctrl+C` stops the server gracefully** only when the application closes its context on signals: set `spring.main.register-shutdown-hook=true`. It is `false` by default here, unlike in Spring Boot, because listening for signals keeps a Dart program alive (see [Shutdown](server/shutdown.md)).
- **A port in use** fails the start with a report that names the port and the property to change.

## What is inside

Getting started:

- [Testing](testing.md): `MockMvc` in memory, or a real server on a free port.

Controllers:

- [Controllers](controllers/index.md): how a request reaches a method.
- [@RestController](controllers/rest-controller.md): the class that answers requests.
- [@RequestMapping and @GetMapping](controllers/request-mapping.md): paths, methods and the `produces`, `consumes` and `headers` conditions.
- [@PathVariable](controllers/path-variable.md): values from the path.
- [@RequestParam](controllers/request-param.md): query parameters and form fields.
- [@RequestBody](controllers/request-body.md): the JSON body, validated with `@Valid()`.
- [Headers, cookies and the request](controllers/headers-and-cookies.md): `@RequestHeader`, `@CookieValue` and the parameters without annotation.
- [Results](controllers/results.md): what a method returns, and the response it becomes.
- [Startup checks](controllers/startup-checks.md): the mistakes found when the application starts.

Errors:

- [Errors](errors/index.md): the default answers, the status of each error, and the logs.
- [ProblemDetail](errors/problem-detail.md): the RFC 9457 error body, and the exceptions that carry one.
- [@ExceptionHandler](errors/exception-handler.md): turn an exception into your own answer.
- [@ControllerAdvice](errors/controller-advice.md): exception handlers for every controller.
- [HandlerExceptionResolver](errors/handler-exception-resolver.md): how a library maps its own exceptions.

Streams and files:

- [Server-sent events](streaming/sse.md): `EventStream`, `Stream<T>` and `SseEmitter`.
- [Uploads](streaming/uploads.md): `multipart/form-data`, `@RequestPart` and `MultipartFile`.
- [Downloads](streaming/downloads.md): `Resource` results with `Range` and `Last-Modified`.
- [StreamingResponseBody](streaming/streaming-response-body.md): bodies written on the fly, and byte streams.

Web features:

- [Static resources](static-resources.md): files of `lib/resources/static/` or of a directory, single-page apps.
- [Sessions](sessions.md): `HttpSession`, its cookie and its limits.
- [Filters](filters.md): `WebFilter` beans around every request.
- [WebMvcConfigurer](web-mvc-configurer.md): interceptors, argument resolvers, CORS mappings and resource handlers.
- [CORS](cors.md): `@CrossOrigin`, global rules and the `corsConfigurationSource` bean.

The server:

- [The server](server/index.md): `server.*`, the start and stop, the factory.
- [SSL](server/ssl.md): HTTPS with PEM files, client certificates.
- [Compression](server/compression.md): gzip for clients that accept it.
- [Timeouts](server/timeouts.md): `server.connection-timeout` and `server.request-timeout`.
- [Overload](server/overload.md): `server.max-concurrent-requests` and `server.max-connections`, a 503 with `Retry-After` at once.
- [A pool of isolates](server/isolates.md): `server.isolates.count`, several isolates on one port, and what that changes.
- [Scaling the isolates](server/scaling.md): `IsolateScaler` and `server.isolates.scaling=auto`.
- [Requests per second](server/qps.md): the debug feature `qps`.
- [Behind a reverse proxy](server/reverse-proxy.md): `Forwarded` and `X-Forwarded-*` headers.
- [Shutdown](server/shutdown.md): graceful and immediate shutdown.
- [Handler mappings](server/handler-mappings.md): the dispatcher and your own `HandlerMapping` beans.
- [WebSocket](server/websocket.md): endpoints of `spring_boot_starter_websocket` on the same port.

Reference:

- [All properties](properties.md): every key of the starter.
- [Differences from Spring](differences.md): what works differently than in Spring Boot.

## In Spring (Java)

```java
@RestController
@RequestMapping("/api/books")
class BookController {
  @GetMapping("/{isbn}")
  Book find(@PathVariable String isbn) { ... }

  @PostMapping
  ResponseEntity<Book> create(@RequestBody @Valid NewBook book) { ... }
}

@SpringBootApplication
class ShopApplication {
  public static void main(String[] args) {
    SpringApplication.run(ShopApplication.class, args);
  }
}
```

Differences that matter:

- The routes are written by the generator at build time. Run `build_runner` after you change annotations.
- `@SpringBootApplication()` goes on the `main` function, not on a class.
- Errors are always `ProblemDetail` bodies. There is no `/error` endpoint and no `ErrorController`.
- Whether a parameter is required comes from the Dart parameter (nullable or with a default), not from `required` and `defaultValue` attributes.
- The full list is on [Differences from Spring](differences.md).

## See also

- [spring_core_dart](../spring-core-dart/index.md)
- [Validation](../spring-core-dart/validation/index.md)
- [JSON](../spring-core-dart/json/index.md)
- [What a build contains](optimizations.md)
