Spring

Swagger - API 문서 자동화

Swagger

Swagger 는 annotation 기반의 REST API 문서를 만들어주는 프레임워크입니다.

간단하게 dependecy 를 추가하여 사용할 수 있습니다.

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>

Configration

@Configuration
@EnableSwagger2
public class Swagger2Configure implements WebMvcConfigurer {

  // Swagger SecurityConfiguration Bean 설정
  @Bean
  public SecurityConfiguration security() {
    return SecurityConfigurationBuilder.builder()
      .scopeSeparator(",")
      .additionalQueryStringParams(null)
      .useBasicAuthenticationWithAccessCodeGrant(false)
      .build();
  }

  // Swagger 설정
  @Bean
  public Docket restApi() {
    return new Docket(DocumentationType.SWAGGER_2)
      .ignoredParameterTypes(AuthenticationPrincipal.class, Pageable.class) //제외할 파라미터
      .securitySchemes(singletonList(apiKey()))  // 토큰을 읽기위한 정보를 넘겨준다
      .securityContexts(singletonList(securityContext())) // SecurityContext 를 넘겨준다
      .produces(singleton("application/json"))
      .consumes(singleton("application/json"))
      .useDefaultResponseMessages(false)
      .select()
        .apis(withMethodAnnotation(ApiOperation.class))
      .build();
  }
}

사용예

@PatchMapping(path = "user/{userId}/post/{postId}/like")
@ApiOperation(value = "해당 포스트의 like 수를 증가 - 친구의 포스트 (사용자당 하나의 like 만 가능)")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "userId", dataType = "long", value = "포스트를 등록한 유저 PK"),
    @ApiImplicitParam(name = "postId", dataType = "long", value = "포스트 대상 PK")
  })
public ApiResult<PostDto> like(
  @AuthenticationPrincipal JwtAuthentication authentication,
  @PathVariable Long userId,
  @PathVariable Long postId
) {
  return OK(
    postService.like(authentication.id, userId, postId)
      .map(PostDto::new)
      .orElseThrow(() -> new NotFoundException(Post.class, postId))
  );
}

annotation 종류

name description
@Api Swagger 리소스로 사용될 클래스를 마킹
@ApiImplicitParam Api 의 파라미터(하나)
@ApiImplicitPrams Api 의 파라미터(value ={} 로 @ApiImplicitParam 을 여러개 포함할 수 있음)
@ApiModel Swagger model 에 정보를 추가(모델 클래스)
@ApiModelProperty model 의 프로퍼티 정보
@ApiOperation http method 에 대한 api 정보
@ApiParam api 파라미터에 직접 설명을 붙임
@ApiResponse api 응답에 관한 정의
@ApiResponses api 응답에 관한 정의(value ={} 로 @ApiResponse 을 여러개 포함할 수 있음)
@Authorization 권한에 대한 설명
@AuthorizationScope oauth2 의 authorization scope에 대해 설명

확인

swagger-ui.html 에서 확인합니다

 

장점

  1. 프로젝트의 규모가 커질수록 개발과 API 문서를 동시에 작성하고, 수정사항이 생기면 반영하고 하는 것을 놓치기 쉽습니다. Swagger 는 Server 코드 내에서 annotation 기반으로 작성하기 때문에 이러한 부분들을 미연에 방지할 수 있습니다.
  2. 브라우저에서 URL 기반으로 접근하여 쉽게 테스트까지 가능하다.
  3. 클라이언트 개발자와의 협업이 용이하다.

단점

  1. API 문서 변경 이력 관리가 안된다. (버전관리시스템의 history를 볼 수 있지만 사실상 문서로는 남기기 어려운 점)
  2. 코드가 지저분해진다. 문서를 작성할 수록 annotation 으로 도배가 되어 코드가 지저분해집니다.

사실 개발을 하면서 개발에 관련된 문서를 정리하는 것이 굉장히 힘들다고 느끼고 있습니다. 여러가지 방법을 적용해보며 고민을 하고 있지만, 소규모 개발팀 + 개발자들의 의지부족 + 리더의 개선의지 없음 등이 합쳐지다보니 여러가지 방법을 도입해보는 데, 결국은 항상 혼자 문서를 작성하게 되더군요. 문서에 대한 부담감을 줄여주는 도구로서 Swagger 사용이 꽤나 도움이 된다고 생각됩니다. 저희팀에도 도입하고 싶다는 생각이 들었습니다.


참고
https://github.com/swagger-api/swagger-core/wiki/Annotations

'Spring' 카테고리의 다른 글

@RestController 와 @Controller 의 차이  (0) 2021.01.06
[setting] Root context, Servlet context 차이점  (0) 2017.07.23
[web] textarea 줄바꿈  (0) 2017.07.16