Lesson 34 / 38

Building a REST Controller End to End

Wire a full Spring Web REST endpoint from request to response, and see how Jackson silently converts your Java objects to and from JSON.

Request in, response out

@RequestBody deserializes the incoming JSON into a Java object; the return value is serialized back to JSON automatically. @Valid triggers bean-validation annotations on the DTO before the method body even runs.

record CreateOrderRequest(@NotBlank String customerId, @Positive int quantity) {}

@RestController
@RequestMapping("/api/orders")
class OrderController {
    private final OrderService service;
    OrderController(OrderService service) { this.service = service; }

    @PostMapping
    ResponseEntity<Order> create(@Valid @RequestBody CreateOrderRequest req) {
        Order created = service.place(req.customerId(), req.quantity());
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }
}

Jackson does the JSON work

Jackson maps Java field names to JSON keys by convention, and handles nested objects, lists, and LocalDate/records automatically (with the jackson-datatype-jsr310 module). Rename a JSON key with @JsonProperty, or hide an internal field with @JsonIgnore.

Customising the JSON

Field-level annotations steer serialization without changing your API's shape for callers.

class UserDto {
    @JsonProperty("user_id")
    Long id;

    String email;

    @JsonIgnore
    String passwordHash;   // never serialized
}