본문 바로가기
STUDY/SPRING

Swagger로 API 문서화하기

by NOTEEE 2018. 1. 22.

이번에 새로운 프로젝트를 하면서 Swagger로 API문서를 정리하기로 했다. 그래서 한번 공부를 해보려고한다. 일단 설치방법부터 

1. Maven에 추가
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
    <scope>compile</scope>
</dependency>
cs

2. 스프링부트에 Swagger 설정

@SpringBootApplication
@EnableSwagger2
public class Application extends SpringBootServletInitializer{
 
    /**
    * SwaggerEnableSwagger2  설정
    */
    @Bean
    public Docket api() {
        // 에러 리스트
        ArrayList responseMessageStatus = newArrayList( 
            new ResponseMessageBuilder().code(500).message("Error request").responseModel(new ModelRef("Error")).build(),
            new ResponseMessageBuilder().code(401).message("No permission").responseModel(new ModelRef("Error")).build(),
            new ResponseMessageBuilder().code(400).message("Invalid request").responseModel(new ModelRef("Error")).build()
        );
    return new Docket(DocumentationType.SWAGGER_2)
        .select() 
         // 현재 RequestMapping으로 할당된 모든 URL 리스트를 추출
         // .apis(RequestHandlerSelectors.none()) 사용X
        .apis(RequestHandlerSelectors.any())
         // /api/** 인 URL들만 필터링
        .paths(PathSelectors.ant("/api/**"))
        .build();
        .apiInfo(apiInfo())
        // 기본 번황 Message 설정
        .useDefaultResponseMessages(false)
        // RequestMethod 설정.
        .globalResponseMessage(RequestMethod.POST, responseMessageStatus)
        .globalResponseMessage(RequestMethod.GET, responseMessageStatus)
        .globalResponseMessage(RequestMethod.PUT, responseMessageStatus)
        .globalResponseMessage(RequestMethod.DELETE, responseMessageStatus);
    }
     
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        .title("SpringBoot REST Sample TEST Swagger")
                .contact("TEST")
                .version("0.0.1")
                .build();
    }
}
cs


3. Controller에 어노테이션을 추가

// 컨트롤러가 매핑되는 URL PATH
@Api(value = "Sample API", description = "Swagger2 테스트 API 가이드", basePath = "/")
@Controller
@RequestMapping("/api/sample")
public class TestAPIController { 
cs

4. Mapping부분 추가
// Mapping에 대한 이름 및 설명
@ApiOperation(value = "API DESC", notes = "DESC")
@ApiImplicitParams({
    @ApiImplicitParam(name = "idx", value = "parameter", required = false, dataType = "string", paramType = "query")
})
@RequestMapping(value = "/apiList" , method=RequestMethod.GET)
public @ResponseBody ResponseResult sampleList(HttpServletRequest request) throws Exception {
cs

@ApiModel, @ApiModelProperty 이용하여 활용가능


끝.



'STUDY > SPRING' 카테고리의 다른 글

@Valid  (0) 2018.07.23
SPRING LOADED 적용  (0) 2018.07.23
SPRINGBOOT CONSOLE SQL 정렬  (0) 2018.07.19
SPRING BOOT SCHDULE  (0) 2018.02.26
lombok을 이용해 Bean 간단히 하기  (0) 2018.01.22