@Tag = api 그룹 설정
Open API 3.0 Swagger v3
Target: ANNOTATION_TYPE, METHOD, TYPE
- name: 태그의 이름
- description: 태그에 대한 설명
Tag에 설정된 name이 같은 것 끼리 하나의 api 그룹으로 묶는다. 주로 Controller나 Controller의 Method 영역에 설정한다.
@Tag(name = "posts", description = "게시물 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/")
public class PostsApiController {
    ...@Schema = api Schema 설정
Open API 3.0 Swagger v3
Target : ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE
- description : 한글명
- defaultValue : 기본값
- allowableValues :
Schmea(= Model)에 대한 정보를 작성하는 곳이다. Schema를 설정할 시, 더욱 완성도 높은 Swagger UI 문서를 만들 수 있다.
@ApiOperation = Method 설명
@ApiOperation으로 해당 Controller 안의 method의 설명을 추가 할 수 있다.
 @ApiOperation(
        value = “사용자 정보 조회”
        , notes = “사용자의 ID를 통해 사용자의 정보를 조회한다.”)
    @GetMapping(“/user/{id}”)
    @ResponseBody
    public UserDTO getUser(@PathVariable(name = “id”) String id) {
        return userService.findUserInfoById(id);
    }@ApiImplicitParam = Request Parameter 설명
@ApiImplicitParam Annotation으로 해당 API Method 호출에 필요한 Parameter들의 설명을 추가할 수 있다.
 @ApiOperation(
        value = "사용자 정보 조회"
        , notes = "사용자의 ID를 통해 사용자의 정보를 조회한다.")
    @ApiImplicitParam(
        name = "id"
        , value = "사용자 아이디"
        , required = true
        , dataType = "string"
        , paramType = "path"
        , defaultValue = "None")
    @GetMapping("/user/{id}")
    @ResponseBody
    public UserDTO getUser(@PathVariable(name = "id") String id) {
        return userService.findUserInfoById(id);
    }dataType, paramType, required의 경우 해당 name의 정보가 자동으로 채워지므로 생략 할 수 있다.
paramType의 경우 @RequestParam은 query를, @PathVariable은 path를 명시해주면 된다.
만약 해당 Method의 Parameter가 복수일 경우, @ApiImplictParams로 @ApiImplictParam을 복수개 사용할 수 있다.
 @ApiOperation(
        value = "자격증 정보 조회"
        , notes = "자격증의 ID를 통해 자격증의 정보를 조회한다.")
    @ApiImplicitParams(
        {
            @ApiImplicitParam(
                name = "id"
                , value = "자격증 아이디"
                , required = true
                , dataType = "string"
                , paramType = "path"
                , defaultValue = "None"
            )
        ,
            @ApiImplicitParam(
                name = "fields"
                , value = "응답 필드 종류"
                , required = false
                , dataType = "string"
                , paramType = "query"
                , defaultValue = ""
            )
        })
    @GetMapping("/licenses/{id}")
    @ResponseBody
    public UserDTO getLicense(@PathVariable(name = "id") String id, @RequestParam(name = "fields", required = false) String fields) {
        return userService.findUserInfoById(id);
    }@ApiResponse = Reponse 설명
@ApiResponse Annotation으로 해당 method의 Response에 대한 설명을 작성할 수 있다.
@ApiResponse(
        code = 200
        , message = "성공입니다."
    )
    @GetMapping("/notices/{id}")
    public String getNotice() {
        return "notice";
    }복수개의 Response에 대한 설명을 추가 하고 싶다면,@ApiResponses를 사용하면 된다.
 @ApiResponses({
        @ApiResponse(code = 200, message = "성공입니다.")
        , @ApiResponse(code = 400, message = "접근이 올바르지 않습니다.")
    })
    @GetMapping("/notices/{id}")
    public String getNotice() {
        return "notice";
    }Default Response Message들을 삭제하고 싶다면,
Swagger Config에 Docket에 useDefaultResponseMessages(false)를 설정해주면 된다.

@Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .consumes(getConsumeContentTypes())
                .produces(getProduceContentTypes())
                .useDefaultResponseMessages(false)
                .apiInfo(getApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.bng.ddaja"))
                .paths(PathSelectors.ant("/**"))
                .build();
    }useDefaultResponseMessages(false)를 설정해주면,
@ApiResponse로 설명하지 않은401, 403, 404 응답들이 사라진다.
@ApiParam = DTO field 설명
@ApiParam Annotation으로 DTO의 field에 대한 설명을 추가할 수 있다.
@ApiResponses({
        @ApiResponse(code = 200, message = "성공입니다.")
        , @ApiResponse(code = 400, message = "접근이 올바르지 않습니다.")
    })
    @GetMapping("/notices/{id}")
    public String getNotice(UserDTO userDTO) {
        return "notice";
    }
    
@Getter
@Setter
@NoArgsConstructor
public class UserDTO {
    
