API는 개발 과정에서 계속 변경되므로 작성한 명세 문서도 주기적인 업데이트가 필요하다. 명세 작업은 번거롭고 시간이 오래 걸리는데, 이를 해결해주는 것이 ‘Swagger’ 라는 오픈소스 프로젝트이다.
Swagger를 사용하기 위해서는 먼저 pom.xml 파일에 의존성을 추가해야 한다.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.api"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Spring Boot Open API Test with Swagger")
.description("설명 부분")
.version("1.0.0")
.build();
}
}
GetController
@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {
//http://localhost:8080/api/v1/get-api/request1?name=value1&email=value2&organization=value3
@ApiOperation(value ="GET 메소드 예제", notes = "@RequestParam을 활용한 GET Method")
@GetMapping(value="/request1")
public String getRequestParam(
@ApiParam(value = "이름", required = true)@RequestParam String name,
@ApiParam(value = "이메일", required = true)@RequestParam String email,
@ApiParam(value = "회사", required = true)@RequestParam String organization
)
{
return name + " " + email + " " + organization;
}
}
해당 API가 무엇인지 설명, 어떤 값이 필요한지 보여줌
try버튼 클릭 후 각 항목의 값 기입 > Execute버튼 클릭
자동으로 완성된 요청된 URL, 결과값 확인 가능
@ApiOperation: 대상 API의 설명을 작성하기 위한 어노테이션
@ApiParam: 매개변수에 대한 설명 및 설정을 위한 어노테이션 . 메소드 매개변수뿐 아니라 DTO 객체를 매개변수로 사용할 경우 DTO 클래스 내 매개변수에도 정의가능