Sub topic 6
Reading a request body with @RequestBody
This chapter assumes you can write a Spring Boot controller that runs, and that you know HTTP methods, status codes, headers, and JSON syntax. It also assumes you have read the earlier chapters on path variables and query parameters. Here you learn how a controller method receives the body of a request, what Spring does before your method runs, and which failures you can expect.
What the request body is
A request body is the data that follows the headers of an HTTP request. POST, PUT, and PATCH requests usually carry one. The body suits data that is large, nested, or structured, such as the details of a new book. A path or query string handles that kind of data poorly.
The body is raw bytes. Two headers tell the server how to read it:
Content-Typedescribes the format of the body, for exampleapplication/json.Content-Lengthor chunked transfer encoding tells the server where the body ends.
Spring does not guess the format. It reads Content-Type and picks a converter that can turn those bytes into the Java type you declared.
Declaring a body parameter
Annotate one method parameter with @RequestBody. The parameter's type tells Spring what to build. This example uses two records. Each goes in its own file.
public record Book(Long id, String title, String author, int pages) {}public record CreateBookRequest(String title, String author, int pages) {}The controller stores books in memory so you can run it as shown. The service layer is left out to keep the focus on the body.
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final Map<Long, Book> books = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
@PostMapping
public ResponseEntity<Book> create(@RequestBody CreateBookRequest request) {
Book saved = new Book(ids.incrementAndGet(),
request.title(), request.author(), request.pages());
books.put(saved.id(), saved);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}
}Send a request with curl:
curl -i -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 response looks like this:
HTTP/1.1 201 Created
Location: http://localhost:8080/api/books/1
Content-Type: application/json
{"id":1,"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}Two details in the handler are worth noting:
ResponseEntity.created(location)sets the status to201 Createdand adds aLocationheader. This is the conventional answer to aPOSTthat creates a resource.ResponseEntitylets you control the status and headers instead of accepting the default200 OK.ServletUriComponentsBuilder.fromCurrentRequest()starts from the URL of the current request,/api/books. Appending/{id}gives the URL of the new resource without hard-coding the host or port.
What happens before your method runs
Your method is called only after Spring has read and converted the body. Knowing the steps helps you read error messages.
Spring MVC hands the work to a list of HttpMessageConverter objects. Each converter declares which media types and Java types it supports. With spring-boot-starter-web, the list includes:
- A Jackson converter for
application/json. - A converter for
Stringthat accepts any content type. - A converter for
byte[], which delivers the raw bytes. - Form-related converters for
application/x-www-form-urlencoded.
The first converter that supports both the Content-Type and your parameter type reads the body. The next chapter covers how Jackson maps JSON fields to record components. This chapter stays on the request level.
Other parameter types
JSON-to-record is the common case, but the parameter type decides what you get:
@PostMapping("/raw")
public String raw(@RequestBody String body) {
return "Received " + body.length() + " characters";
}
@PostMapping("/bulk")
public List<Book> createMany(@RequestBody List<CreateBookRequest> requests) {
// build and return the saved books
return List.of();
}
@PostMapping("/loose")
public Map<String, Object> loose(@RequestBody Map<String, Object> body) {
return body;
}Keep these points in mind:
Stringandbyte[]give you the unparsed body. This helps with signed webhooks, where you must verify a signature over the exact bytes you received.List<CreateBookRequest>works because Spring keeps the generic type of the parameter. The body must then be a JSON array.Map<String, Object>accepts any JSON object. It avoids writing a class, but you lose type checking and documentation. Use it only for truly free-form data.
Required and optional bodies
A @RequestBody parameter is required by default. If the request has no body, Spring answers 400 Bad Request before calling your method. To accept a missing body, set required = false:
@PostMapping("/optional")
public String optional(@RequestBody(required = false) CreateBookRequest request) {
return request == null ? "No body sent" : "Got " + request.title();
}With required = false, an empty body gives null, so you must check for it. A body that is present but malformed is still an error.
Combining a body with other inputs
A method can read all three kinds of input at once. A PUT that replaces a book usually takes the id from the path and the new data from the body. This handler goes in BookController. It needs @PutMapping, @PathVariable, and org.springframework.http.HttpStatus imported, plus a @ResponseStatus for the not-found case.
@PutMapping("/{id}")
public ResponseEntity<Book> replace(@PathVariable Long id,
@RequestBody CreateBookRequest request) {
if (!books.containsKey(id)) {
return ResponseEntity.notFound().build();
}
Book updated = new Book(id, request.title(), request.author(), request.pages());
books.put(id, updated);
return ResponseEntity.ok(updated);
}The id comes from the URL, so a client cannot send a body that claims a different id. A method may have only one @RequestBody parameter. The body is a stream, and Spring reads it once, so a second body parameter would find nothing left.
Failure modes
Most trouble with @RequestBody falls into a few cases. The table lists what a client sees and the exception Spring throws internally. You need the exception name when you write handlers in the chapter on 400 responses.
| Situation | Status | Exception |
|---|---|---|
| `Content-Type` header missing, or a type with no converter such as `text/plain` for a record | 415 | `HttpMediaTypeNotSupportedException` |
| Body is empty and the parameter is required | 400 | `HttpMessageNotReadableException` |
| Body is not valid JSON, for example a missing quote or trailing comma | 400 | `HttpMessageNotReadableException` |
| A field has the wrong type, such as `"pages":"many"` for an `int` | 400 | `HttpMessageNotReadableException` |
| Client sends an `Accept` header the server cannot satisfy | 406 | `HttpMediaTypeNotAcceptableException` |
| Constraint annotations fail under `@Valid` | 400 | `MethodArgumentNotValidException` |
The last row belongs to the validation chapter. It is listed here so you can tell it apart from the others.
Edge cases to know
Missing and extra fields. Spring Boot configures Jackson so that unknown JSON properties are ignored. A body with an extra field "isbn" succeeds, and the field is dropped. A field that is absent leaves its record component at the default value. A String becomes null and an int becomes 0. A client can therefore omit pages and still get a 201 with "pages":0. Declaring a field as required is the job of validation, which a later chapter covers.
null versus absent. For a record with int pages, sending "pages":null also gives 0 by default. Use Integer if you must tell "not sent" from zero, and check for null yourself.
Character encoding. JSON is read as UTF-8 by default. A client that sends another encoding without declaring it in Content-Type (application/json;charset=...) can produce garbled text. Declare the charset in the header, or avoid it entirely and send UTF-8.
Body on GET. HTTP does not forbid a body on GET, and Spring will read it. Many proxies, caches, and clients drop or reject it. If a search needs many filters, use query parameters, or use POST for the search. A later chapter on choosing between input styles compares these options.
Reading the body twice. The servlet request body can be consumed once. A filter that reads it for logging will leave nothing for @RequestBody, unless the request is wrapped in a caching wrapper. If a body arrives empty only when a logging filter is on, look there first.
Size limits. Spring MVC does not cap the size of a JSON body by default. The server may. Tomcat limits form posts through server.tomcat.max-http-form-post-size and the overall request size through its connector settings. Apply an upper bound at the gateway or server for anything exposed to the internet.
Summary of rules
- Annotate a single parameter with
@RequestBody. Spring picks a converter from the request'sContent-Typeand your parameter's type. - Conversion happens before your method runs. Failures there give
415or400, and your code never sees the request. - Bodies are required unless you set
required = false. - Use
ResponseEntity.created(location)to answer aPOSTthat creates something. - Use a dedicated request type, and let the path supply the identity of the resource.
Exercise
A client sends POST /api/books with the body {"title":"Dune","author":"Frank Herbert"} and the header Content-Type: application/json, to the create handler in this chapter. The CreateBookRequest record has int pages. What status does the client get, and what value does pages have in the saved book? Then name the status and exception if the same body is sent with Content-Type: text/plain.
Show answer
With valid JSON and a correct Content-Type, the body parses. The missing pages field stays at the default for int, which is 0, so the client gets 201 Created with "pages":0. Nothing rejects the missing field, because no validation is applied. With Content-Type: text/plain, no converter can turn plain text into a CreateBookRequest, so Spring answers 415 Unsupported Media Type, raised as HttpMediaTypeNotSupportedException, and the handler never runs.
Exercise
Write a handler @PostMapping("/echo-size") that accepts a raw body as a byte[] and returns the number of bytes received as a String. Why might you choose byte[] over a record for a webhook that carries a signature?
Show answer
A handler such as public String echoSize(@RequestBody byte[] body) { return String.valueOf(body.length); } works. The byte[] converter delivers the exact bytes the client sent. For a signed webhook you compute the signature over those bytes. If you parsed the JSON into a record and re-serialized it, whitespace and field order could change, and the signature check would fail.