Sub topic 6
Reading a Request Body with @RequestBody
This chapter shows how a Spring Boot controller reads data sent in the body of an HTTP request. It assumes you know basic Java (classes and records), have a running spring-boot-starter-web project, and understand HTTP methods, status codes, headers, and JSON syntax.
Why use a request body
Path variables and query parameters fit short values such as an id or a page number. They are poor at carrying structured data. A new book has a title, an author, and a page count. Putting these in the URL would be awkward and would expose them in logs and browser history. HTTP lets POST, PUT, and PATCH requests carry a body, and JSON is the usual format for it.
@RequestBody tells Spring to take the body of the request and bind it to a method parameter.
The flow of a request body
Spring does not read the body in your controller code. A message converter does it before your method runs.
Spring picks a converter by looking at the Content-Type header. With spring-boot-starter-web, Jackson is on the classpath and handles application/json.
A first handler
Define a class or record that matches the JSON shape. A record works well because the body is just data.
public record CreateBookRequest(
String title,
String author,
int pages) {}Then add the annotation to a controller parameter:
@PostMapping
public ResponseEntity<Book> create(@RequestBody CreateBookRequest request) {
Book saved = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}Jackson matches JSON property names to record component names. The body {"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183} produces a CreateBookRequest with those three values.
Send it with curl:
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}'The -H option matters. Without a JSON Content-Type, curl sends its default form type, and Spring rejects the request.
Returning 201 Created
A successful POST that creates a resource should answer 201 Created and include a Location header that points to the new resource. ResponseEntity lets you set both:
@PostMapping
public ResponseEntity<Book> create(@RequestBody CreateBookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}fromCurrentRequest() starts from the URL of the current request, such as /api/books. The builder appends /{id}, so the header becomes Location: http://localhost:8080/api/books/42.
Common errors
| Symptom | Likely cause |
|---|---|
| 415 Unsupported Media Type | The `Content-Type` header is missing or is not `application/json`. |
| 400 Bad Request, "JSON parse error" | The body is not valid JSON, for example a trailing comma or single quotes. |
| 400 Bad Request, "Required request body is missing" | The body is empty and `@RequestBody` is required (the default). |
| Fields arrive as `null` or `0` | A JSON property name does not match the component name, so Jackson skips it. |
A missing field does not cause an error by default. A missing title becomes null, and a missing pages becomes 0. Catching those cases is the job of validation, which a later chapter covers.
One body per request
A request has only one body, so a handler can have only one @RequestBody parameter. Combine it with other input styles freely. This handler reads an id from the path and the new values from the body:
@PutMapping("/{id}")
public Book update(@PathVariable Long id,
@RequestBody CreateBookRequest request) {
return service.update(id, request);
}Exercise
A client sends curl -X POST http://localhost:8080/api/books -d '{"title":"Dune","author":"Frank Herbert","pages":412}' to your @RequestBody endpoint and gets a 415 response. What is wrong, and how do you fix the command?
Show answer
The command has no Content-Type header, so curl sends application/x-www-form-urlencoded, which Jackson does not handle. Add -H "Content-Type: application/json" to the command.
Exercise
Why does a request with the body {"title":"Dune","autor":"Frank Herbert","pages":412} succeed, and what value does author have in the record?
Show answer
Spring Boot's Jackson setup ignores unknown properties, so autor is dropped without an error. No JSON property matches author, so it is null.