๐Ÿ“‚ JAVA/Spring

[JAVA/SPRING] API ์‘๋‹ต ๊ณตํ†ต ํฌ๋งท ๋งŒ๋“ค๊ธฐ

dhyuck 2022. 5. 6. 02:36
๋ฐ˜์‘ํ˜•

๊ฐœ๋ฐœ์„ ํ•˜๋‹ค ๋ณด๋ฉด ์ˆ˜๋งŽ์€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋˜๊ณ  ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฅ˜์— ๋Œ€ํ•ด ์ ์ ˆํ•œ HTTP Status Code๋กœ ํ•ธ๋“ค๋งํ•˜๊ธฐ๋Š” ์–ด๋ ค์›€์ด ์žˆ์Šต๋‹ˆ๋‹ค.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๊ณตํ†ต์ ์ธ ํฌ๋งท์„ ๋งŒ๋“ค๊ณ  Response status์™€ message๋กœ Request์— ๋Œ€ํ•œ ์ƒํƒœ์™€ ๋ฉ”์‹œ์ง€๋ฅผ ๋Œ๋ ค์ฃผ๋Š” ์ฝ”๋“œ๋ฅผ ๋งŒ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

  • ResponseStatus

      package com.hyuckang.springboot.utils;
    
      public enum ResponseStatus {
          SUCCESS, FAILURE, ERROR
      }
  • ResponseDto

      package com.hyuckang.springboot.web.dto;
    
      import com.hyuckang.springboot.utils.ResponseStatus;
      import lombok.AllArgsConstructor;
      import lombok.Getter;
    
      @Getter
      @AllArgsConstructor
      public class ResponseDto<T> {
          private final ResponseStatus status;
          private final String message;
          private final T data;
      }
  • ResponseUtil

      package com.hyuckang.springboot.utils;
    
      import com.hyuckang.springboot.web.dto.ResponseDto;
    
      public class ResponseUtil {
    
          public static <T>ResponseDto<T> SUCCESS (String message, T data) {
              return new ResponseDto(ResponseStatus.SUCCESS, message, data);
          }
    
          public static <T>ResponseDto<T> FAILURE (String message, T data) {
              return new ResponseDto(ResponseStatus.FAILURE, message, data);
          }
    
          public static <T>ResponseDto<T> ERROR (String message, T data) {
              return new ResponseDto(ResponseStatus.ERROR, message, data);
          }
      }
  • DemoController

      package com.hyuckang.springboot.web.controller;
    
      import com.hyuckang.springboot.utils.ResponseUtil;
      import com.hyuckang.springboot.web.dto.ResponseDto;
      import org.springframework.web.bind.annotation.*;
    
      import java.util.ArrayList;
      import java.util.List;
    
      @RestController
      public class DemoController {
    
          List<String> UserList = new ArrayList<>();
          int userLimit = 5;
    
          @GetMapping("/user")
          public ResponseDto getUsers() {
              return ResponseUtil.SUCCESS("์œ ์ € ์กฐํšŒ์— ์„ฑ๊ณตํ•˜์˜€์Šต๋‹ˆ๋‹ค.", UserList);
          }
    
          @PostMapping("/user")
          public ResponseDto addUser(@RequestBody String userName) {
              if (UserList.size() < userLimit) {
                  UserList.add(userName);
                  return ResponseUtil.SUCCESS("์œ ์ €๋ฅผ ์ถ”๊ฐ€ํ•˜์˜€์Šต๋‹ˆ๋‹ค.", null);
              }
              else
                  return ResponseUtil.ERROR("์œ ์ € ์ถ”๊ฐ€ ์ค‘ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค.", null);
          }
      }
  • ์„ฑ๊ณต ์‘๋‹ต

  • ์—๋Ÿฌ ์‘๋‹ต

๋ฐ˜์‘ํ˜•