Sub topic 4
Using records as request and response bodies
This chapter shows how a Spring MVC controller reads a JSON request into a record and writes a record back as JSON. It assumes you can write a basic @RestController, you know what a JSON body and an HTTP status code are, and you run Java 17 or later with Spring Boot 3.x and the spring-boot-starter-web and spring-boot-starter-validation dependencies. Records and the reason for DTOs were covered in earlier chapters, so this chapter focuses on how the pieces connect in a controller.
The working model
A controller method never touches raw JSON. Spring MVC delegates that work to an HttpMessageConverter. When Jackson is on the classpath, Spring Boot registers a JSON converter backed by a Jackson ObjectMapper.
For a @RequestBody parameter, the sequence is:
- Spring reads the
Content-Typeheader and finds a converter that supportsapplication/json. - Jackson parses the body and calls the record's canonical constructor with the values it finds.
- If the parameter has
@Valid, Spring runs Bean Validation on the new object. - If everything passes, your method runs with a fully built record.
For the return value, the converter does the reverse. It reads the record's components and writes them as a JSON object.
Jackson 2.12 and later understand records natively. Spring Boot 2.5 and later ship a compatible version, so no extra module or annotation is needed. Jackson uses the record component names as JSON property names and the canonical constructor to create the object. Record accessors are named name() rather than getName(), and Jackson knows how to handle that for records.
Two records, two jobs
Use one record for what the client sends and a different record for what the server returns. They look similar at first, but they diverge as the API grows.
| Row | Request record | Response record |
|---|---|---|
| Direction | Client to server | Server to client |
| Typical name | `CreateUserRequest`, `UpdateUserRequest` | `UserResponse` |
| Contains `id` | No, the server assigns it | Yes |
| Contains validation annotations | Yes | No |
| Contains secrets such as password hashes | Only incoming plain input | Never |
| Built by | Jackson | Your code, often a `from(...)` factory |
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 the client should see. A static factory copies them from the entity:
public record UserResponse(Long id, String name, String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}CreateUserRequest has an age field, and UserResponse leaves it out. That is deliberate. The response is a separate contract, and you decide what goes in it.
A complete create endpoint
The controller needs a service, and the service needs an entity and a repository. Here is a minimal version of each so the example runs as shown.
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private int age;
protected User() {
}
public User(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
public int getAge() { return age; }
}import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
class UserService {
private final UserRepository repository;
UserService(UserRepository repository) {
this.repository = repository;
}
@Transactional
UserResponse create(CreateUserRequest request) {
User saved = repository.save(new User(request.name(), request.email(), request.age()));
return UserResponse.from(saved);
}
}The users table name avoids user, which is a reserved word in some databases. The service accepts the request record and returns the response record. The entity stays inside this layer.
Now the controller:
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);
}
}ResponseEntity.created(...) sets status 201 and the Location header. A successful call looks like this:
POST /users HTTP/1.1
Content-Type: application/json
{"name": "Ada", "email": "[email protected]", "age": 36}HTTP/1.1 201 Created
Location: /users/1
Content-Type: application/json
{"id":1,"name":"Ada","email":"[email protected]"}If you do not need a Location header, you can return the record directly and set the status with @ResponseStatus(HttpStatus.CREATED) on the method. Use ResponseEntity when headers or a conditional status matter.
What happens when the body is wrong
Two different failures can occur, and they happen at different stages.
| Problem | Stage | Exception | Default status |
|---|---|---|---|
| Body is not valid JSON, or a value has the wrong type (`"age": "abc"`) | Jackson | `HttpMessageNotReadableException` | 400 |
| Body parses but a constraint fails (`"email": "nope"`) | Bean Validation | `MethodArgumentNotValidException` | 400 |
| Content type is not JSON | Converter selection | `HttpMediaTypeNotSupportedException` | 415 |
Both of the first two give 400, but the exception types differ, which matters when you write an @RestControllerAdvice to shape error bodies. Validation errors expose a BindingResult with per-field messages. Parse errors do not.
Constraint annotations on record components are applied to the generated fields, accessors, and constructor parameters where the annotation allows it. Bean Validation reads them from the fields, so the @Valid on the controller parameter is all you need.
Gotchas
Missing fields become defaults
Jackson does not fail when a property is absent. It passes null for reference types and 0 or false for primitives. Consider this body sent to the endpoint above:
{"name": "Ada", "email": "[email protected]"}Because age is an int, it becomes 0, and the client receives a message about the minimum value of 18 instead of a message saying the field is required. If you want "missing" to be distinguishable, use a wrapper type and add @NotNull:
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public record AgeRequest(@NotNull @Min(18) Integer age) {
}Unknown properties are ignored
Spring Boot configures its ObjectMapper with FAIL_ON_UNKNOWN_PROPERTIES turned off. If a client sends "id": 99 to POST /users, Jackson drops it because CreateUserRequest has no id component. This is a quiet benefit of a separate request record. A client cannot set fields you did not declare, which prevents mass assignment bugs that appear when an entity is bound directly. It also means typos in property names go unnoticed. If you want strict parsing, set spring.jackson.deserialization.fail-on-unknown-properties=true.
Forgetting `@Valid`
Constraint annotations do nothing on their own. Without @Valid (or @Validated) on the parameter, an invalid record reaches your service. The code compiles, the tests with valid data pass, and the bug only shows up in production.
Records are not nullable-safe by default
A record component of type String accepts null. If the compact constructor or service code calls methods on it, you can get a NullPointerException for input that validation would have rejected, if validation is missing or runs later than the code you wrote. Keep validation annotations and constructor logic consistent, and let Bean Validation report missing values wherever possible.
Entities leaking through return types
A method declared as ResponseEntity<User> compiles and works, and that is the danger. Every getter on the entity becomes part of the API, and lazy associations can trigger extra queries or serialization errors. Declare the return type as the response record. Then the compiler stops you from returning the entity.
Other request shapes
Not every input is a body. Records fit the body case, but other sources use different binding.
- Path variables and request parameters use
@PathVariableand@RequestParamon individual method parameters. A record is not needed for a singleLong id. - Query parameter groups can bind to a record without
@RequestBody. Spring MVC treats a record parameter as a model attribute and fills it from the query string through its constructor. Use this for filters such asGET /users?active=true&page=0. - Update bodies usually get their own record.
UpdateUserRequestmight allow onlynameandemail, whileCreateUserRequestalso acceptsage. Separate records let each operation have its own rules.
Here is a query-parameter record used as a filter:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
record UserSearch(String name, Boolean active) {
}
@RestController
class UserSearchController {
@GetMapping("/users/search")
String search(UserSearch search) {
return "name=" + search.name() + ", active=" + search.active();
}
}A request to /users/search?name=Ada&active=true returns name=Ada, active=true. Wrapper types are used here so absent parameters become null rather than a default. This works because the record has a single canonical constructor and Spring binds its parameters by name. The parameter names are available in a standard Spring Boot build, but a build that does not keep them (for instance, one that omits the -parameters compiler flag outside the Spring Boot plugin setup) can break constructor binding.
Returning collections and nested records
A List<UserResponse> return type works with no extra setup. Jackson writes a JSON array of objects. Records can also nest:
import java.util.List;
public record UserDetailResponse(Long id, String name, List<AddressResponse> addresses) {
}
record AddressResponse(String city, String country) {
}Build nested records in your mapping code, not by passing entities down. If UserDetailResponse.from(user) calls user.getAddresses().stream().map(AddressResponse::from).toList(), the mapping runs inside the service transaction, where lazy collections can still load. Serializing an entity after the transaction closes is a common source of LazyInitializationException. Mapping to records inside the service avoids it.
Practical checklist
- Name request records by operation (
CreateUserRequest,UpdateUserRequest) and response records by resource (UserResponse). - Put
@Validon every@RequestBodyrecord parameter. - Use wrapper types plus
@NotNullwhen you must tell "missing" from "zero". - Return response records from controller methods, never entities.
- Map entities to records inside the service, while the transaction is open.
- Use
ResponseEntity.created(...)for creation, so clients get aLocationheader.
Exercise
A client posts {"name": "Ada", "email": "[email protected]"} to an endpoint whose request record declares @Min(18) int age. The response is a 400 about the minimum age. Why does the message not say that age is missing, and what change to the record would let you report it as missing?
Show answer
Jackson does not fail on absent properties. For a primitive int it passes the default value 0 to the canonical constructor, so @Min(18) sees 0 and rejects it as too small. Declare the component as the wrapper type Integer and add @NotNull, as in @NotNull @Min(18) Integer age. An absent property then arrives as null and fails @NotNull, which gives a distinct "required" violation.
Exercise
A client sends {"id": 99, "name": "Ada", "email": "[email protected]", "age": 36} to POST /users using the CreateUserRequest record from this chapter. What happens to the id value, and why is this a benefit of a separate request record?
Show answer
Jackson ignores it. Spring Boot disables FAILONUNKNOWN_PROPERTIES, and CreateUserRequest has no id component, so the value is dropped and the database assigns the id. Because the request type only declares the fields you allow, a client cannot set fields such as the id, which would be possible if the entity were bound directly as the request body.