Rest API 개발 문서 자동화의 필요성을 느끼게 되었고, swagger을 사용해보기로 하였다. 간단한 로그인과 권한이 필요한 URI 정도로 프로젝트를 구성하여 swagger를 적용해보자.
간단한 프로젝트는 기존 Redis와 JWT에서 진행하였던 프로젝트를 기반으로 진행하였다.
스웨거를 적용하기에 앞서 다음의 라이브러리를 받아야 한다.
build.gradle에 추가해준다.
// [SWAGGER-1]
compileOnly group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
compileOnly group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
swagger를 사용하기 위해 스프링 컨테이너에 설정을 등록해야 한다.
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private String version; // API 버전
private String title; // API 설명
@Bean
public Docket apiV1() {
version = "V1";
title = "Sol SpringBoot API " + version;
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(AuthenticationPrincipal.class) // @AuthenticationPrincipal의 파라미터 요구 필드를 없애기 위함!
.useDefaultResponseMessages(false)
.groupName(version)
.select()
.apis(RequestHandlerSelectors.basePackage("com.springbootswagger"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo(title, version));
}
private ApiInfo apiInfo(String title, String version) {
return new ApiInfo(
title,
"Swagger로 생성한 API Docs",
version,
"www.example.com",
new Contact("Contact Me", "www.example.com", "foo@example.com"),
"Licenses",
"www.localhost:8080",
new ArrayList<>());
}
}
Doket을 만들어 컨테이너에 등록한다.
아래는 UserDTO의 일부이다.
@ApiModelProperty(value = "이메일", example = "solchan@hello.swagger",required = true)
private String email;
@ApiModelProperty(value = "비밀번호", example = "swagger123", required = true)
private String password;
@ApiModelProperty를 통해 각 변수마다 설정한다.
value: 변수에 대한 간략한 설명.
required: 필수 요소
example: 예시
다른 DTO 등 도메인에도 같은 방식으로 적용하면 된다.
아래는 UserController의 일부이다.
// 나의 정보 조회
@ApiOperation(value = "나의 정보 조회", notes = "나의 정보 조회하기")
@ApiResponses({
@ApiResponse(code = 500, message = "서버에서 문제가 발생하였습니다.")})
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true,
dataType = "string", paramType = "header"),
@ApiImplicitParam(name = "refreshToken", value = "refreshToken", required = true,
dataType = "string", paramType = "header")
})
@GetMapping("/profile")
public UserDTO test(@AuthenticationPrincipal User user) {
return userService.getProfile(user);
}
authorization과 refreshToken 요청을 글로벌로 설정하고 싶었지만 아무리 적용해도 막상 요청시에는 헤더에 포함되지가 않았다..
방법을 좀 더 찾아보기로..