API 문서화
백엔드와 프론트엔드 개발자 사이의 원활한 협업을 위해서는 REST API 명세에 대한 문서화가 잘 되어있어야 한다. 현재 개인 프로젝트 (AImage)에서도 REST API를 구현하였고, 문서화를 진행해야 했다.
Spring에서 자주 사용되는 API 문서 자동화 도구는 대표적으로 Swagger와 Spring REST Doc 두가지가 있다. 이 개인 프로젝트에서 두 기술을 모두 사용해 보고, 비교해서 최종적으로 어떤 기술을 적용시킬지 결정할 것이다.
먼저 Swagger를 사용하여 API 문서화를 진행해보겠다.
Swagger
1. Springfox vs. Springdoc
Swagger로 API 문서화를 시작하기에 앞서, Springfox와 Springdoc에 대해 알아보자.
Spring Framework를 사용하는 프로젝트에서 Swagger를 이용해 API 문서를 쉽게 쓸 수 있도록 해주는 라이브러리
Springfox
2012년 부터 Swagger SpringMVC 라는 이름으로 사용되기 시작해, 2015년 부터는 springfox-swagger 라는 이름으로 업데이트가 활발히 이루어지게 된다.
허나 2018년 중반 쯤 부터, 업데이트가 중단되기 시작하고, 약 2년 간 없데이트 소식이 없다가, 2020년 7월에 v3.0.0 업데이트를 마지막으로 더 이상 다른 소식이 없다 (참고: https://github.com/springfox/springfox/tags).
Springdoc
Springfox가 업데이트를 중단한 사이, 2019년 쯤에 처음 등장하여 현재까지 활발히 업데이트가 이뤄지고 있다.
여기서는 Springdoc을 사용하는 것이 좋아보인다 (사실 특별한 이유는 없고, Springfox는 더 이상 활동 기록이 없기 때문에...)
2. Springdoc 적용하기
build.gradle에 의존성 추가
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
Configuration
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.components(new Components())
.info(apiInfo());
}
private Info apiInfo() {
return new Info()
.title("AImage API Documenation")
.description("Springdoc을 이용한 AImage API 문서")
.version("1.0.0");
}
}
실행
Springdoc은 application 속성 (.properties / .yml)의 springdoc.packages-to-scan에 설정한 패키지 내부의 클래스는 모두 자동으로 Swagger의 문서로 등록한다. 만약 등록하고 싶지 않은 클래스가 있다면, @Hidden 어노테이션을 사용해 숨길 수 있다.
아래 링크에서 더 다양한 속성들을 확인할 수 있다.
https://springdoc.org/#springdoc-openapi-core-properties)
application을 실행하고 springdoc.swagger-ui.path 속성에 설정한 경로로 들어가면 Swagger UI를 확인할 수 있다.
- 기본값으로 설정된 경로는 /swagger-ui.html 이다.
- Ex) http://localhost:8080/swagger-ui.html (로컬에서 접속 시)
- 해당 경로로 접속하면 이렇게 @RestController에 있는 모든 API가 문서화 된 것을 볼 수 있다.
- 게다가 위처럼 Entity와 DTO까지 Schema로 전부 자동으로 문서화 해준다.
상세 설정
Springdoc이 제공하는 어노테이션을 사용하면 문서에 API의 이름을 바꾸거나 설명 추가 등 여러 상세 설정을 할 수 있다.
@Tag(name = "User API", description = "회원 기능 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/users")
public class UserApiController {
private final UserService userService;
@Operation(summary = "회원가입", description = "사용자 회원가입")
@Parameters({
@Parameter(name = "id", description = "사용자 id"),
@Parameter(name = "username", description = "사용자 닉네임"),
@Parameter(name = "email", description = "사용자 email")
})
@PostMapping("")
public ResponseEntity<UserVO> signup(@Validated @RequestBody Signup signupForm) {
UserVO signupUser = userService.join(signupForm);
return ResponseEntity.status(HttpStatus.OK).body(signupUser);
}
...
}
위와 같이 어노테이션을 추가하고 application을 다시 실행하면,
이렇게 문서에 정보가 추가된다.
사용한 어노테이션들은 다음과 같다.
- @Tag : API class 이름 및 설명 (미적용 시, controller class의 이름을 사용)
- @Operations : 각 API의 이름 및 설명 추가
- @Parameter / @Parameters : 파라미터 이름 및 설명 추가.
Request Body와 Response Body 예시도 수정이 가능하다.
@Getter
public class UserVO {
@Schema(example = "1")
private final Long id;
@Schema(example = "tester")
private final String username;
@Schema(example = "test@gmail.com")
private final String email;
public UserVO(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
}
위와 같이 @Schema(example = "...") 어노테이션을 DTO나 VO 객체에 사용하면 Request Body와 Response Body 예제가 수정된 것을 확인할 수 있다.
- @Schema(description = "...") 를 사용하면 @Parameter 를 사용한 것 처럼 파라미터 설명도 추가할 수 있다.
그 외에도 여러 다양한 기능들을 제공한다. 더 많은 정보는 아래의 링크를 참고하자.
https://springdoc.org/#additional-resources-to-get-started
후기
Swagger의 어노테이션으로 문서를 생성하는 방법은 매우 간단하고 직관적이어서 좋았다. 게다가 API 를 테스트 해볼 수 있는 화면을 제공해서 더 편하게 사용할 수 있었다. 하지만, 과연 이렇게 controller나 DTO 객체에 문서화 코드를 붙이는 것이 좋은 방법인지는 의문이 든다.
- 일단 가장 큰 문제점이라고 생각되는 것은 코드의 가독성이 떨어진다는 것이다.
- 그리고 만약, API에 변화가 생긴다면? -> 문서화 코드를 전부 다시 수정해야 하는 불편함이 생길 것이다.
사실 현재 프로젝트는 매우 작은 규모라 Swagger를 사용해도 큰 문제점은 없을 것 같지만, 만약 규모가 매우 큰 프로젝트에서 이런 방식으로 API 문서화를 한다면 유지보수성이 떨어질 것이라 생각했다.
Reference
OpenAPI 3 Library for spring-boot
Library for OpenAPI 3 with spring boot projects. Is based on swagger-ui, to display the OpenAPI description.Generates automatically the OpenAPI file.
springdoc.org
'Spring' 카테고리의 다른 글
[Spring] Spring Data JPA의 Pagination (0) | 2023.12.24 |
---|---|
[Spring] Spring에서 API 문서 자동화하기 (3) (0) | 2023.12.24 |
[Spring] Spring에서 API 문서 자동화하기 (2) - Spring REST Docs (0) | 2023.12.24 |
[Spring] MockMVC를 이용한 Test (0) | 2023.12.24 |
[Spring] Spring의 Cookie & Session (0) | 2023.12.24 |