    @ApiModelProperty(
        name = "id"
        , example = "gillog"
    )
    @ApiParam(value = "사용자 ID", required = true)
    private String id;
    @ApiParam(value = "사용자 이름")
    private String name;
    @ApiParam(value = "token 갱신 값")
    private String tokenRefresh;
}@ApiModelProperty = DTO 예제 설명
@ApiModelProperty Annotation을 사용하는 DTO Class Field에 추가하면, 해당 DTO Field의 예제 Data를 추가할 수 있다.
아래의 옵션을 부가적으로 설정 해주면 훨씬 더 명확하게 model에 대한 Docs가 표현되고 테스트 값으로 임의로 활용할 수 있습니다.
설명(값), 이름, 데이터 유형, 예제 값 및 모델 속성에 허용되는 값과 같은 Swagger 관련 정의를 제어할 수 있습니다.
또한 특정 시나리오에서 속성을 숨기려는 경우 추가 필터링 속성을 제공합니다.
- value - 파라메터 이름
- name - Swagger에서 입력 받을 리얼 파라메터 명 (생략가능)
- notes - 부가설명
- example - 지정된 임의 테스트 값을 입력 함
- required - 필수 입력 여부
@Getter
@Setter
@NoArgsConstructor
public class UserDTO {
    
    @ApiModelProperty(
        name = "id"
        , example = "gillog"
    )
    @ApiParam(value = "사용자 ID", required = true)
    private String id;
    
    @ApiModelProperty(example = "길로그")
    @ApiParam(value = "사용자 이름")
    private String name;
}@ApiIgnore = Swagger UI 상 무시
@ApiIgnore을 추가함으로써, @ApiImplictParam으로 선언하지않은 parameter 정보들을 무시할 수 있다.
해당 method getNotice에서는 UserDTO의 id 만 필요한 상황
 @ApiResponses({
        @ApiResponse(code = 200, message = "성공입니다.")
        , @ApiResponse(code = 400, message = "접근이 올바르지 않습니다.")
    })
    @ApiImplicitParam(
        name = "id"
        , value = "사용자 아이디"
        , required = true
        , dataType = "string"
        , paramType = "path"
        , defaultValue = "None")
    @GetMapping("/notices/{id}")
    public String getNotice(@ApiIgnore UserDTO userDTO) {
        return "notice";
    }method의 return type 앞에 명시해 해당 method를 아예 Swagger UI 에서 노출되지 않게도 할수 있다.
@ApiResponses({
        @ApiResponse(code = 200, message = "성공입니다.")
        , @ApiResponse(code = 400, message = "접근이 올바르지 않습니다.")
    })
    @ApiImplicitParam(
        name = "id"
        , value = "사용자 아이디"
        , required = true
        , dataType = "string"
        , paramType = "path"
        , defaultValue = "None")
    @GetMapping("/notices/{id}")
    public @ApiIgnore String getNotice(UserDTO userDTO) {
        return "notice";
    }swagger 2 -> 3 어노테이션 변경
- @Api → @Tag
- @ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
- @ApiImplicitParam → @Parameter
- @ApiImplicitParams → @Parameters
- @ApiModel → @Schema
- @ApiModelProperty(hidden = true) → @Schema(accessMode = READ_ONLY)
- @ApiModelProperty → @Schema
- @ApiOperation(value = "foo", notes = "bar") → @Operation(summary = "foo", description = "bar")
- @ApiParam → @Parameter
- @ApiResponse(code = 404, message = "foo") → @ApiResponse(responseCode = "404", description = "foo")
연관된 글 :
[Spring] 스웨거 (Swagger) v3 설정하기
[Spring] DTO(Data Transfer Object)
참고:
REST API Response Format, 응답 객체는 어떤 형식이 좋을까?
v2
Swagger의 @ApiOperation VS @ApiResponse
[Swagger] @ApiResponse response = Response.Class 설정해도 응답 Class 적용 안되는 에러 해결
스웨거 @ApiParam VS @ApiModelProperty
[API documentation 자동화] spring boot swagger UI 적용 방법
v3
[Spring] OpenApi 3.0 Swagger Springdoc 적용
[Swagger] Open API 3.0 Swagger v3 상세설정
'개발 > Spring' 카테고리의 다른 글
| [Springboot]Springboot 3.x에 Swagger (0) | 2024.06.06 | 
|---|---|
| [Spring] 스웨거 (Swagger) v3 설정하기 (0) | 2023.04.30 | 
| [Spring] 빌더 패턴(Bulider Pattern) (0) | 2023.04.28 | 
| [Spring] 스프링 프로젝트 구조 (DTO, Entity and Mapper) (0) | 2023.04.28 | 
| [Spring] 스웨거 (Swagger) 설정하기 (0) | 2023.04.27 | 
