An HTTP request body is the payload that carries data from a client to a server. It is useful when a request needs to send more data than is convenient in a URI, such as payment details. The body may contain a formatted string, such as JSON, or binary data, such as a file. section 8.1.1 section 10.4
A request can carry data in several places:
- Query parameters appear in the URI and are suited to small quantities of data. section 8.1.1
- Path variables appear in the request path and are useful for small, mandatory values. section 8.1.1
- Headers do not appear in the URI, but are not intended for large quantities of data. The request body is the usual choice for larger payloads. section 8.1.1
In a Spring controller, annotate an action parameter with @RequestBody to receive the payload. By default, Spring assumes JSON and attempts to decode it into the parameter’s type. If it cannot decode the JSON into that type, the application responds with 400 Bad Request. section 10.4
Listing 10.16 Getting data from the client in the request body
@RestController
public class PaymentController {
private static Logger logger =
Logger.getLogger(PaymentController.class.getName());
@PostMapping("/payment")
public ResponseEntity<PaymentDetails> makePayment(
@RequestBody PaymentDetails paymentDetails) { #A
logger.info("Received payment " +
paymentDetails.getAmount()); #B
return ResponseEntity #C
.status(HttpStatus.ACCEPTED)
.body(paymentDetails);
}}
The POST /payment action receives a PaymentDetails object, logs its amount, and returns the object in the response body with an Accepted status. section 10.4
curl -v -X POST http://127.0.0.1:8080/payment -d '{"amount": 1000}' -H
➥"Content-Type: application/json"This cURL call sends a JSON payload containing an amount to /payment and identifies its content type as application/json. section 10.4
Although HTTP GET can use a request body, doing so is generally not recommended, and many tools do not support it. section 10.4
The request body is also part of an endpoint’s contract. A controller integration test can send a payload and check the response, helping catch problems such as a body that is not decoded as expected. section 16.2
Listing 16.4 Calling the endpoint with MockMvc
mockMvc.perform(post("/transfer") #A
.contentType(MediaType.APPLICATION_JSON) #B
.content(""" #C
{
"senderAccountId": 1,
"receiverAccountId": 2,
"amount": 100
}
"""))
.andExpect(status().isOk()); #DThis MockMvc test sends a JSON transfer payload to /transfer and checks for an OK response. section 16.2











