[Swagger] swagger를 간단하게 사용해보기

박솔찬·2021년 9월 6일
0

RestAPI Docs

목록 보기
1/1
post-thumbnail

Rest API 개발 문서 자동화의 필요성을 느끼게 되었고, swagger을 사용해보기로 하였다. 간단한 로그인과 권한이 필요한 URI 정도로 프로젝트를 구성하여 swagger를 적용해보자.

간단한 프로젝트는 기존 Redis와 JWT에서 진행하였던 프로젝트를 기반으로 진행하였다.

스웨거 적용해보기

스웨거를 적용하기에 앞서 다음의 라이브러리를 받아야 한다.

build.gradle에 추가해준다.

// [SWAGGER-1]
compileOnly group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
compileOnly group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'

SwaggerConfig

swagger를 사용하기 위해 스프링 컨테이너에 설정을 등록해야 한다.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    private String version; // API 버전
    private String title; // API 설명

    @Bean
    public Docket apiV1() {
        version = "V1";
        title = "Sol SpringBoot API " + version;

        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(AuthenticationPrincipal.class) // @AuthenticationPrincipal의 파라미터 요구 필드를 없애기 위함!
                .useDefaultResponseMessages(false)
                .groupName(version)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springbootswagger"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo(title, version));
    }

    private ApiInfo apiInfo(String title, String version) {
        return new ApiInfo(
                title,
                "Swagger로 생성한 API Docs",
                version,
                "www.example.com",
                new Contact("Contact Me", "www.example.com", "foo@example.com"),
                "Licenses",

                "www.localhost:8080",

                new ArrayList<>());
    }
}

Doket을 만들어 컨테이너에 등록한다.

  1. ignoredParameterTypes: @ AuthenticationPrincipal 어노테이션을 사용하면서 해당 API에 요청 param으로 요구되어 이를 무시하기 위한 설정이다.
  2. useDefaultResponseMessages: swagger에서 기본적으로 제공하는 응답 메세지 사용 여부를 설정한다.
  3. groupName: 그룹 이름을 설정한다.
  4. select: ApiSelectorBuilder instance를 반환한다.
  5. apis: swagger로 만들어질 API들이 존재하는 package 경로이다.
  6. paths: apis()로 선택되어진 API중 특정 path 조건에 맞는 API들을 다시 필터링하여 문서화 한다..
  7. apiInfo: 제목, 설명 등 문서에 대한 정보들을 보여주기 위해 호출한다.

Domain 설정

아래는 UserDTO의 일부이다.

@ApiModelProperty(value = "이메일", example = "solchan@hello.swagger",required = true)
private String email;
@ApiModelProperty(value = "비밀번호", example = "swagger123", required = true)
private String password;

@ApiModelProperty를 통해 각 변수마다 설정한다.
value: 변수에 대한 간략한 설명.
required: 필수 요소
example: 예시

다른 DTO 등 도메인에도 같은 방식으로 적용하면 된다.

Controller 설정

아래는 UserController의 일부이다.

// 나의 정보 조회
@ApiOperation(value = "나의 정보 조회", notes = "나의 정보 조회하기")
@ApiResponses({
        @ApiResponse(code = 500, message = "서버에서 문제가 발생하였습니다.")})
@ApiImplicitParams({
        @ApiImplicitParam(name = "authorization", value = "authorization", required = true,
                dataType = "string", paramType = "header"),
        @ApiImplicitParam(name = "refreshToken", value = "refreshToken", required = true,
                dataType = "string", paramType = "header")
})
@GetMapping("/profile")
public UserDTO test(@AuthenticationPrincipal User user) {
    return userService.getProfile(user);
}
  1. @ApiOperation: 메서드의 정보를 정의한다.
    1. value: 간략한 메서드 정보
    2. notes: 상세한 메서드 정보
  2. @ApiResponses: 응답 형식의 모음
    1. ApiResponse: 응답 형식
      1. code: 응답 코드
      2. message: 응답 메세지
  3. @ApiImplicitParams: 요청 인자의 모음
    1. ApiImplicitParam: 요청 인자 정보
      1. name: key값
      2. value: 간략한 설명
      3. required: 필수 여부

authorization과 refreshToken 요청을 글로벌로 설정하고 싶었지만 아무리 적용해도 막상 요청시에는 헤더에 포함되지가 않았다..
방법을 좀 더 찾아보기로..

profile
Why? How? What?

0개의 댓글