2 min read

컨트롤러에서 ResponseEntity 대신 DTO를 직접 반환하는 이유

성공 응답이 항상 200이고 붙일 헤더도 없어서 감쌀 이유가 없기 때문이다. @RestController에서 객체를 반환하면 Spring이 200 + JSON으로 보내주므로, ResponseEntity.ok(dto)와 결과가 같다.

java
// 둘 다 200 OK + 같은 JSON
public PostResponse getPost(@PathVariable String slug) {
    return postService.getPost(slug);
}

public ResponseEntity<PostResponse> getPost(@PathVariable String slug) {
    return ResponseEntity.ok(postService.getPost(slug));
}

"없으면 404"는 컨트롤러에서 ResponseEntity.notFound()로 분기하지 않고 예외로 처리한다. Service가 PostNotFoundException을 던지면 ApiExceptionHandler가 404 ProblemDetail로 바꾼다. 컨트롤러는 성공한 경우만 다루고, 오류 형식은 한 곳에서 관리된다.

ResponseEntity가 필요한 경우 (상태 코드나 헤더를 요청마다 다르게 정해야 할 때)

상황예
200이 아닌 성공 코드글 작성 201 Created + Location: /api/posts/{slug} 헤더
바디 없는 응답삭제 204 No Content
캐시 헤더Cache-Control, ETag (304 Not Modified)
파일 다운로드Content-Disposition

2차 쓰기 API(POST /api/posts)에서는 201 + Location 때문에 ResponseEntity를 쓰게 된다. 상태 코드만 고정으로 바꾸려면 @ResponseStatus(HttpStatus.CREATED)도 된다.

"모든 컨트롤러는 ResponseEntity를 반환한다"는 규칙을 두는 팀도 있다. 일관성을 위한 선택이라 틀린 건 아니다. 이 프로젝트는 혼자 하므로 단순한 쪽을 골랐다.

공유

댓글