A controller that runs is not yet an API that is easy and safe to use: wrong status codes, a leaked password hash, a PATCH that wipes data, unknown ids silently ignored. This post walks through each decision at the HTTP edge of a Spring Boot API, with code that ran in the HR lab (users, roles, permissions). Read the REST conventions and centralized error handling posts first.
At a glance:
flowchart LR
C[Client] -->|"Request DTO + validate"| CT[Controller]
CT --> SV[Service]
SV --> DB["Entity + UNIQUE in DB"]
SV -.-> FA["findAllById: compare counts → 404"]
SV -->|Response DTO| CT
CT -->|"201 + Location / 204"| C
SV -.->|throws exception| AD[ControllerAdvice]
AD -->|ProblemDetail| C
1. ResponseEntity: the right status and headers
Key idea: returning an object directly always gives 200. When you need 201, 204 or a custom header, return a ResponseEntity; for 4xx/5xx throw an exception instead of building it by hand in the controller.
ResponseEntity bundles three things: status, headers, body. The usual factories:
| Case | How to return | Notes |
|---|---|---|
| Successful read | return the DTO, or ResponseEntity.ok(body) |
200 |
| Create | ResponseEntity.created(uri).body(dto) |
201, Location points to the new resource |
| Delete, logout | ResponseEntity.noContent().build() |
204, no body |
| Not found, duplicate | throw new ResourceNotFoundException(...) |
the advice turns it into 404/409 |
The lab controller:
@PostMapping
public ResponseEntity<ApiResponse<UserResponse>> create(@Valid @RequestBody CreateUserRequest req) {
UserResponse created = userService.create(req);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri(); // http://host/api/v1/users/42
return ResponseEntity.created(location).body(ApiResponse.of("User created", created));
}
@GetMapping("/{id}")
public ApiResponse<UserResponse> get(@PathVariable Long id) {
return ApiResponse.of(userService.get(id)); // not found: the service throws, the advice returns 404
}
ServletUriComponentsBuilder.fromCurrentRequest() takes the scheme, host and path of the current request, so Location stays correct when the port or prefix changes. Behind a reverse proxy, set server.forward-headers-strategy=framework so it reads X-Forwarded-*; otherwise Location carries the internal host.
2. Success bodies: envelope, bare body or ProblemDetail
Key idea: errors use ProblemDetail (RFC 9457) because it is a standard and Spring supports it out of the box. For success, pick one style and stay consistent; the lab picks a small envelope with data and meta, and no statusCode.
The source wants every body to carry statusCode, message, data (success) or statusCode, message, error, details (errors). Consistency is the right goal, but there are two problems:
statusCodeduplicates the HTTP status. Two sources of truth will disagree at some point (body says 200, header says 500 from a filter). Clients, proxies and monitoring all read the status line.- A home-made error format when a standard exists. ProblemDetail has
type,title,status,detail,instance, and allows extra fields such aserrors; Spring Security and Spring MVC can both produce it.
The lab keeps an envelope for success and ProblemDetail for errors:
/** Envelope for success bodies. Errors use ProblemDetail (RFC 9457). */
@JsonInclude(JsonInclude.Include.NON_NULL)
public record ApiResponse<T>(String message, T data, PageMeta meta) {
public static <T> ApiResponse<T> of(T data) { return new ApiResponse<>(null, data, null); }
public static <T> ApiResponse<T> of(String message, T data) { return new ApiResponse<>(message, data, null); }
public static <T> ApiResponse<List<T>> page(List<T> items, PageMeta meta) { return new ApiResponse<>(null, items, meta); }
public record PageMeta(int page, int size, long total, int pages) {}
}
@JsonInclude(NON_NULL) drops null fields, so GET /users/42 has no "meta": null. A lab test asserts exactly that (jsonPath("$.meta").doesNotExist()).
3. DTOs: never return entities
Key idea: the request DTO is the input contract (with validation), the response DTO is the output contract (only the fields allowed out). The entity is a storage detail and doesn’t cross the HTTP boundary.
A DTO (data transfer object) exists only to carry data across a boundary. Java records fit well: immutable, equals/toString for free, and Jackson reads and writes them without setters.
/** Input contract: validation lives here, not on the entity. */
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 the first 72 bytes
User.Gender gender) {}
/** Output contract: no password, no lazy collections. */
public record UserResponse(Long id, String name, String email, User.Gender gender,
List<String> roles, Instant createdAt) {
static UserResponse from(User u) {
return new UserResponse(u.getId(), u.getName(), u.getEmail(), u.getGender(),
u.getRoles().stream().map(Role::getName).sorted().toList(), u.getCreatedAt());
}
}
Serializing the User entity directly causes four kinds of trouble:
| Problem | What happens |
|---|---|
| Data leak | the password hash and internal columns go out; every new column leaks too |
| Lazy loading | Jackson calls getRoles() after the transaction closed: LazyInitializationException, or open-in-view on and silent N+1 |
| Recursion | User.roles → Role.users → User.roles…: StackOverflowError or endless JSON |
| Coupling | renaming a column breaks clients; the API can’t have its own computed fields |
The same goes for requests: binding an entity as @RequestBody invites mass assignment (the client adds "roles":[...] or "id":1 and Jackson sets it). A DTO only has the fields the client may send.
4. Mapping entities to DTOs
Key idea: with a few dozen DTOs, a from() factory on the record or a hand-written mapper class is enough and the easiest to read. MapStruct pays off when there are many mappings with many repetitive fields.
Three common options:
- Static factory on the DTO (
UserResponse.from(user)): short, sits next to the DTO. Downside: the DTO knows the entity. - Hand-written mapper (
UserMapperas a@Component): separates both sides fully, with room for logic such as masking an email or converting units. - MapStruct: generates mapping code at compile time, no reflection, as fast as hand-written.
Whatever you pick, mapping must happen inside the service transaction, while lazy collections can still load. The lab hit this for real: the controller called user.getRoles() after the service returned, and with open-in-view=false that threw LazyInitializationException. The fix: the service returns a fully built record.
5. PUT, PATCH and relations by id
Key idea: PUT replaces the whole resource, so its DTO looks like the create DTO. PATCH must tell “not sent” from “sent as null”. Relations arrive as lists of ids; check every id exists before assigning.
PUT sends the whole resource: a missing field means reset it. PATCH sends only the fields to change. A record with all-nullable fields can’t tell {"address": null} (remove the address) from {} (keep it): both end up as address == null.
Ways to handle PATCH:
- JSON Merge Patch (RFC 7396,
application/merge-patch+json): read the body as aJsonNode, apply it to the current state, then validate the resulting DTO. The clearest semantics. JsonNullable<T>(thejackson-databind-nullablelibrary): three states, “absent”, “null”, “has a value”.- A separate endpoint for a separate action: a password change is
POST /users/{id}/passwordrequiring the current password, not “if password is not null, re-hash it” inside the user PUT as the source suggests.
Relations by id. Creating a role sends permissionIds: [1, 2, 3]; updating it sends the new list and replaces the whole set (not additive). The lab code:
Set<Permission> loadAll(Set<Long> ids) {
List<Permission> found = permissions.findAllById(ids);
if (found.size() != ids.size()) { // findAllById silently skips unknown ids
Set<Long> foundIds = found.stream().map(Permission::getId).collect(Collectors.toSet());
Long missing = ids.stream().filter(id -> !foundIds.contains(id)).findFirst().orElseThrow();
throw new ResourceNotFoundException("Permission", "id", missing);
}
return new HashSet<>(found);
}
@Transactional
public Role replacePermissions(Long roleId, Set<Long> permissionIds) {
Role role = roles.findWithPermissionsById(roleId)
.orElseThrow(() -> new ResourceNotFoundException("Role", "id", roleId));
role.replacePermissions(loadAll(permissionIds)); // clear() + addAll(): PUT semantics
return role; // dirty checking writes the join-table diff at commit
}
Set or List for @ManyToMany, and which side to delete from
- Use a
Setfor@ManyToManycollections. With aList(a “bag” in Hibernate terms), removing one element makes Hibernate delete all of the owner’s rows in the join table and re-insert the rest. ASetdeletes just the one row. - No
CascadeType.REMOVEon@ManyToMany: deleting a role would delete permissions shared with other roles. - Delete from the owning side (the side with
@JoinTable): Hibernate removes the join rows first. The source says “deleting a role makes JPA clear the join table (cascade)”: that’s only true ifRoleownspermission_role. Deleting the inverse side (for exampleRolewhenUser.rolesownsuser_role) hits a foreign key violation; detach the role from its users first, or refuse to delete a role in use. - The lab has a
@DataJpaTestfor the permission replace: afterflush()+clear()to force real SQL, the role only has the new permission and thepermissionstable still has both rows.
6. Validation beyond the basics
Key idea: built-in annotations only check one field. Your own rules become your own constraints; rules across fields become class-level constraints; rules that need the database (duplicate email) belong to the service and to UNIQUE.
The basics (@Valid, MethodArgumentNotValidException, returning all errors at once) are in the error handling post. The lab returns them as ProblemDetail with an errors array:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
List<Map<String, String>> errors = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of("field", fe.getField(), "message", String.valueOf(fe.getDefaultMessage())))
.toList();
ProblemDetail pd = problem(HttpStatus.BAD_REQUEST, "validation-failed", "Request body is invalid");
pd.setProperty("errors", errors);
return ResponseEntity.badRequest().body(pd);
}
A @WebMvcTest sends {"name":" ","email":"not-an-email","password":"123"} and asserts all three fields are in errors, plus verify(userService, never()).create(any()): an invalid request never reaches the service.
A custom constraint is an annotation plus a ConstraintValidator. Example @StrongPassword (run with Hibernate Validator 9 from Spring Boot 4):
@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = StrongPasswordValidator.class)
public @interface StrongPassword {
String message() default "must have 8-72 bytes, a letter and a digit";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class StrongPasswordValidator implements ConstraintValidator<StrongPassword, String> {
@Override public boolean isValid(String v, ConstraintValidatorContext ctx) {
if (v == null) return true; // null is @NotBlank's job
int bytes = v.getBytes(StandardCharsets.UTF_8).length; // BCrypt reads at most 72 BYTES
return bytes >= 8 && bytes <= 72
&& v.chars().anyMatch(Character::isLetter)
&& v.chars().anyMatch(Character::isDigit);
}
}
The validator returns true for null so each annotation owns one rule. Spring creates validators through the bean factory, so you can inject other beans; but don’t query the database in a validator, leave that to the service.
Class-level constraint: @PasswordsMatch, and the run results
A rule across two fields goes on the whole record, then the error is attached to a specific field so the frontend highlights the right input:
@PasswordsMatch
public record RegisterRequest(@NotBlank @Email String email,
@NotBlank @StrongPassword String password,
String confirmPassword) {}
public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, RegisterRequest> {
@Override public boolean isValid(RegisterRequest r, ConstraintValidatorContext ctx) {
if (r == null || r.password() == null) return true;
if (r.password().equals(r.confirmPassword())) return true;
ctx.disableDefaultConstraintViolation(); // attach the error to a field, not the object
ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())
.addPropertyNode("confirmPassword").addConstraintViolation();
return false;
}
}
Run results (JDK 21, spring-boot-starter-validation 4.0.3):
| Input | Errors |
|---|---|
| valid | none |
password = “password” |
password: must have 8-72 bytes, a letter and a digit |
| two different passwords | confirmPassword: passwords do not match |
| bad email, 76-byte password | three errors: confirmPassword, email, password |
| null password | only password: must not be blank |
Note: when @NotBlank already failed, @StrongPassword still runs (it returns true for null). To stop at the first error use @GroupSequence, but for most APIs returning every error at once is fine.
Create and update have different rules. Two options: validation groups (@NotBlank(groups = OnCreate.class) then @Validated(OnCreate.class) in the controller, since @Valid doesn’t take groups) or two separate records, CreateUserRequest and UpdateUserRequest. Two records read better and have fewer traps; groups are only worth it when the DTOs are almost identical.
Validating in the service. Put @Validated on the service class and @Valid/constraints on parameters, and Spring checks them even when a job or a Kafka consumer calls the service, not only HTTP. Violations throw ConstraintViolationException; map it in the advice, or the catch-all returns 500.
Normalize first, check second, UNIQUE is the guard. The lab service:
String email = req.email().trim().toLowerCase(Locale.ROOT);
if (users.existsByEmailIgnoreCase(email)) throw new DuplicateResourceException("User", "email", email);
// UNIQUE is still the real guard: two concurrent requests can both pass the check above
User saved = users.save(new User(req.name().trim(), email, passwordEncoder.encode(req.password()), req.gender()));
The exists check gives a friendly message, but two parallel requests can both see “not there yet”. The UNIQUE constraint stops the second row; catch DataIntegrityViolationException and return 409. Normalize before saving because UNIQUE compares bytes: PostgreSQL treats an@x.dev and AN@x.dev as different values.
7. Swagger/OpenAPI and pagination
Key idea: springdoc generates OpenAPI docs from controllers and DTOs, handy for frontend developers to try the API; but don’t leave it public in production. Pagination returns meta and lets clients count pages from 1 through configuration, not manual arithmetic.
- springdoc: add
springdoc-openapi-starter-webmvc-ui(the 3.x line for Spring Boot 4). The UI is at/swagger-ui/index.html, the JSON at/v3/api-docs. With Spring Security, permit/v3/api-docs/**,/swagger-ui/**,/swagger-ui.html; declare a bearer@SecuritySchemeso the “Authorize” button sends the JWT. - Production: turn it off with
springdoc.api-docs.enabled=falseandspringdoc.swagger-ui.enabled=falsein the prod profile, or put it behind authentication. Public API docs are a map for attackers. - Pagination: take a
Pageable, returnApiResponse.page(items, new PageMeta(page, size, total, pages)). Sort whitelists and cursor pagination are in advanced REST API design.
Exercises
Exercise 1: Refactor the User API to be correct HTTP and safe
Task (paraphrased from the course lab): the user API returns entities, always answers 200 and validates nothing. (1) Return 201 + Location on create and 204 on delete, (2) use request/response DTOs and never leak the password, (3) validate input and return all errors at once, (4) return 409 for a duplicate email, (5) write a @WebMvcTest that proves all of it.
Solution to Exercise 1: a slice test that pins the contract
The controller, DTOs and advice are the snippets in sections 1, 3 and 6. The part worth reading is the test, because it is the proof of the HTTP contract:
@WebMvcTest(UserController.class)
class UserControllerWebMvcTest {
@Autowired MockMvc mvc;
@MockitoBean UserService userService;
@Test @WithMockUser
void createReturns201WithLocationAndNoPassword() throws Exception {
when(userService.create(any())).thenReturn(new UserResponse(42L, "An", "an@example.dev",
User.Gender.FEMALE, List.of(), Instant.parse("2026-01-01T00:00:00Z")));
mvc.perform(post("/api/v1/users").with(csrf()).contentType(APPLICATION_JSON).content(VALID))
.andExpect(status().isCreated())
.andExpect(header().string("Location", endsWith("/api/v1/users/42")))
.andExpect(jsonPath("$.data.password").doesNotExist())
.andExpect(jsonPath("$.meta").doesNotExist());
}
@Test @WithMockUser
void duplicateMapsTo409() throws Exception {
when(userService.create(any())).thenThrow(new DuplicateResourceException("User", "email", "an@example.dev"));
mvc.perform(post("/api/v1/users").with(csrf()).contentType(APPLICATION_JSON).content(VALID))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.type").value(endsWith("duplicate-resource")));
}
}
All four tests in this class (plus the validation test from section 6 and a malformed-JSON test that expects 400, not 500) pass on Spring Boot 4.0.3. with(csrf()) is needed because the slice uses the default security chain, while the real chain disables CSRF for /api/**.
What a senior would add: tests for a separate UpdateUserRequest, a @DataJpaTest for the UNIQUE constraint (catch DataIntegrityViolationException → 409), and a contract test generated from OpenAPI so the frontend knows when the API changes.
Remember
- Know which endpoints return 200, 201 +
Location, 204, and why errors should be thrown rather than built by hand. - Explain the four consequences of serializing an entity.
- Tell PUT from PATCH at the DTO level, and how to express “sent null” versus “not sent”.
- Know why
findAllByIdneeds a count check, and whyUNIQUEis the real duplicate guard. - Write a custom constraint, including a cross-field one.
Interview questions
Junior
Why not return JPA entities directly from a controller?
Because they leak sensitive data, cause lazy-loading and JSON recursion errors, and lock the database schema into the API contract.
A response DTO holds only the fields allowed out and is built inside the transaction. A request DTO blocks mass assignment: the client can’t sneak in id or roles.
What should a POST that creates a resource return?
201 Created, a Location header pointing to the new resource, and usually the created resource as the body.
In Spring: ResponseEntity.created(uri).body(dto), with uri built from ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"). A successful DELETE returns 204 with no body.
Mid
Do you put a statusCode in the response body?
No. The HTTP status is already in the status line; repeating it in the body creates two sources of truth that can disagree.
Errors use ProblemDetail (which has a standard status field per RFC 9457). Success uses a bare body or a data/meta envelope, as long as it’s consistent across the system.
How do PUT and PATCH differ when designing DTOs?
PUT sends the whole resource, so the DTO looks like the create DTO; PATCH sends only changed fields, so it must tell “not sent” from “sent as null”.
A record with all-nullable fields can’t. Use JSON Merge Patch read as a JsonNode, or JsonNullable, or move specific actions (password change) to their own endpoints.
You update a role with permissionIds and one id doesn’t exist. What happens?
If you just call findAllById and assign, the bad id is silently dropped and the client gets 200. Compare the counts and return 404 naming the missing id.
Take the ids as a Set so duplicates don’t break the count, and replace the whole permission set (PUT semantics) with clear() + addAll() on a Set collection.
Validation groups or two DTOs for create and update?
Usually two separate records: easier to read, no groups to remember, one contract per DTO.
Groups need @Validated(OnCreate.class) because @Valid doesn’t take groups, and field annotations get crowded. They’re only worth it when both DTOs are almost identical.
Senior
You already check existsByEmail in the service. Why do you still need UNIQUE?
Because check-then-write isn’t atomic: two parallel requests both see “not there” and both insert. Only a database constraint stops that.
Keep the exists check for a friendly error; map the DataIntegrityViolationException from UNIQUE to 409 as well. Normalize the email (trim, lowercase) before both steps because UNIQUE compares bytes.
How should you limit password length with BCrypt?
Limit it in bytes, at most 72, because BCrypt ignores every byte after 72; @Size counts characters, which isn’t enough for Unicode strings.
Write a constraint that counts UTF-8 bytes, or use an algorithm without this limit such as Argon2. Keep a sane upper bound anyway to block DoS with huge passwords.
Useful phrases for interviews
- “Request and response DTOs are two separate contracts, and the entity never crosses the HTTP boundary.”
- “A create returns 201 with a Location header; a delete returns 204 with no body.”
- “The HTTP status is the single source of truth, so I don’t repeat it in the body.”
- “Errors are ProblemDetail everywhere, including the ones from the security filters.”
- “Binding the entity directly opens the door to mass assignment.”
- “With merge patch, null means remove and a missing field means keep.”
- “findAllById silently skips unknown ids, so I compare the counts and return a 404.”
- “The exists check is for a nice message; the unique constraint is the real guard against races.”
- “BCrypt only reads 72 bytes, so the limit has to be in bytes, not characters.”
- “I’d hand-write mappers in a small codebase and move to MapStruct with an error policy when mapping becomes busywork.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.