REST Controllers, Validation and DTOs
Building REST APIs with @RestController, request mapping, DTOs and Bean Validation is the daily work of a Spring Boot developer and a standard interview and machine-coding topic.
What you will learn
- Map endpoints with @GetMapping, @PostMapping and friends
- Bind @PathVariable, @RequestParam and @RequestBody
- Validate with @Valid and Jakarta Bean Validation
- Return proper status codes with ResponseEntity
Key concepts
@RestController
@Controller + @ResponseBody: return values are written as JSON by Jackson HttpMessageConverters.
DTOs
Separate request and response classes (records work well) from JPA entities, so you control what is accepted and exposed and avoid lazy-loading and recursion issues.
Bean Validation
Annotations like @NotBlank, @Email, @Size, @Positive on DTO fields, triggered by @Valid. Failures throw MethodArgumentNotValidException (400).
Layering
Controller (HTTP only) → Service (business rules, transactions) → Repository (data). Keep logic out of controllers.
Step by step
A complete endpoint
public record CreateOrderRequest(
@NotNull Long productId,
@Positive @Max(10) int quantity,
@NotBlank @Size(max = 200) String address) {}
public record OrderResponse(Long id, String status, BigDecimal total) {}
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
class OrderController {
private final OrderService orders;
@PostMapping
ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest req, @AuthenticationPrincipal Jwt jwt) {
OrderResponse created = orders.create(jwt.getSubject(), req);
return ResponseEntity.created(URI.create("/api/orders/" + created.id())).body(created);
}
@GetMapping("/{id}")
OrderResponse get(@PathVariable Long id) { return orders.get(id); }
@GetMapping
Page<OrderResponse> list(@RequestParam(defaultValue = "PAID") String status, Pageable pageable) {
return orders.list(status, pageable); // ?page=0&size=20&sort=createdAt,desc
}
}Examples
Calling another service with RestClient
Price price = pricingClient.get()
.uri("/prices/{sku}", sku)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { throw new PriceNotFound(sku); })
.body(Price.class);Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Build CRUD endpoints for a Book resource with validation and pagination.
- Write a custom validator annotation @ValidPincode.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
@RequestParam vs @PathVariable?
@PathVariable reads part of the URL path (/orders/42) and identifies a resource. @RequestParam reads query parameters (?status=PAID&page=2), used for filters, sorting and pagination.
Why not return JPA entities from controllers?
It couples your API to the database schema, can expose sensitive fields, triggers lazy-loading exceptions or N+1 queries during serialisation, and bidirectional relations can recurse forever. DTOs make the API contract explicit.
Summary
Thin @RestControllers bind and validate DTOs, delegate to services, and return precise statuses with ResponseEntity; keep entities out of the API.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus