Sub topic 7
Accepting JSON with @RequestBody
This chapter assumes you know Java records, basic HTTP (methods, headers, status codes), and how to write a @RestController with @PostMapping. It also assumes you have a Spring Boot web project, where Jackson is already on the classpath through spring-boot-starter-web.
What @RequestBody does
A POST or PUT request usually carries data in its body. @RequestBody tells Spring MVC to read that body and convert it into a Java object. The conversion is done by an HttpMessageConverter. For JSON, Spring Boot configures a Jackson converter automatically.
The conversion depends on the Content-Type request header. Spring selects a converter that can read that media type and produce your parameter type.
A request DTO and the controller method
Use a dedicated request type instead of your domain entity. A record works well because it is immutable and Jackson can build it through its canonical constructor.
public record CreateBookRequest(String title, String author) {}
public record BookResponse(long id, String title, String author) {}The controller method takes the DTO as a parameter marked with @RequestBody:
@PostMapping
public ResponseEntity<BookResponse> create(@RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}A client can now send this request:
POST /api/books HTTP/1.1
Content-Type: application/json
{"title": "Dune", "author": "Frank Herbert"}Spring creates new CreateBookRequest("Dune", "Frank Herbert") and calls create. The method returns 201 Created with a Location header.
Adding validation
@RequestBody only converts the data. It does not check it. Add Bean Validation constraints to the record and put @Valid on the parameter. This needs the spring-boot-starter-validation dependency.
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {}@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
// same body as before
}If validation fails, Spring throws MethodArgumentNotValidException before your method runs. The default response is 400. Set spring.mvc.problemdetails.enabled=true to get a ProblemDetail body instead.
Common errors
| Symptom | Likely cause |
|---|---|
| 415 Unsupported Media Type | The client did not send `Content-Type: application/json`. |
| 400 with a "JSON parse error" or "Required request body is missing" message | The JSON is malformed, has a wrong value type (such as a string where a number is expected), or the body is empty. |
| Fields are `null` after binding | The JSON property names do not match the record component names, which are case-sensitive. |
| Constraints are ignored | `@Valid` is missing from the parameter, or the validation starter is not on the classpath. |
Unknown properties in the JSON are ignored by default in Spring Boot, because it disables Jackson's FAIL_ON_UNKNOWN_PROPERTIES. A typo in a field name therefore does not cause an error. It produces a null field, which is why validation matters.
Things to remember
- Only one parameter per method can be annotated with
@RequestBody, because the body stream is read once. @RequestBodyis required by default. An empty body returns 400. Use@RequestBody(required = false)to accept it, and handlenull.@RestControlleralready applies@ResponseBodyto return values. It does not replace@RequestBodyon parameters.
Exercise
A client sends POST /api/books with the body {"title": "Dune", "writer": "Frank Herbert"} and the correct Content-Type. The DTO is CreateBookRequest(@NotBlank String title, @NotBlank String author), and the parameter has @Valid @RequestBody. What status code does the client get, and why?
Show answer
400 Bad Request. Jackson ignores the unknown property "writer", so author is null. The @NotBlank constraint on author then fails, and Spring throws MethodArgumentNotValidException before the controller method runs.
Exercise
Which HTTP request header decides whether Spring will use the Jackson converter for a request body, and what status code is returned when no converter matches?
Show answer
The Content-Type header. If no converter can read that media type, Spring returns 415 Unsupported Media Type.