컨트롤러에서 리턴 타입으로 흔히 보는
ResponseEntity<T>
,
그냥T
만 반환하는 것과는 뭐가 다를까?
ResponseEntity<T>
는 Spring에서 HTTP 응답 전체를 커스터마이징할 수 있는 클래스다.
T는 HTTP Body에 담을 데이터 타입
상태 코드, 헤더, 본문까지 직접 제어 가능
@GetMapping
fun getAllTeams(): List<TeamResponse> {
return teamService.getAllTeams()
}
장점: 아주 간단하고 짧다
단점: 항상 200 OK로만 응답됨
→ 상태 코드 조작 불가
→ 헤더 설정 불가
@GetMapping
fun getAllTeams(): ResponseEntity<List<TeamResponse>> {
val result = teamService.getAllTeams()
return ResponseEntity.ok(result)
}
또는
@PostMapping
fun createTeam(@RequestBody request: TeamCreateRequest): ResponseEntity<Long> {
val id = teamService.createTeam(request)
return ResponseEntity.status(HttpStatus.CREATED).body(id)
}
상황 | 써야 하나? | 이유 |
---|---|---|
상태 코드를 바꿔야 할 때 | ✅ | 201, 204, 400 등 직접 지정 가능 |
응답 헤더를 조작해야 할 때 | ✅ | 예: CORS, 쿠키, Location 헤더 |
API 명세를 깔끔하게 유지하고 싶을 때 | ✅ | 명시적으로 어떤 응답인지 드러남 |
그냥 단순한 조회용 (200 OK만) | ❌ 가능 | 편의상 생략 가능 |
표현 | 의미 |
---|---|
ResponseEntity<T> | 응답 body에 T를 담고 상태코드/헤더 조작 가능 |
ResponseEntity<List<TeamResponse>> | body에 팀 리스트를 담고 상태코드 제어 가능 |
ResponseEntity<Void> | body 없이 상태코드만 응답 (204 No Content 등) |