Video in progress

Junior 🌱 Spring

What does @RequestBody do?

It turns the JSON in the request body into a Java object. It's usually used in POST and PUT to accept a DTO.

📖 Answer

public record CreateUserRequest(String name, String phone) {}

@PostMapping("/api/users")
public ResponseEntity<UserDto> create(@Valid @RequestBody CreateUserRequest req) {
    UserDto saved = users.create(req);
    return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}

The client sends:

{ "name": "Dilshod", "phone": "+998901234567" }

Jackson converts the JSON into CreateUserRequest. Where errors come up:

  • broken JSON — HttpMessageNotReadableException, response 400;
  • no Content-Type: application/json — 415;
  • @Valid is present and validation fails — 400 (MethodArgumentNotValidException).

A method can have only one @RequestBody, because the body is read once. If you need two objects, put them inside one DTO.