menuhwang

[Spring Boot] Swagger : API 명세 본문

스터디/Spring

[Spring Boot] Swagger : API 명세

menuhwang 2022. 8. 23. 14:59

Swagger


API 제작 후 사용방법을 모르면 올바른 접근, 사용이 불가능하다.

그래서 API 사용방법 즉, API 명세서를 작성해주어야 한다.

 

아래는 배틀그라운드의 API Document이다.

Swagger는 이런 명세서를 간단하게 작성해준다.

 

 

적용


Dependency 추가

먼저 Swagger를 사용하기 위해 Dependency를 추가해준다.

 

이 글에서는 Swagger2 3.0.0 버전과 Swagger-ui 3.0.0 버전을 사용한다.

* 많이 사용되는 2.9.2 버전과는 설정에 있어서 조금 차이가 있다.

 

Gradle

implementation 'io.springfox:springfox-boot-starter:3.0.0'

 

Maven

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

 

https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter/3.0.0

 

springfox-boot-starter 안에 Swagger2와 Swagger-ui를 포함한 필요한 라이브러리들이 존재한다.

 

 

Configuration 생성

 

다음으로 Configuration를 작성한다.

 

configuration 파일은 따로 config라는 패키지를 생성해서 작성해주었다.

 

SwaggerConfig.java

@Configuration
@EnableWebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.menuhwang.My"))
                .paths(PathSelectors.any())
                .build();
    }
}

 

접속

 configuration 파일까지 작성한 후 application을 실행하고, http://localhost:8080/swagger-ui/index.html 로 접속하면 깔끔한 API 명세 페이지를 만날 수 있다.

* 2.9.2 버전의 경우 http://localhost:8080/swagger-ui.html 로 접속 가능하다.

 

 작성한 API 도 테스트해 볼 수 있으며, curl 스크립트도 알아서 작성해준다.

 

 

 

설정


페이지 기본 정보 설정

 

변경 전

먼저, UI의 제목과 설명, 버전들을 설정해보자.

 

SwaggerConfig.java

@Configuration
@EnableWebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
        		.apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.menuhwang.My"))
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My Application API Document")
                .description("My Application API 명세서입니다.")
                .version("alpha 1.0.0")
                .build();
    }
}

 

Docket에. apiInfo()를 추가해주고 인자로 ApiInfo를 넣어준다.

 

ApiInfo는 ApiInfoBuilder로 생성해준다.

 

Docket.apis(RequestHandlerSelectors.basePackage()) 는 스캔할 패키지 범위를 설정한다.

 

변경 후

 

 

그 외 ApiInfo 설정

 

  • contact() : 연락처 설정

SwaggerConfig.java

// ...
private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("My Application API Document")
            .description("My Application API 명세서입니다.")
            .version("alpha 1.0.0")
            .contact(new Contact("menu-Hwang", "https://test.com", "menu@test.com"))
            .build();
}
// ...

 

  • license()
  • termsOfServiceUrl()

등 추가적으로 설정해줄 수 있다.

 

 

 

세부 설명


이번에는 컨트롤러 메서드에 세부 설명을 설정해보자.

 

MyController.java

@RestController
@RequestMapping("/api")
public class MyController {
	// ...
    @ApiOperation(value = "PathVariable 예제", notes = "@PathVariable을 사용한 예제")
    @GetMapping(value = "/hello1/{name}")
    public String hello1(@ApiParam(value = "이름", required = true) @PathVariable("name") String userName) {
        return "Hello-1, " + userName;
    }
    // ...
}

 

@ApiOperation 어노테이션은 메서드 이름과 설명을 설정해줄 수 있다.

 

@ApiParam 어노테이션으로 파라미터의 설명과 필요 여부를 설정할 수 있다.

 

변경 전
변경 후

 

 

DTO 설정

DTO 필드에도 설정을 해줄 수 있다.

@ApiModel(value = "회원정보")
public class MyDTO {
    @ApiModelProperty(value = "이름")
    @ApiParam(value = "이름", required = true)
    private String name;
    @ApiModelProperty(value = "나이")
    @ApiParam(value = "나이", required = true)
    private Integer age;
	// ...
}

 

 

Comments