[Spring Boot] REST API 문서를 Swagger로 관리하기

안녕하세요 명동역 델리만쥬입니다~!

실무에서 REST API를 개발할때면 API 관련 문서를 만들어야 합니다.
API의 요청, 반환 값이 변경되거나 주소 및 API 속성이 변경되었을시에 문서를
일일이 업데이트를 해줘야 하는 번거로움이 존재합니다.

이번 포스팅에서는 API관련 명세를 만들어주는 Swagger를 써보려고 합니다!~

기본 베이스
( Spring  Boot, Spring MVC, AOP, Gradle을 적용한 REST API 설계 구조 )
위의 가정 아래 시작하겠습니다!

build.gradle에 아래와 같은 설정을 해줍니다.

compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
compile("io.springfox:springfox-swagger2:2.9.2") {
    exclude module: 'swagger-annotations'
    exclude module: 'swagger-models'
}
compile("io.swagger:swagger-annotations:1.5.21")
compile("io.swagger:swagger-models:1.5.21")
cs

Swagger 기본 설정

위의 build.gradle의 설정이 끝난 후
Config 클래스를 생성해서 Swagger 기본 설정을 하려고 합니다.

Config 디렉토리에 SwaggerConfig 클래스를 생성합니다.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.study.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfo(
                "Hello REST API",
                "Some custom description of API.",
                "API TOS",
                "Terms of service",
                new Contact("명동역델리만슈""www.example.com""myeaddress@company.com"),
                "License of API""API license URL", Collections.emptyList());
    }
}
cs

api() method의 return 부분에서
apis()의 basepackage는 api를 인식하는 디렉토리를 명시해주는 것입니다.
제 프로젝트에서는 controller에서 api 경로가 분기되기때문에 이쪽으로 basepackage로
설정해두었습니다.

프로젝트 빌드한 후에 로컬호스트 경로(http://localhost:8080/swagger-ui.html)로
접속하면


위와 같이 제가 프로젝트에서 생성해둔 basepackage 하위의 api controller들이 들어와있음을 확인할 수 있습니다.


컨트롤러를 클릭하면 CRUD로 구분된 API들을 확인할 수 있습니다.



댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

SPA(Sigle Page Applications) 란 무엇인가?

안드로이드에서 당겨서 새로고침(SwipeRefreshLayout) 쉽게 구현하기

[AWS] WinSCP 를 이용해 Linux 인스턴스로 파일 전송하기