@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:
- The media type is checked first, before the body is read, as Spring picks its converter first. A
Content-Typethat is not a media type at all is a 415, whatever the parameter type. - No
Content-Type. The body is thenapplication/octet-stream, as in Spring. For an object in aPOST,PUTorPATCHthat has a body, that is a 415. When there is no body (or the method is another one), it is a missing body. - Text encoding. The text is UTF-8, or Latin-1 when the
Content-Typesayscharset=iso-8859-1(orlatin1). Invalid UTF-8 bytes become U+FFFD. - Size. A body above
server.max-http-request-body-size(10 MB by default) is a 413 (PayloadTooLargeErrorException). AStream<Uint8List>parameter reads the body itself and is meant for large bodies. A body that sends nothing forserver.connection-timeout(60 s) is a 408 (see Timeouts). - One body per method. Two
@RequestBodyparameters stop the start. - The JSON classes. A class of the same package that a controller takes as a body is introspected automatically: its constructor and setters (and, with
@Valid(), the getters of the properties that have constraints). Immutable classes are created through their constructor (see JSON). JSON that does not fit the class (a missing required property, a wrong type) is a 400.
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()
@Valid()next to@RequestBody()checks the object's constraints with the application'sValidatorbean (thedefaultValidatorofspring_boot_dart, aBeanValidator). See Constraints.@Validated([Group, ...])does the same with validation groups. ListDefaultto keep the ordinary constraints.- A violation throws
MethodArgumentNotValidException: a 400 whose problem hasdetailInvalid request content.and anerrorslist. Each field error is{"field", "message", "rejectedValue"}; an error of the whole object is{"object", "message"}. Messages are resolved through the application'sMessageSource, somessages.propertiescan word them (see MessageSource); without one, the default messages are used. - The same works for JSON parts of an upload:
@RequestPart('book') @Valid() NewBook book(see Uploads). - A
nullbody is not validated. Use a non-nullable parameter when the body is required. - No validator, no check. With several
Validatorbeans and none of them@Primary, no validator is chosen and@Valid()bodies are not checked, without a warning. - To answer violations in another shape, write an
@ExceptionHandlerforMethodArgumentNotValidException(see @ExceptionHandler).
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:
@RequestBody(required = false)is a nullable parameter.- The violation answer is always a
ProblemDetailwith anerrorslist. Spring Boot's default is its/errorJSON unlessspring.mvc.problemdetails.enabled=true. - There are no
HttpMessageConverterbeans: JSON goes through theObjectMapper; text, bytes, streams and forms are fixed. - A
Stream<Uint8List>body has no counterpart in Spring MVC (it is Spring WebFlux'sFlux<DataBuffer>).