Java에서 일관된 API 응답을 위한 유틸 클래스 만들기
RESTful API를 설계할 때 가장 중요한 요소 중 하나는 일관된 응답 형식입니다. 클라이언트는 API 응답이 일정한 구조를 가지고 있어야 성공과 실패를 쉽게 구분할 수 있으며, 이는 디버깅과 유지보수를 더욱 간단하게 만듭니다. 이 글에서는 Java에서 통합된 응답 형식을 제공하기 위해 작성한 유틸리티 클래스를 소개하고, 이를 통해 API의 일관성을 어떻게 유지할 수 있는지 살펴보겠습니다.
설계 목표
유틸 클래스의 설계 목표는 다음과 같습니다:
- 성공과 실패에 대해 통합된 응답 형식 제공
- 클라이언트는 성공(
success
) 또는 실패(error
) 여부를 예측할 수 있어야 합니다.
- 클라이언트는 성공(
- 간결한 에러 메시지 전달
- 예외 처리 시 명확한 에러 메시지를 반환하여 클라이언트와의 원활한 소통을 지원합니다.
- 재사용 가능한 구조
- 여러 컨트롤러에서 반복적으로 사용 가능한 공통 로직을 제공하여 코드 중복을 줄입니다.
유틸 클래스 설계
아래는 작성된 ApiResponseUtil
클래스의 주요 구현입니다:
1. ApiResponseUtil
의 역할
- 성공 응답 생성: 데이터를 포함한 성공적인 응답 객체를 반환합니다.
- 실패 응답 생성: 예외 또는 메시지를 기반으로 에러 객체를 포함한 응답을 반환합니다.
2. 주요 메서드
success
: 성공 응답 객체 생성error
: 예외나 메시지를 기반으로 에러 응답 생성
package com.sparta.gaeppa.global.util;
import lombok.Getter;
public class ApiResponseUtil {
public static <T> ApiResult<T> success(T response) {
return new ApiResult<>(true, response);
}
public static ApiResult<ApiError> error(Throwable throwable) {
return new ApiResult<>(false, new ApiError(throwable));
}
public static ApiResult<ApiError> error(String message) {
return new ApiResult<>(false, new ApiError(message));
}
@Getter
public static class ApiError {
private final String message;
ApiError(Throwable throwable) {
this(throwable.getMessage());
}
ApiError(String message) {
this.message = message;
}
}
public static class ApiResult<T> {
private final boolean success;
private final T response;
public ApiResult(boolean success, T response) {
this.success = success;
this.response = response;
}
public boolean isSuccess() {
return success;
}
public T getResponse() {
return response;
}
}
}
활용 예제
아래는 컨트롤러에서 ApiResponseUtil
을 사용하여 성공 및 실패 응답을 처리하는 예제입니다:
컨트롤러 코드
@GetMapping
public ResponseEntity<ApiResult<StoreProductListResponseDto>> getProducts(@RequestParam("storeid") UUID storeId) {
try {
StoreProductListResponseDto responseDto = productService.getAllProductsByStoreId(storeId);
return new ResponseEntity<>(ApiResponseUtil.success(responseDto), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(ApiResponseUtil.error(e), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
코드 설명
- 성공 시:
productService
에서 데이터를 받아 성공 응답 객체를 생성합니다. - 실패 시: 예외 객체를
ApiResponseUtil.error
메서드에 전달해 실패 응답 객체를 반환합니다. - 클라이언트는 항상
success
와response
필드를 포함한 일관된 구조를 수신합니다.
결론
ApiResponseUtil
클래스는 API 응답 형식을 표준화하여 클라이언트와 서버 간의 통신을 명확하게 합니다. 이를 통해 개발자는 일관된 코드를 유지할 수 있으며, 클라이언트는 예측 가능한 응답 구조를 통해 개발 생산성을 높일 수 있습니다.
이 유틸리티 클래스를 활용해 프로젝트에 안정성과 가독성을 더해보세요!
'Study > SPRING' 카테고리의 다른 글
[SPRING BOOT] Swagger 설정하기 (핵심만 간단히) (0) | 2025.04.12 |
---|---|
[SPRING BOOT] QueryDSL 설정하기 (0) | 2025.04.12 |
[SPRING BOOT] 전역 예외 처리 핸들러 및 Enum 으로의 관리 (0) | 2025.04.12 |
[SpringBoot] Entity의 생성자 범위 (0) | 2025.04.12 |
Dto 와 Entity 간의 데이터 이동 (0) | 2025.04.12 |