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
ObjectMapperofspring_core_dart; - validation of request bodies with
@Valid(); - errors as standard
ProblemDetailbodies (RFC 9457,application/problem+json); - server-sent events and NDJSON from a
Stream; - file uploads (
multipart/form-data) and downloads withRangesupport; - 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
# 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:
// 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);
# 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).
Running it
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:
INFO Web server started on port 8080 (http)
Then:
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).
Ctrl+Cstops the server gracefully only when the application closes its context on signals: setspring.main.register-shutdown-hook=true. It isfalseby default here, unlike in Spring Boot, because listening for signals keeps a Dart program alive (see Shutdown).- 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:
MockMvcin memory, or a real server on a free port.
Controllers:
- Controllers: how a request reaches a method.
- @RestController: the class that answers requests.
- @RequestMapping and @GetMapping: paths, methods and the
produces,consumesandheadersconditions. - @PathVariable: values from the path.
- @RequestParam: query parameters and form fields.
- @RequestBody: the JSON body, validated with
@Valid(). - Headers, cookies and the request:
@RequestHeader,@CookieValueand the parameters without annotation. - Results: what a method returns, and the response it becomes.
- Startup checks: the mistakes found when the application starts.
Errors:
- Errors: the default answers, the status of each error, and the logs.
- ProblemDetail: the RFC 9457 error body, and the exceptions that carry one.
- @ExceptionHandler: turn an exception into your own answer.
- @ControllerAdvice: exception handlers for every controller.
- HandlerExceptionResolver: how a library maps its own exceptions.
Streams and files:
- Server-sent events:
EventStream,Stream<T>andSseEmitter. - Uploads:
multipart/form-data,@RequestPartandMultipartFile. - Downloads:
Resourceresults withRangeandLast-Modified. - StreamingResponseBody: bodies written on the fly, and byte streams.
Web features:
- Static resources: files of
lib/resources/static/or of a directory, single-page apps. - Sessions:
HttpSession, its cookie and its limits. - Filters:
WebFilterbeans around every request. - WebMvcConfigurer: interceptors, argument resolvers, CORS mappings and resource handlers.
- CORS:
@CrossOrigin, global rules and thecorsConfigurationSourcebean.
The server:
- The server:
server.*, the start and stop, the factory. - SSL: HTTPS with PEM files, client certificates.
- Compression: gzip for clients that accept it.
- Timeouts:
server.connection-timeoutandserver.request-timeout. - Overload:
server.max-concurrent-requestsandserver.max-connections, a 503 withRetry-Afterat once. - A pool of isolates:
server.isolates.count, several isolates on one port, and what that changes. - Scaling the isolates:
IsolateScalerandserver.isolates.scaling=auto. - Requests per second: the debug feature
qps. - Behind a reverse proxy:
ForwardedandX-Forwarded-*headers. - Shutdown: graceful and immediate shutdown.
- Handler mappings: the dispatcher and your own
HandlerMappingbeans. - WebSocket: endpoints of
spring_boot_starter_websocketon the same port.
Reference:
- All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring Boot.
In Spring (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_runnerafter you change annotations. @SpringBootApplication()goes on themainfunction, not on a class.- Errors are always
ProblemDetailbodies. There is no/errorendpoint and noErrorController. - Whether a parameter is required comes from the Dart parameter (nullable or with a default), not from
requiredanddefaultValueattributes. - The full list is on Differences from Spring.