[Spring Boot] Spring Boot 에서 Spring REST Docs 설정, Swagger 와 비교
Spring REST Docs
개념
Spring REST Docs는 RESTful API 문서를 생성하는 도구입니다. 통합 테스트와 문서화를 통합하여 테스트 코드에서 직접 문서를 생성할 수 있게 해줍니다. 이는 테스트가 통과된 내용만 문서화되기 때문에 항상 신뢰할 수 있는 문서를 보장합니다. Asciidoctor를 사용하여 문서를 생성하며, 커스터마이징이 가능합니다.
설정 방법
1. 의존성 추가
build.gradle
파일에 필요한 의존성을 추가합니다.
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.0'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.asciidoctor.convert' version '3.3.2'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
}
asciidoctor {
configurations 'asciidoctorExt'
dependsOn test
}
configurations {
asciidoctorExt
}
dependencies {
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor'
}
2. 테스트 작성
Spring REST Docs는 통합 테스트와 함께 사용됩니다. 다음은 간단한 REST API를 테스트하고 문서화하는 예제입니다.
컨트롤러 작성
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return List.of(new User(1, "John Doe", "john.doe@example.com"),
new User(2, "Jane Smith", "jane.smith@example.com"));
}
public static class User {
private int id;
private String name;
private String email;
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getters and setters omitted for brevity
}
}
테스트 작성
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext context) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(documentationConfiguration(MockMvcRestDocumentation.documentationConfiguration()))
.alwaysDo(document("{method-name}/{step}/"))
.build();
}
@Test
public void getAllUsers() throws Exception {
this.mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andDo(document("get-all-users",
preprocessRequest(),
preprocessResponse()));
}
}
3. 문서 생성
테스트가 실행될 때마다 build/generated-snippets
디렉토리에 스니펫이 생성됩니다. 이를 기반으로 Asciidoctor를 사용하여 최종 문서를 생성할 수 있습니다.
4. 스니펫 복사 작업 추가
build.gradle
파일에 스니펫을 Asciidoctor 소스 디렉토리로 복사하는 작업을 추가합니다.
task copySnippets(type: Copy) {
from 'build/generated-snippets'
into 'src/docs/asciidoc/snippets'
}
asciidoctor.dependsOn copySnippets
5. 문서 작성
src/docs/asciidoc/index.adoc
파일을 생성하고 문서를 작성합니다.
= API Documentation
== User API
=== Get All Users
include::{snippets}/get-all-users/http-request.adoc[]
include::{snippets}/get-all-users/http-response.adoc[]
6. 문서 빌드
./gradlew asciidoctor
위 명령어를 실행하면 build/docs/asciidoc/index.html
파일이 생성됩니다. 이를 열어 문서를 확인할 수 있습니다.
Swagger (OpenAPI)
개념
Swagger는 RESTful API를 문서화하고 테스트할 수 있는 도구입니다. 코드와 주석을 기반으로 자동으로 문서를 생성하며, Swagger UI를 통해 브라우저에서 API를 테스트할 수 있는 인터랙티브 콘솔을 제공합니다. Swagger는 OpenAPI 사양을 따르며, 다양한 언어와 프레임워크에서 사용할 수 있습니다.
설정 방법
1. 의존성 추가
build.gradle
파일에 Swagger 관련 의존성을 추가합니다.
dependencies {
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'
}
2. Swagger 설정
Spring Boot 프로젝트에서는 기본 설정으로 Swagger UI를 사용할 수 있습니다. 기본 URL은 /swagger-ui.html
입니다. 추가 설정이 필요하면 application.properties
파일에 설정을 추가할 수 있습니다.
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
Swagger와 Spring REST Docs 비교
Swagger의 장점
- 자동 문서 생성: API 코드와 주석 기반으로 자동으로 문서를 생성합니다.
- 인터랙티브 콘솔: Swagger UI를 통해 브라우저에서 API를 테스트할 수 있는 인터랙티브 콘솔을 제공합니다.
- 광범위한 생태계: 다양한 언어와 프레임워크에서 사용할 수 있으며, 다양한 도구와의 통합이 용이합니다.
Swagger의 단점
- 추가 설정 필요: 자동 생성되는 문서를 커스터마이징하려면 추가 설정이 필요합니다.
- 유지보수: 자동 생성되는 문서의 신뢰성은 주석이나 애노테이션의 정확성에 따라 달라지므로, 문서와 코드가 일치하지 않을 수 있습니다.
Spring REST Docs의 장점
- 테스트 기반 문서화: 테스트가 통과된 API만 문서화되므로, 항상 신뢰할 수 있는 문서를 보장합니다.
- 유연성: Asciidoctor를 사용하여 문서를 자유롭게 커스터마이징할 수 있습니다.
- 코드와 문서의 일치: 테스트 코드와 문서가 밀접하게 연결되어 있어, 코드 변경 시 문서도 자동으로 업데이트됩니다.
Spring REST Docs의 단점
- 복잡성: 초기 설정이 다소 복잡할 수 있으며, 문서화 과정이 자동화되지 않으므로 추가 작업이 필요합니다.
- 인터랙티브 콘솔 부족: Swagger UI와 같은 인터랙티브 콘솔이 기본적으로 제공되지 않습니다.
Spring REST Docs로 생성된 HTML
Spring REST Docs는 Asciidoctor를 사용하여 문서를 생성합니다. 예를 들어, src/docs/asciidoc/index.adoc
파일을 작성하고 이를 기반으로 문서를 빌드합니다. 다음은 Spring REST Docs로 생성된 HTML 문서의 예입니다.
예제 index.adoc 파일
= API Documentation
== User API
=== Get All Users
include::{snippets}/get-all-users/http-request.adoc[]
include::{snippets}/get-all-users/http-response.adoc[]
생성된 HTML 문서 예시
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Documentation</title>
</head>
<body>
<h1>API Documentation</h1>
<h2>User API</h2>
<h3>Get All Users</h3>
<pre>
GET /api/users HTTP/1.1
Host: localhost:8080
</pre>
<pre>
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane.smith@example.com"
}
]
</pre>
</body>
</html>
이 HTML 문서는 ./gradlew asciidoctor
명령어를 실행하여 build/docs/asciidoc/index.html
로 생성됩니다. 문서 구조는 Asciidoctor의 템플릿에 따라 달라질 수 있습니다.
Swagger UI로 생성된 HTML
Swagger를 사용하면, Swagger UI를 통해 인터랙티브한 API 문서를 자동으로 생성할 수 있습니다. Spring Boot 프로젝트에서는 기본적으로 /swagger-ui.html
경로에 Swagger UI가 설정됩니다.
Swagger 설정 예제
application.properties
파일에 Swagger 설정을 추가할 수 있습니다.
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
Swagger UI HTML 문서 예시
Swagger UI는 Spring Boot 애플리케이션이 실행될 때 자동으로 생성됩니다. 다음은 Swagger UI에서 보여주는 HTML 문서의 예입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.0/swagger-ui.css" >
<link rel="icon" type="image/png" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.0/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.0/favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after
{
box-sizing: inherit;
}
body {
margin:0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.0/swagger-ui-bundle.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.45.0/swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
const ui = SwaggerUIBundle({
url: "/api-docs",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
</body>
</html>
Swagger UI는 JSON 문서를 읽어와 자동으로 API 문서를 생성하며, 사용자에게 인터랙티브한 인터페이스를 제공합니다.
결론
Swagger와 Spring REST Docs는 각각의 장단점이 있으므로, 프로젝트의 요구사항에 맞게 선택하는 것이 중요합니다. Swagger는 빠른 문서화와 인터랙티브 테스트 환경을 제공하는 데 강점이 있고, Spring REST Docs는 테스트 기반으로 신뢰성 있는 문서를 생성하는 데 강점이 있습니다.
Spring REST Docs와 Swagger는 각기 다른 방식으로 API 문서를 생성합니다. Spring REST Docs는 테스트 기반으로 신뢰할 수 있는 문서를 생성하는 반면, Swagger는 코드 주석을 기반으로 인터랙티브한 문서를 자동 생성합니다