@RequestBody

@RequestBody() binds a controller parameter to the body of the request. An object is read from JSON; a String, bytes, a byte stream and a form Map are read their own way. With @Valid(), the object is validated.

Why

POST, PUT and PATCH send their data in the body, usually as JSON. The annotation reads the body, decodes it into the parameter's type through the application's ObjectMapper, checks its constraints, and answers the client's mistakes for you: a 415 for a body that is not JSON, a 400 for JSON that does not parse or does not fit, a 400 listing the fields that break a constraint.

Example

import 'dart:typed_data';

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

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

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

  @NotBlank()
  final String title;

  @PositiveOrZero()
  final int stock;
}

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

  final String isbn;
  final String title;
}

abstract final class OnImport {}

@RestController()
@RequestMapping('/api/books')
class BookController {
  // POST /api/books with {"isbn": "978-0", "title": "Dune"}.
  // An empty title is a 400 that lists the field.
  @PostMapping()
  @ResponseStatus(HttpStatus.created)
  Book create(@RequestBody() @Valid() NewBook book) =>
      Book(isbn: book.isbn, title: book.title);

  // Validated with the Default group and the OnImport group.
  @PostMapping('/import')
  Book importBook(@RequestBody() @Validated([Default, OnImport]) NewBook book) =>
      Book(isbn: book.isbn, title: book.title);

  // The body is optional: without one, book is null.
  @PatchMapping('/{isbn}/touch')
  String touch(@PathVariable() String isbn, @RequestBody() Book? book) =>
      book == null ? 'touched $isbn' : 'replaced $isbn';

  // A JSON object of any shape.
  @PatchMapping('/{isbn}')
  Map<String, Object?> update(
    @PathVariable() String isbn,
    @RequestBody() Map<String, Object?> changes,
  ) => changes;

  // A list of objects.
  @PostMapping('/batch')
  int batch(@RequestBody() List<NewBook> books) => books.length;

  // The body as text, whatever its Content-Type.
  @PostMapping('/notes')
  int note(@RequestBody() String text) => text.length;

  // The raw bytes.
  @PostMapping('/{isbn}/cover')
  int cover(@PathVariable() String isbn, @RequestBody() Uint8List bytes) =>
      bytes.length;

  // A big upload, read as it arrives and never held whole in memory.
  @PostMapping('/backup')
  Future<int> backup(@RequestBody() Stream<Uint8List> body) async {
    var total = 0;
    await for (final chunk in body) {
      total += chunk.length;
    }
    return total;
  }

  // A form body: title=Dune&isbn=978-0 with
  // Content-Type application/x-www-form-urlencoded.
  @PostMapping('/form')
  Map<String, String> form(@RequestBody() Map<String, String> fields) => fields;
}

A failed validation:

POST /api/books {"isbn": "978-0", "title": ""}
→ 400 application/problem+json
{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid request content.",
 "instance":"/api/books",
 "errors":[{"field":"title","message":"must not be blank","rejectedValue":""}]}

Parameters

@RequestBody() has no parameters.

How the body is read

The parameter's type decides:

Type Read as Content-Type
a class, List, Map, ... JSON through the ObjectMapper application/json, application/*+json or */*; anything else is a 415
Map<String, String> (or another Map) with a form the form fields, converted like @RequestParam values application/x-www-form-urlencoded
String the text any
Uint8List, List<int> the raw bytes any
Stream<Uint8List> the body as it arrives, unread any

Rules:

Required or optional

The body is empty, and the parameter is Result
nullable: @RequestBody() Book? book null
with a default value left out of the call: the Dart default
anything else 400 Failed to read request (HttpMessageNotReadableException)

Malformed JSON and JSON of the wrong shape give the same 400. Its detail stays vague on purpose; the reason is in the exception's message (JSON parse error: ..., Required request body is missing: BookController.create), which an @ExceptionHandler can read. It is never sent to the client.

Validation: @Valid() and @Validated()

In Spring (Java)

@PostMapping("/api/books")
@ResponseStatus(HttpStatus.CREATED)
Book create(@RequestBody @Valid NewBook book) { ... }

@PatchMapping("/api/books/{isbn}/touch")
Book touch(@PathVariable String isbn,
    @RequestBody(required = false) Book book) { ... }

Differences that matter:

See also