SteelReed

Search

Search posts, questions…

5. Spring Boot

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.

18 Nov 20267 min readMid

–

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

JAVA
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 permissionIds and replaces the whole set. findAllById skips missing ids, so compare counts: if any are missing, throw ResourceNotFoundException with the missing id (404) instead of assigning a partial set.
  • A custom constraint is an annotation (@StrongPassword) plus a ConstraintValidator. Multi-field rules (end date after start date) go at class level.
  • Create and update need different rules: separate CreateUserRequest and UpdateUserRequest, 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: page and size with 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.
  • POST creation returns 201 + Location; DELETE returns 204 with no body.
  • Validation sits on request DTOs; responses carry no password or tokens.
  • Uniqueness has a DB UNIQUE and the violation maps to 409.
  • findAllById results 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.

JAVA
@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":5 to overwrite).
  • Returning the entity: leaked password hash, lazy loading, recursive JSON.
  • Validation on the entity: the entity stores a hash, so @Size checks the wrong thing; validation also runs on import paths.
  • existsByEmail then save: two simultaneous requests both pass. You need UNIQUE with 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 @WebMvcTest asserting 201, Location, no password, 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+json as a JsonNode, apply it to the current state, then validate the resulting DTO. Fields absent from the body stay; only null fields are cleared.
  • JsonNullable<T> (jackson-databind-nullable): three states (absent, null, value); the mapper copies only fields that are isPresent().

Either way, test that a missing field keeps its value and an explicit null clears it.

Summary

  • 201 + Location on 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"; findAllById must 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

All Web & REST API questions →All Spring Boot questions →All JPA & Hibernate questions →

Loading comments…
Next on the roadmapIoC and Dependency Injection: how the Spring container works