스웨거 2.0으로 스프링 부트 어플리케이션 API 문서화하기

Usage of Swagger 2.0 in Spring Boot Applications to document APIs

(원문링크: http://heidloff.net/article/usage-of-swagger-2-0-in-spring-boot-applications-to-document-apis/)

IBM VP인 엔젤 디아즈(Angel Diaz)는 SearchCloudComputing의 인터뷰에서 "스웨거Swagger는 대부분의 개발자가 [REST] API를 그려내는 방식"이라고 인용하였다. 2.0버젼에서 확장성과 같은 많은 중요한 기능이 추가되었고 큰 커뮤니티와 많은 개발자들이 이제 이것을 사용하고 있다. 추가적으로 Open API Initiative의 일부로서 리눅스 재단하에 스웨거의 명세서가 열린 정부 모델로서 만들어지고 있다.

내가 스웨거에 대해 가장 좋아하는 부분은 (자바) 소스코드내에서 어노테이션을 통해 직접 API를 문서화할 수 있다는 것이다. 이를 통해 문서와 실제 API는 항상 동기화되어있다.

IBM은 몇몇의 제품과 서비스의 API 문서화를 위해 내부적으로 스웨거를 사용한다. 더나아가 IBM Bluemix의 API관리서비스가 당신의 API를 손쉽게 관리하기 위해 스웨거 2.0 정의를 가지고 온다.

자바 스프링 프레임워크는 엔터프라이즈 커뮤니티안에 수많은 견인장치들을 가지고 있다. 스프링 부트 어플리케이션에서 스웨거를 사용하려고 나는 스프링폭스Springfox를 썼는데 이는 스웨거 코어의 일부는 아니지만 스프링안에서 아주 나이스하게 통합되어있으며 코어 스웨거 어노테이션을 지원한다.

아래는 스웨거 어노테이션을 사용하여 스프링 예제인 Building a RESTful Web Service를 확장한 것이다.

먼저 당신은 스프링폭스와 스웨거 라이브러리 의존성을 정의해야한다. 아래의 경우 메이븐을 사용하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.springframework</groupId>
    <artifactId>gs-rest-service</artifactId>
    <version>0.1.0</version>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RELEASE</version>
    </parent>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
     
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>
 

그 다음 스프링 부트 어플리케이션에 스웨거를 enable하였다:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package hello;
 
import static springfox.documentation.builders.PathSelectors.regex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.google.common.base.Predicate;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
@SpringBootApplication
@EnableSwagger2
@ComponentScan("hello")
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
     
    @Bean
    public Docket newsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("greetings")
                .apiInfo(apiInfo())
                .select()
                .paths(regex("/greeting.*"))
                .build();
    }
     
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring REST Sample with Swagger")
                .description("Spring REST Sample with Swagger")
                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
                .contact("Niklas Heidloff")
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
                .version("2.0")
                .build();
    }
}

컨트롤러에서는 API 문서화를 위해 스웨거 어노테이션을 사용하였다:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package hello;
 
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader;
 
@RestController
public class GreetingController {
 
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
 
    @ApiOperation(value = "getGreeting", nickname = "getGreeting")
    @RequestMapping(method = RequestMethod.GET, path="/greeting", produces = "application/json")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "name", value = "User's name", required = false, dataType = "string", paramType = "query", defaultValue="Niklas")
      })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success", response = Greeting.class),
            @ApiResponse(code = 401, message = "Unauthorized"),
            @ApiResponse(code = 403, message = "Forbidden"),
            @ApiResponse(code = 404, message = "Not Found"),
            @ApiResponse(code = 500, message = "Failure")})
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                String.format(template, name));
    }
}

이 예제 리소스에서 파라메터들을 문서화하였다:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package hello;
 
import com.fasterxml.jackson.annotation.JsonProperty;
 
import io.swagger.annotations.ApiModelProperty;
 
public class Greeting {
 
    private final long id;
    private final String content;
 
    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }
 
    public long getId() {
        return id;
    }
 
    @JsonProperty(required = true)
    @ApiModelProperty(notes = "The name of the user", required = true)
    public String getContent() {
        return content;
    }
}

이제 API explorer에서 결과물을 보자:

swaggerspring

 



출처: http://springboot.tistory.com/23 [스프링부트는 사랑입니다]

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
126 Creating a CRUD REST API/Service with Spring Boot, JPA and Hibernate file 졸리운_곰 2018.08.17 120
125 Spring boot에서 REST API 개발 시작해보기 file 졸리운_곰 2018.08.17 318
124 [JSP] 네이버 스마트 에디터 연동 + 이미지파일 업로드 기능 추가 file 졸리운_곰 2018.07.28 1060
123 Use React and Spring Boot to Build a Simple CRUD App file 졸리운_곰 2018.07.28 354
122 JSP CRUD Example jsp 기본예제 file 졸리운_곰 2018.07.28 131
» 스웨거 2.0으로 스프링 부트 어플리케이션 API 문서화하기 file 졸리운_곰 2018.05.24 101
120 Spring REST API 문서를 Swagger로 만들자 file 졸리운_곰 2018.05.22 374
119 Spring REST API에 Swagger 2 설정하기 file 졸리운_곰 2018.05.22 300
118 Spring Boot와 AngualrJS를 조합한 코드 자동 생성 도구(scaffolding) file 졸리운_곰 2018.05.17 107
117 Spring java Code 기반 설정 Configuration 어노테이션과 Bean 어노테이션 졸리운_곰 2018.05.14 48
116 java spring redis 세션 공유 : Spring Session을 이용한 세션 클러스터링 졸리운_곰 2018.05.06 989
115 Spring MVC hello world example file 졸리운_곰 2018.05.04 180
114 Create a Web Application With Spring Boot file 졸리운_곰 2018.05.03 104
113 Spring Boot and JSP Tutorial file 졸리운_곰 2018.05.03 400
112 Spring Boot Hello World Example – JSP file 졸리운_곰 2018.05.03 90
111 Spring Boot – JSP View Example file 졸리운_곰 2018.05.03 110
110 SpringMVC-JSP 프로젝트를 Spring Boot로 옮기기 file 졸리운_곰 2018.05.03 272
109 SPRING BOOT에서 JSP 사용하기 졸리운_곰 2018.05.03 34
108 MYBATIS 기본 - SELECTLIST file 졸리운_곰 2018.03.26 53
107 Spring MVC 에 MyBatis 적용해 보기. file 졸리운_곰 2018.03.26 60
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED