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:

The media type

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

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:

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:

A method that writes its answer itself can run the same check with the responseWriter bean's checkNotModified(request, response).

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:

See also