Home Swagger
Post
Cancel

Swagger

Swagger란?

  • 만약 내가 회사에서 API를 개발하고 있다고 가정해보자. 내가 만든 API를 다른사람들에게 공유하는 방법으로 보통 API 명세서를 사용한다. 나는 노션을 사용하여 API 명세서를 작성하였고 API가 수정될때마다 명세서를 수정하였다. 어느날 깜빡하고 명세서를 수정하지 않았다. 명세서를 보고 API를 사용하던 팀원들은 오류를 만나게 될것이다.

  • 매번 API를 사용, 수정할 때마다 노션에 들어가서 명세서를 확인, 수정하는 것은 매우 번거로운 일이다. 그렇다고 부지런히 관리해주지 않으면 오류를 일으킨다. 이런 문제들을 해결할 수 있는 것이 Swagger다.

Swagger

  1. 실행 시 컨트롤러에 명시된 어노테이션을 스캔을 통해 자동으로 API 명세서를 만들어준다.
  2. 단순히 명세만 하는 것이 아닌 테스트가 가능하다. -> postman 역할 가능
  3. 컨트롤러에 Swagger 어노테이션이 많음 -> 가독성이 안좋아짐
  4. 쉽다. RestDocs에 비해 시간이 적게 걸림

순서

  1. build.gradle 설정
  2. SwaggerConfig 클래스 생성
  3. build

1. build.gradle 설정

1
2
3
dependencies {
    implementation 'io.springfox:springfox-boot-starter:3.0.0'
}

2. SwaggerConfig 클래스 생성

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
package com.sungkyul.decemberproject.Awesomely_Delicious.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableWebMvc //@EnableSwagger2 대신 사용
public class SwaggerConfig {
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sungkyul.decemberproject.Awesomely_Delicious"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Awesomely_Delicious")
                .description("API 명세서 입니다.")
                .version("0.0.1")
                .build();
    }
}

3. build

  1. gradlew 파일이 있는곳으로 이동
  2. ./gradlew clean build
  3. cd build/libs
  4. java -jar (jar파일이름).jar
  5. localhost:8080/swagger-ui/index.html으로 접속하면 명세서 확인 가능

참고

영상

블로그

This post is licensed under CC BY 4.0 by the author.