백엔드/Spring

[Swagger] 스웨거(Swagger) Annotation, Validation

능이개발자 2024. 2. 28. 09:35
728x90

 

잘 작성된 API 문서는 작업의 시간과 테스트 시간을 줄여주기 때문에 효율을 극대화시킬 수 있다.

API 문서를 작성할 때 Swagger를 사용한다면 간편하게 문서를 작성할 수 있어 좋은 프레임워크로 평가 받고 있다.

이번 포스팅에서는 Swagger의 Annotation을 이용하여 API 문서의 설명을 구체화하고, Java Bean Validation을 이용하여 API 사용 시 유효성 체크에 관한 내용을 다뤄보고자 한다.

 

 

1) API 그룹 : @Tag


Tag에 설정된 name이 같은 것 끼리 하나의 api 그룹으로 묶는다.

@Tag(name = "member", description = "회원 API")
public class MemberController {
  • name : 태그의 이름
  • description : 태그의 설명

 

 

2) API 정보 : @Operation


 

API 동작에 대한 명세를 작성하기 위해 설정한다.

@GetMapping(path = "/list")
@Operation(summary = "MemberApi 목록 요청", description = "MemberApi 목록을 조회합니다.")
public ChamomileResponse<Page<MemberVO>> getMemberList(MemberQuery memberQuery, Pageable pageable) {
    Page<MemberVO> results = memberService.getMemberList(memberQuery, pageable);
    return new ChamomileResponse<>(results);
}
  • summary : API에 대한 요약
  • description : API 대한 상세 설명
  • response : Response 리스트
  • parameters : Parameter 리스트

 

 

3) API Schema 설정 : @Schema


@Schema(description = "게시물 리스트 응답DTO")
@Getter
public class PostsListResponseDto {
    @Schema(description = "일자")
    private Long id;

    @Schema(description = "게시물 제목", defaultValue = "디폴트 제목", allowableValues = {"게시물1", "게시물2"})
    private String title;

    @Schema(description = "내용")
    private String content;

    @Schema(description = "수정일자")
    private LocalDateTime modifiedDate;

    public PostsListResponseDto(Posts posts) {
        this.id = posts.getId();
        this.title = posts.getTitle();
        this.content = posts.getContent();
        this.modifiedDate = posts.getModifiedDate();
    }
}
  • description : 컬럼 명
  • example : 예제 값
  • defaultValue : 기본값
  • allowbleValues : 허용값
  • accessMode : 접근모드
    • Schema.AccessMode.AUTO : 자동
    • Schema.AccessMode.READ_ONLY : 읽기 전용
    • Schema.AccessMode.WRITE_ONLY : 쓰기 전용
    • Schema.AccessMode.READ_WRITE : 읽기쓰기 전용

4) API Response 설정 : @ApiResponse


@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "게시글 조회 성공", content = @Content(schema = @Schema(implementation = PostsResponseDto.class))),
        @ApiResponse(responseCode = "404", description = "존재하지 않는 리소스 접근", content = @Content(schema = @Schema(implementation = ErrorResponse.class))) })
@Operation(summary = "게시글 조회", description = "id를 이용하여 posts 레코드를 조회합니다.")
@GetMapping("/posts/{id}")
public PostsResponseDto findById(@PathVariable Long id) {
    return postsService.findById(id);
}
  • responseCode : HTTP 상태 코드
  • description : Response에 대한 설명
  • content : Response payload 구조
    • schema : payload에서 이용하는 Schema
    • hidden : Schema 숨김 여부
    • implementation : Scema 대상 클래스

 

5) API Parameter 설정 : @Parameter


@GetMapping("/posts/{id}")
public PostsResponseDto findById(@Parameter(name = "id", description = "posts 의 id", in = ParameterIn.PATH)
                                        @PathVariable Long id) {
    return postsService.findById(id);
}
  • name : 파라미터 명
  • description : 파라미터 설명, 문자열로 작성
  • required: 필수/선택 여부 (true이면 필수, false이면 선택이다)
  • in : 파라미터 타입
    (Value = { ParameterIn.QUERY : 요청 쿼리 파라미터이다.
                  , ParameterIn.HEADER : 요청 헤더에 전달되는 파라미터이다.
                  ,  ParameterIn.PATH : PathVariable에 속하는 파라미터이다.
                  , ParameterIn.COOKIE : PathVariable에 속하는 파라미터이다
                  , 값 없음 : RequestBody에 해당하는 객체 타입의 파라미터이다. } )
반응형