[1년 후 마실가실] API 문서화 도구 - Spring REST Docs
1년 전 진행했던 마실가실 프로젝트를 🛠️리팩토링하며 정리한 내용입니다.

리팩토링을 Backend 부분만 하고 있다보니, 문득.. 다른 이들이 제 API를 확인할 길이 전혀 없다는 걸 최근에 깨달았습니다..!
프론트 연결...까지는 시간이 오래 걸릴 것 같아서, 그간 만들어놓은 API를 문서로라도 남겨두면 좋을 것 같아서 API 문서화 도구를 썼습니다.
근래 작업한 내용 중에서 가장 많은 블로그 글을 찾아보았습니다..
그렇기에 정리가 꼭 필요하다고 판단되어 글을 작성해봅니다.
1. API 문서화
클라이언트가 REST API 애플리케이션에 요청을 전송하기 위해서 알아야 되는 요청 정보(요청 URI, request body, query parameter 등)를 정리하여 문서화 하는 것
* 일반적으로 애플리케이션 빌드를 통해 API 문서를 자동 생성하는 경우가 많음
2. Spring REST Docs or Swagger
Spring REST Docs
* 애플리케이션 기능 구현과 관련된 코드에 API 문서 생성을 위한 애노테이션 같은 정보가 추가되지 않음
* Controller 테스트 코드가 선행되어야 하며, Controller 테스트 클래스에 API 문서를 위한 정보가 추가됨
Swagger
* Postman처럼 API 요청 툴로써의 기능을 사용할 수 있음
* 웹 인터페이스를 제공해 사용자와 개발자가 API를 테스트할 수 있는 페이지를 쉽게 확인할 수 있음
☺️저는 주석으로 학습한 내용을 코드에 작성하는 편이라 Swagger까지 추가하면 코드가 복잡해질 것 같아 REST Docs를 사용했습니다!
3. 환경 설정
build.gradle
plugins { | |
id "org.asciidoctor.jvm.convert" version "3.3.2" // AsciiDoc 문서를 HTML, PDF, ePub 등 다양한 포맷으로 변환 | |
} | |
configurations { | |
asciidoctorExt // asciidoctorExt에 대한 종속성 구성 선언 | |
} | |
dependencies { | |
// Spring REST Docs | |
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' | |
// Spring REST Docs로 생성된 AsciiDoc 형식의 문서를 최종적으로 HTML이나 PDF 같은 문서 파일로 변환하기 위해 사용되는 라이브러리 | |
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' | |
// MockMvc를 사용한 테스트에서 API 문서를 생성할 때 사용 | |
// MockMvc: Spring MVC 애플리케이션을 실제 서버 없이 테스트할 수 있게 해주는 도구 | |
testImplementation 'org.springframework.restdocs:spring-restdocs-restassured' | |
// REST Assured를 사용한 API 테스트에서 문서를 생성할 때 사용 | |
// REST Assured: REST API를 테스트하기 위해 자주 사용되는 라이브러리, HTTP 요청 및 응답을 간단하게 작성하고 확인할 수 있음 | |
} | |
ext { // 스니펫 생성 디렉토리 설정 | |
snippetsDir = file('build/generated-snippets') | |
} | |
test { | |
outputs.dir snippetsDir // 테스트가 수행된 후 Spring REST Docs에서 생성한 스니펫들이 이 디렉토리에 저장 | |
} | |
asciidoctor { // asciidoctor 테스크 설정 | |
inputs.dir snippetsDir | |
// Spring REST Docs가 테스트 실행 후에 생성하는 스니펫 파일(예: 요청/응답, cURL 명령어 등)이 저장되는 디렉토리 | |
configurations 'asciidoctorExt' | |
// asciidoctor 작업에 대해 추가적인 설정을 적용하기 위해 사용되는 설정 | |
// Spring REST Docs가 테스트를 통해 생성한 스니펫을 가져와, Asciidoctor가 문서로 변환할 수 있도록 함 | |
dependsOn test | |
// test 테스크가 먼저 실행된 후에 asciidoctor 테스크가 실행되도록 하여, | |
// 테스트가 완료된 후 생성된 스니펫을 사용해 API 문서를 빌드할 수 있도록 보장 | |
} | |
task copyDocument(type: Copy) { | |
dependsOn asciidoctor | |
from file("build/docs/asciidoc") | |
// resources/static/docs로 복사하여 서버가 돌아가고 있을때 /docs/index.html로 접속하면 볼수 있음 | |
into file("src/main/resources/static/docs") | |
} | |
build { | |
dependsOn copyDocument | |
} | |
bootJar { | |
dependsOn asciidoctor | |
from("${asciidoctor.outputDir}/html5") { | |
into 'static/docs' | |
} | |
} |
🌟 Spring REST Docs에 관련된 정보만 기재되어있습니다.
* MockMvc vs RestAssured
* MockMvc
* @SpringBootTest와 함께 사용할수도 있고, @WebMvcTest와 함께 사용할수도 있음
* RestAssured
* @SpringBootTest와 함께 사용
* 어플리케이션이 동작하는 실제 환경과 동일한 환경에서 테스트를 진행하고 싶을 때 RestAssured 를 사용
* implementation or runtimeOnly
* implementation
* 컴파일 타임에 안전하게 의존성을 관리할 수 있음
* 의존성의 클래스를 코드에서 직접 import하여 사용할 수 있음
* 많은 의존성이 컴파일 타임에 추가되면 빌드 시간이 늘어날 수 있음
* runtimeOnly
* 가벼운 빌드와 의존성 충돌을 줄일 수 있음
* 의존성의 클래스를 코드에서 직접 import하여 사용할 수 없음
* 런타임 시에만 동작하기 때문에 문제가 늦게 발견될 수 있음
WebMvcConfig.java
@Configuration | |
public class WebMvcConfig implements WebMvcConfigurer { | |
@Override | |
public void addResourceHandlers(ResourceHandlerRegistry registry) { | |
registry.addResourceHandler("/docs/**").addResourceLocations("classpath:/static/docs/"); | |
} | |
} |
* static resource에 파일을 url로 접근하기 위한 설정
4. Test Code 작성
UserControllerTest.java
@SpringBootTest | |
@ExtendWith({RestDocumentationExtension.class}) | |
// RestDocumentationExtension: Spring REST Docs의 기능을 테스트에 확장하여 API 문서화를 자동으로 할 수 있게 함 | |
// RestDocumentationContextProvider 객체를 제공하여 MockMvc 설정 시 REST Docs 문서화를 할 수 있게 도와줌 | |
// 테스트 실행 시 REST Docs 관련 설정을 수동으로 추가할 수 있도록 도와줌 | |
@AutoConfigureMockMvc | |
class UserControllerTest { | |
@Autowired | |
MockMvc mockMvc; | |
@Autowired | |
ObjectMapper objectMapper; | |
@MockBean | |
UserService userService; | |
@BeforeEach | |
void setUp(WebApplicationContext webApplicationContext, | |
RestDocumentationContextProvider restDocumentation) { | |
this.mockMvc = MockMvcBuilders.webAppContextSetup( | |
webApplicationContext) // webApplicationContext 기반 Mock 객체 생성 | |
.apply(documentationConfiguration( | |
restDocumentation)) // REST Docs의 문서화를 위한 설정을 추가 | |
.alwaysDo(print()) | |
.alwaysDo(document("users/{method-name}", | |
preprocessRequest(prettyPrint()), | |
preprocessResponse(prettyPrint()))) | |
// REST Docs 문서화 작업을 자동으로 실행 | |
// {method-name}을 통해 각 테스트 메서드 이름에 따라 문서화 파일을 생성 | |
.addFilters(new CharacterEncodingFilter("UTF-8", true)) | |
.build(); | |
} | |
@Test | |
@DisplayName("회원 가입: 성공") | |
void createSuccess() throws Exception { | |
// given | |
SignUpRequestDTO signUpDto = SignUpRequestDTO.builder() | |
.userType("MSGS") | |
.email("new@email.com") | |
.phone("01023698741") | |
.nickname("name") | |
.password("newnew123!") | |
.confirmPassword("newnew123!") | |
.build(); | |
// when | |
ResultActions result = mockMvc.perform(post("/api/v2/users/new") | |
.contentType(MediaType.APPLICATION_JSON) | |
.content(objectMapper.writeValueAsString(signUpDto))); | |
// objectMapper.writeValueAsString(signUpDto) | |
// DTO 객체를 JSON 문자열로 변환한 후, 이를 HTTP 요청으로 보냄 | |
// signUpDto의 값들이 변형되지 않지만, userService.create()가 호출될 때는 새로운 인스턴스가 생성 | |
// then | |
result.andExpect(status().isCreated()); | |
} | |
} |
* @ExtendWith or @AutoConfigureRestDocs
* @ExtendWith({RestDocumentationExtension.class})
* Spring REST Docs의 기능을 테스트에 확장하여 API 문서화를 자동으로 할 수 있게 함
* RestDocumentationContextProvider 객체를 제공하여 MockMvc 설정 시 REST Docs 문서화를 할 수 있게 도와줌
* 테스트 실행 시 REST Docs 관련 설정을 수동으로 추가할 수 있도록 도와줌
* @AutoConfigureRestDocs
* Spring REST Docs를 자동 설정해 문서화를 지원
* Spring Boot에서 자동으로 REST Docs 설정을 구성하여 MockMvc 객체에 REST Docs 관련 설정을 추가
* MockMvc 객체 생성 시 REST Docs 설정을 자동으로 추가
5. .adoc 파일 작성
🌟Gradle 프로젝트의 경우, 템플릿 문서가 위치하는 default 경로: src/docs/asciidoc
* Markdown or Asciidoc
* Markdown
* 문서 작성용 마크업 언어(태그를 이용하여 문서나 데이터의 구조를 명시하는 언어 )
* Asciidoc
* 문서 작성용 마크업 언어 + include 기능 포함
6. build 실행
🙋♀️
본 포스트는 공부 목적으로 작성하였습니다.
보시는 도중 잘못된 부분이나 개선할 부분이 있다면 댓글로 알려주시면 수정하도록 하겠습니다.
📑
참고 자료
https://velog.io/@bagt/API-%EB%AC%B8%EC%84%9C%ED%99%94%EC%99%80-Spring-Rest-Docs
API 문서화와 Spring Rest Docs 사용기
클라이언트가 REST API 애플리케이션에 요청을 전송하기 위해서 알아야 되는요청 정보(요청 URI, request body, query parameter 등)를 정리하여 문서화 하는 것.API 문서 / API 스펙(사양, Specification) : API 사용
velog.io
https://hudi.blog/spring-rest-docs/
Spring REST Docs를 사용한 API 문서 자동화
API 문서 자동화 백엔드와 프론트엔드 개발자 사이의 원활한 협업을 위해서는 REST API 명세에 대한 문서화가 잘 되어있어야 한다. 구글 독스, 스프레드 시트, 위키, 노션 등을 사용해서 직접 API 명
hudi.blog
https://helloworld.kurly.com/blog/spring-rest-docs-guide/
내가 만든 API를 널리 알리기 - Spring REST Docs 가이드편
'추석맞이 선물하기 재개발'에 차출되어 API 문서화를 위해 도입한 Spring REST Docs 를 소개합니다.
helloworld.kurly.com
Spring Rest Docs를 이용한 API 문서 만들기 | Carrey`s 기술블로그
Spring Rest API 문서를 자동으로 생성하고자 할 때, 보통 Swagger로 많이 사용하지만 이번에는 Spring Rest Docs를 사용하여 API 문서를 자동으로 작성 할 수 있도록 해봤습니다. 포스팅에 작성된 코드는 htt
jaehun2841.github.io
https://velog.io/@galmegi/build.gradle-asciidoctor-%EC%84%A4%EC%A0%95
build.gradle asciidoctor 설정
1. 공부배경 API문서 작성을 자동화하기 위해 Spring RestDocs를 사용했는데, RestDocs보다 asciidoctor설정에 더 애를 먹었다. 온라인에 나와있는 글들이 버전이 달라 문제가 되는 경우가 있었고 무엇보다
velog.io
[Spring] Spring rest docs 적용기(gradle 7.0.2)
gradle 7 버전에서 spring rest docs 적용 방법과 겪은 문제
velog.io
https://jake-seo-dev.tistory.com/87
Spring REST Docs + asciidoctor 로 문서 자동 생성해보기
Spring REST Docs 개요 RESTful 서비스의 문서 작성을 돕는다. Spring MVC Test 와 함께 자동 생성된 스니펫과 Asciidoctor 로 쓰여진 수기 문서를 조합한다. Swagger 와 같은 도구에 의해 만들어진 문서화의 한계
jake-seo-dev.tistory.com
https://github.com/DeveloperAcademy-POSTECH/MacC-Team-Trying-server
GitHub - DeveloperAcademy-POSTECH/MacC-Team-Trying-server
Contribute to DeveloperAcademy-POSTECH/MacC-Team-Trying-server development by creating an account on GitHub.
github.com
https://devwriter.tistory.com/28
[Spring REST Docs ✍️] 어렵게만 느껴졌던 REST Docs를 적용해보자! (1)
Spring REST Docs오늘은 스프링 REST Docs에 대해 적용하고, 관리하는 방법을 알아보고자 합니다. 스프링을 어느 정도 써 보고, 테스트 및 문서화등을 해 보신 분들이라면 스웨거나 노션, 포스트맨으로
devwriter.tistory.com