Results
The return value of a controller method becomes the response. Its type decides the body and the media type; @ResponseStatus or a ResponseEntity decides the status and the headers.
Why
A method returns a Dart value, not bytes. The starter writes it: an object as JSON through the ObjectMapper, a String as text, a stream as server-sent events. So most methods return the plain value, and a ResponseEntity only when the status or the headers depend on what happened.
Example
import 'dart:typed_data';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
class Book {
const Book({required this.isbn, required this.title, required this.version});
final String isbn;
final String title;
final int version;
}
@Service()
class BookService {
final _books = {'978-0': const Book(isbn: '978-0', title: 'Dune', version: 3)};
Book? find(String isbn) => _books[isbn];
Book save(Book book) => _books[book.isbn] = book;
}
@RestController()
@RequestMapping('/api/books')
class BookController {
BookController(this.books);
final BookService books;
// An object: 200 and JSON.
@GetMapping('/{isbn}')
Book? find(@PathVariable() String isbn) => books.find(isbn);
// 200 with the book, or 404 without a body.
@GetMapping('/{isbn}/or-404')
ResponseEntity<Book> findOr404(@PathVariable() String isbn) =>
ResponseEntity.ofNullable(books.find(isbn));
// 201 Created with a Location header.
@PostMapping()
ResponseEntity<Book> create(@RequestBody() Book book) {
final saved = books.save(book);
return ResponseEntity.created(Uri.parse('/api/books/${saved.isbn}'))
.body(saved);
}
// An ETag: a client that sends If-None-Match: "3" gets a 304.
@GetMapping('/{isbn}/cached')
ResponseEntity<Book> cached(@PathVariable() String isbn) {
final book = books.find(isbn);
if (book == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.status(HttpStatus.ok)
.eTag('${book.version}')
.header('Cache-Control', ['max-age=60'])
.body(book);
}
// Text: text/plain;charset=UTF-8.
@GetMapping('/{isbn}/title')
String title(@PathVariable() String isbn) => books.find(isbn)?.title ?? '';
// Bytes: application/octet-stream, or the mapping's produces.
@GetMapping.of(path: '/{isbn}/cover', produces: 'image/png')
Uint8List cover(@PathVariable() String isbn) => Uint8List(0);
// Nothing: 204 No Content.
@DeleteMapping('/{isbn}')
@ResponseStatus(HttpStatus.noContent)
Future<void> delete(@PathVariable() String isbn) async {}
// Retired: whatever the method returns, the answer is a 410 problem.
@GetMapping('/{isbn}/legacy')
@ResponseStatus(HttpStatus.gone, reason: 'Use /api/books/{isbn}')
void legacy(@PathVariable() String isbn) {}
}
A null result (find for an unknown ISBN) is a 200 without a body. Return ResponseEntity.ofNullable(...), or throw a ResponseStatusException(HttpStatus.notFound), for a 404.
Return types
| Return type | Response |
|---|---|
void, null, Future<void> |
the status (200, or @ResponseStatus), no body |
an object, List, Map, num, bool |
JSON through the ObjectMapper (application/json, or the mapping's produces); a 406 when Accept allows neither |
String |
the text as UTF-8, text/plain;charset=UTF-8 (or the mapping's produces, with ;charset=UTF-8 added) |
Uint8List |
the bytes, application/octet-stream (or the mapping's produces) |
ResponseEntity<T> |
its status and headers, and its body written as T would be alone |
ProblemDetail |
application/problem+json with the problem's status (see ProblemDetail) |
an ErrorResponse (such as a ResponseStatusException), returned |
its status, headers and problem, as when thrown |
Resource (FileSystemResource, ByteArrayResource) |
a download with Content-Length, Range and Last-Modified (see Downloads) |
Stream<Uint8List>, Stream<List<int>> (declared so) |
the bytes as they come, application/octet-stream (or produces) (see StreamingResponseBody) |
StreamingResponseBody |
bytes the method writes itself (see StreamingResponseBody) |
EventStream<T>, any other Stream<T> |
server-sent events (text/event-stream), or NDJSON with produces: 'application/x-ndjson' (see Server-sent events) |
SseEmitter |
server-sent events sent from anywhere, later (see Server-sent events) |
Rules:
- A
Futureof any of these is awaited. AFutureof a stream is not allowed and stops the start: return the stream itself. - The byte stream case depends on the declared type. Only a method declared to return
Stream<Uint8List>orStream<List<int>>writes raw bytes. Any other stream, even one that happens to carry bytes, is written as events. - JSON classes. A class of the same package that a method returns is introspected automatically (its getters). A value the build cannot see (a result typed
Objectholding a class of another package) fails when it is written, with a message that asks for@Introspected(); that is a 500. Properties are written in alphabetical order by default (see JSON). - An error while writing after the response was committed (a stream that fails half-way) cannot become an error answer: the connection is dropped without finishing the response, so the client sees a broken response, not a short one that looks complete.
The media type
- With
produceson the mapping, the response gets the first of its media types that the request'sAcceptallows, in the order of the client'sqvalues. A wildcard type inproduces(text/*) writes the default type of the result (text/plainfor aString). - Without
produces, an object isapplication/json, aStringtext/plain, bytesapplication/octet-stream. - An object whose types
Acceptdoes not allow is a 406 (HttpMediaTypeNotAcceptableException). AStringorUint8Listfalls back to its default type instead. - A
Content-Typethe method set (on aResponseEntitywith.contentType(...), or on the response) is kept.
@ResponseStatus
@ResponseStatus(value) sets the status of a normal answer.
| Name | Type | Default | Meaning |
|---|---|---|---|
value (positional) |
int |
required | The status code: an HttpStatus constant (HttpStatus.created) or a number. |
reason |
String? |
null |
With a reason, the method's result is ignored and the answer is a ProblemDetail with this status and the reason as its detail. |
- It applies to a plain result (also
nullandvoid), aProblemDetail(whose status it replaces), bytes, aResource, a byte stream and aStreamingResponseBody. - A
ResponseEntitykeeps its own status. Event streams start with 200 (use aResponseEntityof the stream for another status). - On the controller class, it applies to every method without its own.
- On an @ExceptionHandler method, it sets the status of the error answer.
- It is not read on exception classes: throw a
ResponseStatusExceptioninstead.
ResponseEntity
A ResponseEntity<T> is a response as a value: a status, headers and an optional body.
| Constructor or builder | Response |
|---|---|
ResponseEntity(status, body: ..., headers: ...) |
any status (100 to 999, else an ArgumentError), body and HttpHeaders |
ResponseEntity.ok(body) |
200 with the body, the same as returning the body |
ResponseEntity.ofNullable(value), ResponseEntity.of(value) |
200 with the value, or 404 without a body when it is null |
ResponseEntity.status(code) |
a builder for any status |
ResponseEntity.created(uri) |
a builder for 201 with Location |
ResponseEntity.accepted() |
a builder for 202 |
ResponseEntity.noContent() |
a builder for 204 |
ResponseEntity.badRequest() |
a builder for 400 |
ResponseEntity.notFound() |
a builder for 404 |
ResponseEntity.unprocessableContent() |
a builder for 422 |
ResponseEntity.internalServerError() |
a builder for 500 |
The builder (ResponseEntityBuilder) chains:
| Method | Does |
|---|---|
header(name, values) |
adds values to a header: .header('Cache-Control', ['no-store']) |
headers(httpHeaders) |
copies every header; a name already set gets the new values |
location(uri) |
sets Location |
contentType(mediaType) |
sets Content-Type, such as MediaType.imagePng |
eTag(tag) |
sets ETag, quoted unless it already is (W/"..." included) |
lastModified(dateTime) |
sets Last-Modified, as an HTTP date in UTC |
body<T>(value) |
finishes the entity with a body |
build<T>() |
finishes it without a body; write build<Book>() when T cannot be inferred |
An entity has statusCode (an HttpStatusCode with is2xxSuccessful and the like), body, headers (read-only), hasBody and isSuccess.
Rules:
- Headers of the entity replace those of the same name on the response, except
Vary: its names join those already there (the CORS ones), as in Spring. - The body is written the way it would be alone: an object as JSON, a
Resourceas a download, anEventStream, aStreamor anSseEmitteras events, with the entity's status and headers. ResponseEntity<void>withbuild()answers the status and headers only.
Conditional requests: ETag and Last-Modified
A ResponseEntity with status 200 and an ETag or Last-Modified answers a browser or a cache that revalidates, for GET and HEAD, as Spring's HttpEntityMethodProcessor does:
If-None-Matchwith its tag is a304 Not Modifiedwithout a body. Tags are compared weakly (W/is ignored), and a list or several headers are read.If-None-Match: *is not a match for aGET, as in Spring.- Without
If-None-Match,If-Modified-Sinceat or afterLast-Modified(in whole seconds) is a 304. If-Unmodified-SincebeforeLast-Modifiedis a412 Precondition Failed.- The 304 keeps the other headers (
Cache-Control,Vary, the CORS ones). - Not checked:
If-MatchandIf-Unmodified-Sinceof other methods (the method checks them itself), and bodies written as they come (event streams, byte streams,StreamingResponseBody).
A method that writes its answer itself can run the same check with the responseWriter bean's checkNotModified(request, response).
HEAD
Every GET mapping answers HEAD: the method runs as for a GET, the headers and Content-Length are sent, the body is dropped.
In Spring (Java)
@PostMapping("/api/books")
ResponseEntity<Book> create(@RequestBody Book book) {
Book saved = books.save(book);
return ResponseEntity.created(URI.create("/api/books/" + saved.isbn())).body(saved);
}
@GetMapping("/api/books/{isbn}")
ResponseEntity<Book> find(@PathVariable String isbn) {
return ResponseEntity.of(books.findById(isbn));
}
Differences that matter:
ResponseEntity.oftakes a nullable value instead of anOptional.@ResponseStatuson an exception class is not read; throw aResponseStatusExceptionor implementErrorResponse.- A declared
Stream<Uint8List>is raw bytes (Spring WebFlux'sFlux<DataBuffer>); there is noResponseBodyEmitter, aStream<T>covers server-sent events and NDJSON. - A
Futureof a stream is refused at startup. - There are no views and no
ModelAndView.