DTOs, responses and validation for a Spring Boot REST API
ResponseEntity with 201 + Location and 204, envelope or bare body, record DTOs instead of entities, mapping entities to DTOs, PUT versus PATCH, relations sent as ids, custom constraints, normalizing before the uniqueness check, Swagger and pagination on Spring Boot 4.
On this page
1. The problem
The user API returns the User entity directly: the JSON includes password (a hash), and sometimes throws LazyInitializationException when Jackson calls getRoles(). Creation returns 200 with no Location; PATCH {"name":"An"} wipes the address; assigning permissionIds: [1, 2, 999] succeeds although permission 999 doesn't exist.
2. Key idea
A request DTO is the input contract, with validation. A response DTO holds only fields allowed out. Entities never cross the HTTP boundary; map entities to DTOs inside the service's transaction.
Returning the User entity as JSON |
What happens |
|---|---|
| Data leaks | password and internal columns go out; every new column leaks too |
| Lazy loading | LazyInitializationException, or open-in-view with silent N+1 |
| Recursion | User.roles → Role.users → … : StackOverflowError |
Taking the entity as @RequestBody |
mass assignment: the client adds "roles":[...] and Jackson sets it |
2.1 Which approach?
| Decision | Use when | Don't use when |
|---|---|---|
ResponseEntity |
you need 201, 204 or custom headers | returning errors (throw; the advice handles it) |
Envelope {data, meta} |
you want a fixed place for paging and warnings | the team prefers plain bodies with paging in headers |
UserResponse.from(user) |
a few dozen DTOs | complex mapping, many DTOs: MapStruct with unmappedTargetPolicy = ERROR |
PATCH via JSON Merge Patch or JsonNullable |
"not sent" must differ from "sent null" | full replacement (use PUT) |
3. In Spring Boot
public record CreateUserRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email @Size(max = 255) String email,
@NotBlank @Size(min = 8, max = 72) String password) {} // 72: BCrypt only reads 72 bytes
public record UserResponse(Long id, String name, String email, List<String> roles) {
static UserResponse from(User u) {
return new UserResponse(u.getId(), u.getName(), u.getEmail(),
u.getRoles().stream().map(Role::getName).sorted().toList());
}
}
@PostMapping
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest req) {
UserResponse created = userService.create(req);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri(); // .../api/v1/users/42
return ResponseEntity.created(location).body(created); // 201
}Validation errors go through a @RestControllerAdvice into one ProblemDetail (RFC 9457) listing every invalid field at once. Duplicate emails: normalize (trim, lowercase), rely on UNIQUE, and map DataIntegrityViolationException to 409; an existsByEmail check before insert still races. Behind a reverse proxy, enable forwarded-header handling so Location doesn't contain internal hosts.
Relationships by id and custom constraints
- Updating a role sends
permissionIdsand replaces the whole set.findAllByIdskips missing ids, so compare counts: if any are missing, throwResourceNotFoundExceptionwith the missing id (404) instead of assigning a partial set. - A custom constraint is an annotation (
@StrongPassword) plus aConstraintValidator. Multi-field rules (end date after start date) go at class level. - Create and update need different rules: separate
CreateUserRequestandUpdateUserRequest, or validation groups. - Changing a password is its own endpoint (
POST /users/{id}/password) requiring the old password, not part of a generic PATCH. - Pagination:
pageandsizewith a maximum; deep pages use keyset.
4. Working with AI
Hand to AI: request/response DTOs from an entity, @WebMvcTest for the HTTP contract, OpenAPI annotations, mappers with mapping tests.
Check yourself in AI-written code:
- No controller accepts or returns a JPA entity.
-
POSTcreation returns 201 +Location;DELETEreturns 204 with no body. - Validation sits on request DTOs; responses carry no
passwordor tokens. - Uniqueness has a DB
UNIQUEand the violation maps to 409. -
findAllByIdresults are counted; PATCH tells "not sent" from "null".
5. Exercises
Exercise 1: Review an AI-written controller
The AI says "complete user API, validated". Find the bugs and fix them.
@PostMapping("/users")
public User create(@Valid @RequestBody User user) { // User is an @Entity with @Email, @Size on fields
if (repo.existsByEmail(user.getEmail())) throw new DuplicateException();
return repo.save(user); // returns 200
}Solution 1
- Accepting the entity: mass assignment (the client sends
"roles":[{"id":1}]or"id":5to overwrite). - Returning the entity: leaked
passwordhash, lazy loading, recursive JSON. - Validation on the entity: the entity stores a hash, so
@Sizechecks the wrong thing; validation also runs on import paths. existsByEmailthensave: two simultaneous requests both pass. You needUNIQUEwith the error mapped to 409, after normalizing the email.- 200 instead of 201 +
Location; the password isn't hashed. - Fix as in section 3, plus a
@WebMvcTestasserting 201,Location, nopassword, and 409 on duplicates.
Exercise 2: PATCH wipes data
PATCH /users/42 with {"name":"An"} sets address to null. The AI's code: mapper.updateEntity(dto, user) with a DTO holding every field. Explain and propose two fixes.
Solution 2
Jackson reads missing fields as null, so the DTO can't tell "the client didn't send address" from "the client sent address: null". The mapper copies every field, nulls included, over the entity.
- JSON Merge Patch (RFC 7396): accept
application/merge-patch+jsonas aJsonNode, apply it to the current state, then validate the resulting DTO. Fields absent from the body stay; onlynullfields are cleared. JsonNullable<T>(jackson-databind-nullable): three states (absent, null, value); the mapper copies only fields that areisPresent().
Either way, test that a missing field keeps its value and an explicit null clears it.
Summary
- 201 +
Locationon create, 204 on delete; errors are thrown and the advice returns ProblemDetail. - Never return or accept entities; request DTOs validate, response DTOs expose only allowed fields.
- Map entities to DTOs inside the service's transaction.
- PATCH separates "not sent" from "null";
findAllByIdmust be counted. - Enforce uniqueness with a DB
UNIQUE, not just a SELECT.
Further reading: Centralized error handling in Spring Boot.
Practice interview questions on this topic
- How do you validate request DTOs in Spring, and why is API-level validation not enough?
- Which status codes should a REST API return for create, delete, auth failures and server errors?
- How do PUT and PATCH differ, and how does that affect DTO design?
- What is ResponseEntity? When do you return a ResponseEntity, a plain object, or use @ResponseStatus?
- Why shouldn't you return JPA entities directly from an API? How do you use DTOs and projections?
- How do you design error responses for a multi-service system, and why not return stack traces to clients?
All Web & REST API questions →All Spring Boot questions →All JPA & Hibernate questions →
Comments
Community rules