📮 ResponseEntity란?

정의

ResponseEntityHTTP 응답의 본문(body), 상태 코드(status), 헤더(headers)를 함께 담아 반환할 수 있는 Spring의 응답 객체이다. REST API에서 응답을 더 명확하게 제어할 때 자주 사용한다.

🎯 사용하는 이유

  • 상태 코드를 명시적으로 반환할 수 있다.
  • 응답 헤더를 추가할 수 있다.
  • 성공/실패 상황에 따라 응답 형태를 유연하게 바꿀 수 있다.
  • @RestController 환경에서 API 응답을 더 세밀하게 제어할 수 있다.

🧩 기본 구조

ResponseEntity<T>
  • T는 응답 본문 타입이다.
  • body가 없으면 ResponseEntity<Void> 같은 형태로도 사용할 수 있다.

🛠️ 사용 예시

200 OK 응답

@GetMapping("/users/{id}")
public ResponseEntity<UserResponseDTO> findUser(@PathVariable Long id) {
    UserResponseDTO dto = userService.findUser(id);
    return ResponseEntity.ok(dto);
}

상태 코드와 함께 반환

@PostMapping("/users")
public ResponseEntity<String> createUser(@RequestBody UserRequest request) {
    userService.createUser(request);
    return ResponseEntity.status(HttpStatus.CREATED).body("사용자 생성 완료");
}

헤더를 포함한 반환

@GetMapping("/download")
public ResponseEntity<byte[]> download() {
    byte[] file = fileService.load();

    return ResponseEntity.ok()
            .header("Content-Disposition", "attachment; filename=\"sample.txt\"")
            .body(file);
}

🔍 자주 쓰는 메서드

  • ResponseEntity.ok(...)
  • ResponseEntity.status(...)
  • ResponseEntity.created(...)
  • ResponseEntity.noContent().build()
  • ResponseEntity.badRequest().build()

✅ 장점

  • HTTP 응답을 명확하게 제어할 수 있다.
  • 성공과 실패를 코드로 구분하기 좋다.
  • 헤더와 상태 코드를 한 번에 다룰 수 있다.
  • API 설계가 명확해진다.

⚠️ 주의할 점

  • 단순한 응답까지 무조건 ResponseEntity로 감쌀 필요는 없다.
  • 응답 규칙이 지나치게 복잡해지지 않도록 기준을 정해 두는 것이 좋다.

정리

ResponseEntityAPI 응답의 형식을 표준화하고 제어할 때 유용하다. 특히 DTO와 함께 쓰면 응답 구조를 더 깔끔하게 관리할 수 있다.


연결문서

댓글남기기