Sub topic 2
Separating the API Contract with DTOs
Assume Java records, annotations, HTTP methods, JSON, Spring Boot, and basic JPA. A data transfer object (DTO) is a type used to move data across an API boundary. It keeps the JSON contract separate from the database entity.
DTOs Protect the Contract
Do not expose Book directly. Database fields may change, or may contain internal values that clients should not see. Use separate request and response types.
public record BookRequest(
@NotBlank String title,
@NotBlank String author) {
}
public record BookResponse(Long id, String title, String author) {
static BookResponse from(Book book) {
return new BookResponse(book.getId(), book.getTitle(), book.getAuthor());
}
}BookRequest describes accepted input. BookResponse describes returned output. The @NotBlank annotations will be checked when the controller uses @Valid.
Put Business Logic in a Service
The service coordinates repositories and conversions. It also decides what happens when a book does not exist.
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional
public BookResponse create(BookRequest request) {
Book book = repository.save(new Book(request.title(), request.author()));
return BookResponse.from(book);
}
@Transactional(readOnly = true)
public BookResponse get(Long id) {
return repository.findById(id)
.map(BookResponse::from)
.orElseThrow(() -> new BookNotFoundException(id));
}
}Constructor injection makes the dependency explicit and easy to replace in tests.
Define Transaction Boundaries
@Transactional groups database work into one unit. A successful method commits its changes. An unchecked exception normally rolls them back. Use readOnly = true for queries to document that they should not modify data.
Keep transaction annotations on service methods. This prevents HTTP details from controlling persistence behavior.
Write the REST Controller
The controller translates HTTP requests into service calls. It should remain thin.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable Long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(
@Valid @RequestBody BookRequest request) {
BookResponse response = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
}Map CRUD to HTTP
Use POST to create, GET to read, PUT to replace, and DELETE to remove. Return 201 Created after creation, 200 OK for successful reads and updates, 204 No Content after deletion, 400 Bad Request for invalid input, and 404 Not Found for an unknown ID.
Exercise
Why should a controller return a DTO instead of a JPA entity?
Show answer
A DTO keeps the public JSON contract independent from the persistence model and prevents accidental exposure of internal fields.