1. 개요

REST API 설계 및 문서화 등에 유용하게 사용되는 Swagger에 대해 소개하고, Spring Boot에 적용하여 REST API를 문서화하는 예제를 소개한다.


2. Swagger란

Swagger(스웨거)는 개발자가 REST API 서비스를 설계, 빌드, 문서화할 수 있도록 하는 프로젝트이다.

Swagger는 다음과 같은 경우에 유용하게 사용된다.

  • 다른 개발팀과 협업을 진행할 경우
  • 이미 구축되어있는 프로젝트에 대한 유지보수를 진행할 경우
  • 백엔드의 API를 호출하는 프론트엔드 프로그램을 제작할 경우

기능

  • API 디자인
  • API 빌드
  • API 문서화
  • API 테스팅
  • API 표준화

장점

  • API 정보 현행화 가능
  • API를 통해 Parameter, 응답 정보, 예제 등 Spec 정보 전달이 용이함
  • 실제 사용되는 Parameter로 테스트 가능

Swagger Tool 종류

  • Swagger Codegen : Swagger로 정의된대로 클라이언트/서버 코드를 생성하는 CLI 툴이다.
  • Swagger UI : Swagger UI는 Swagger API 명세서를 HTML 형식으로 확인할 수 있는 툴이다.
  • Swagger Editor : Swagger 표준에 따른 API 설계서/명세서를 작성하기 위한 에디터이다.

3. Spring Boot에 Swagger UI 적용하기

Swagger UI를 적용하여 Spring Boot에서 사용하고 있는 REST API를 문서화할 수 있다.

1) pom.xml에 의존성 추가

   <dependencies>
       <!-- Swagger -->
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger2</artifactId>
           <version>2.9.1</version>
       </dependency>
       <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger-ui</artifactId>
           <version>2.9.1</version>
       </dependency>
   </dependencies>

· 버전이 변경될 수 있으므로, https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui에서 최신 버전을 확인한다.

2) Swagger Config 클래스 작성

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
​
import java.util.ArrayList;
import java.util.Collections;
​
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
​
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any()) // 현재 RequestMapping으로 할당된 모든 API 리스트
                .paths(PathSelectors.any()) // 모든 API 참조
                .build();
    }
}

Spring Boot를 실행한 후, http://localhost:8080/<**루트 컨텍스트>/swagger-ui.html로 접속하여 swagger UI가 적용된 것을 확인한다.

API의 정보를 확인하거나, Try it out 버튼을 사용해 API를 테스트할 수 있다.