戻り値

コントローラーのメソッドの戻り値がレスポンスになります。その型がボディとメディアタイプを決め、@ResponseStatus や ResponseEntity がステータスとヘッダーを決めます。

使う理由

メソッドはバイトではなく Dart の値を返します。それを書くのはスターターです。オブジェクトは ObjectMapper を通して JSON に、String はテキストに、ストリームはサーバー送信イベントになります。そのため、ほとんどのメソッドは素の値を返し、ステータスやヘッダーが結果によって変わるときだけ ResponseEntity を返します。

例

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;

  // オブジェクト: 200 と JSON。
  @GetMapping('/{isbn}')
  Book? find(@PathVariable() String isbn) => books.find(isbn);

  // 本付きの 200、またはボディなしの 404。
  @GetMapping('/{isbn}/or-404')
  ResponseEntity<Book> findOr404(@PathVariable() String isbn) =>
      ResponseEntity.ofNullable(books.find(isbn));

  // Location ヘッダー付きの 201 Created。
  @PostMapping()
  ResponseEntity<Book> create(@RequestBody() Book book) {
    final saved = books.save(book);
    return ResponseEntity.created(Uri.parse('/api/books/${saved.isbn}'))
        .body(saved);
  }

  // ETag: If-None-Match: "3" を送るクライアントは 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/plain;charset=UTF-8。
  @GetMapping('/{isbn}/title')
  String title(@PathVariable() String isbn) => books.find(isbn)?.title ?? '';

  // バイト: application/octet-stream、またはマッピングの produces。
  @GetMapping.of(path: '/{isbn}/cover', produces: 'image/png')
  Uint8List cover(@PathVariable() String isbn) => Uint8List(0);

  // 何も返さない: 204 No Content。
  @DeleteMapping('/{isbn}')
  @ResponseStatus(HttpStatus.noContent)
  Future<void> delete(@PathVariable() String isbn) async {}

  // 廃止: メソッドが何を返しても、応答は 410 の problem になる。
  @GetMapping('/{isbn}/legacy')
  @ResponseStatus(HttpStatus.gone, reason: 'Use /api/books/{isbn}')
  void legacy(@PathVariable() String isbn) {}
}

null の結果(未知の ISBN に対する find)は、ボディなしの 200 です。404 にするには、ResponseEntity.ofNullable(...) を返すか、ResponseStatusException(HttpStatus.notFound) を投げます。

戻り値の型

戻り値の型 レスポンス
void、null、Future<void> ステータス(200、または @ResponseStatus)、ボディなし
オブジェクト、List、Map、num、bool ObjectMapper を通した JSON(application/json、またはマッピングの produces)。Accept がどちらも許さなければ 406
String UTF-8 のテキスト、text/plain;charset=UTF-8(またはマッピングの produces に ;charset=UTF-8 を付けたもの)
Uint8List バイト、application/octet-stream(またはマッピングの produces)
ResponseEntity<T> そのステータスとヘッダー。ボディは T 単独の場合と同じように書かれる
ProblemDetail problem のステータスでの application/problem+json(ProblemDetail を参照)
返された ErrorResponse(ResponseStatusException など) 投げた場合と同じ、そのステータス、ヘッダー、problem
Resource(FileSystemResource、ByteArrayResource) Content-Length、Range、Last-Modified 付きのダウンロード(ダウンロード を参照)
Stream<Uint8List>、Stream<List<int>>(そう宣言したもの) 届いた順のバイト、application/octet-stream(または produces)(StreamingResponseBody を参照)
StreamingResponseBody メソッドが自分で書くバイト(StreamingResponseBody を参照)
EventStream<T>、その他の Stream<T> サーバー送信イベント(text/event-stream)、または produces: 'application/x-ndjson' で NDJSON(サーバー送信イベント を参照)
SseEmitter どこからでも後から送るサーバー送信イベント(サーバー送信イベント を参照)

ルール:

メディアタイプ

@ResponseStatus

@ResponseStatus(value) は通常の応答のステータスを設定します。

名前 型 デフォルト 意味
value(位置引数) int 必須 ステータスコード。HttpStatus の定数(HttpStatus.created)または数値。
reason String? null reason があると、メソッドの結果は無視され、応答はこのステータスと、reason を detail とする ProblemDetail になる。

ResponseEntity

ResponseEntity<T> は、値としてのレスポンスです。ステータス、ヘッダー、省略可能なボディを持ちます。

コンストラクターまたはビルダー レスポンス
ResponseEntity(status, body: ..., headers: ...) 任意のステータス(100 から 999。それ以外は ArgumentError)、ボディ、HttpHeaders
ResponseEntity.ok(body) ボディ付きの 200。ボディを返すのと同じ
ResponseEntity.ofNullable(value)、ResponseEntity.of(value) 値付きの 200、または null ならボディなしの 404
ResponseEntity.status(code) 任意のステータスのビルダー
ResponseEntity.created(uri) Location 付きの 201 のビルダー
ResponseEntity.accepted() 202 のビルダー
ResponseEntity.noContent() 204 のビルダー
ResponseEntity.badRequest() 400 のビルダー
ResponseEntity.notFound() 404 のビルダー
ResponseEntity.unprocessableContent() 422 のビルダー
ResponseEntity.internalServerError() 500 のビルダー

ビルダー(ResponseEntityBuilder)は次のメソッドをチェーンできます。

メソッド 動作
header(name, values) ヘッダーに値を追加する: .header('Cache-Control', ['no-store'])
headers(httpHeaders) すべてのヘッダーをコピーする。すでに設定された名前は新しい値になる
location(uri) Location を設定する
contentType(mediaType) MediaType.imagePng のように Content-Type を設定する
eTag(tag) ETag を設定する。すでに引用符で囲まれていなければ囲む(W/"..." も含む)
lastModified(dateTime) Last-Modified を UTC の HTTP 日付として設定する
body<T>(value) ボディ付きでエンティティを完成させる
build<T>() ボディなしで完成させる。T を推論できない場合は build<Book>() と書く

エンティティは、statusCode(is2xxSuccessful などを持つ HttpStatusCode)、body、headers(読み取り専用)、hasBody、isSuccess を持ちます。

ルール:

条件付きリクエスト: ETag と Last-Modified

ステータス 200 で ETag または Last-Modified を持つ ResponseEntity は、Spring の HttpEntityMethodProcessor と同じように、再検証するブラウザーやキャッシュに GET と HEAD で応答します。

応答を自分で書くメソッドは、responseWriter Bean の checkNotModified(request, response) で同じチェックを実行できます。

すべての GET マッピングが HEAD に応答します。メソッドは GET と同じように実行され、ヘッダーと Content-Length が送られ、ボディは捨てられます。

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

重要な違い:

関連項目