Sub topic 4
Using records as request and response bodies
This chapter assumes you know basic Java syntax, can write a Spring Boot @RestController, and understand JSON request and response bodies. It also assumes Java 17 or later. It covers how records fit into a controller: one record for input, one for output, and a service that connects them.
The request and response pair
A request DTO describes what a client may send. A response DTO describes what the server chooses to return. Keeping them as two separate records lets each one change without affecting the other. A request has no id, because the server assigns it. A response never contains fields such as a password hash.
The request record carries the constraints:
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@Min(18) int age) {
}The response record exposes only the fields you want to publish. A static factory method copies them from the entity, so the entity itself never reaches the API:
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}The controller
The controller below accepts the request record and returns the response record.
import jakarta.validation.Valid;
import java.net.URI;
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;
@RestController
@RequestMapping("/users")
class UserController {
private final UserService service;
UserController(UserService service) {
this.service = service;
}
@PostMapping
ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
UserResponse created = service.create(request);
return ResponseEntity.created(URI.create("/users/" + created.id())).body(created);
}
}Each part of the create method has a job:
@RequestBodytells Spring to read the HTTP body and convert it with Jackson, the JSON library Spring Boot uses by default.@Validruns the Bean Validation constraints on the record before the method body executes.ResponseEntity.created(...)sets status201 Createdand theLocationheader, which is the correct REST answer for a new resource.- The return value is a record, which Jackson writes as a JSON object.
Here is what happens during one call:
What a request looks like
A client sends this body:
{
"name": "Ada",
"email": "[email protected]",
"age": 36
}Jackson matches JSON property names to the record component names and calls the canonical constructor. The service returns a UserResponse, and the client receives:
{
"id": 1,
"name": "Ada",
"email": "[email protected]"
}The age field is absent from the response because UserResponse has no such component. The shape of the output follows the record, not the entity.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Invalid input is accepted | `@Valid` is missing on the parameter | Add `@Valid` before `@RequestBody` |
| Constraints are ignored | The Bean Validation starter is not on the classpath | Add `spring-boot-starter-validation` |
| `400` with a JSON parse error | Malformed JSON or a wrong type, such as a string for `age` | Fix the client payload |
| A missing `int` field becomes `0` | Primitive components take their default value | Use `Integer` with `@NotNull` when absence matters |
| Extra JSON fields are silently dropped | Spring Boot disables Jackson's fail-on-unknown-properties by default | Set `spring.jackson.deserialization.fail-on-unknown-properties=true` if you want strictness |
Why not use the entity directly?
Using the entity as the request body lets a client set any field it can guess, such as id or a role flag. Using it as the response can leak internal columns or trigger lazy loading while Jackson serializes it. Two small records avoid both problems and make the API contract visible in one place.
Exercise
A client sends {"name": "Bo", "email": "[email protected]"} to the endpoint above, and the server returns 400. Which component of CreateUserRequest most likely caused it, and why? What change would make the error message clearer?
Show answer
The age component. It is a primitive int, so the missing field becomes 0, and @Min(18) fails. Changing it to Integer age with @NotNull @Min(18) makes the missing field produce a clear "must not be null" violation instead of a misleading value error.
Exercise
Why does the controller build the Location header from created.id() instead of reading an id from the request?
Show answer
The request record has no id, because the server assigns it. Only the response record, built from the saved entity, contains the generated id, so the Location URI must come from it.