서버 개발
Spring Boot REST API 회원관리 - (2) Swagger 적용
devgenie
2024. 7. 30. 13:03
Swagger를 사용하면 보다 API 문서를 자동으로 생성하고, 이를 시각적으로 표현할 수 있는 인터페이스를 제공받기 때문에 API 문서화를 편하게 할 수 있다. 또한 Swagger UI를 이용하여 편리하게 API를 직접 테스트할 수 있어서 API의 동작을 빠르게 검증할 수 있다. 그래서 API 개발 및 변경사항을 쉽게 관리 및 추적할 수 있다.
이러한 이유로 Swagger를 적용해보기로 하였다.
의존성 추가
- Spring Boot 2.x.x 버전과 3.x.x 는 추가하는 의존성이 다르다. 3.x.x 는 아래와 같은 의존성을 추가하면 된다.
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.4.0'
SwaggerConfig 클래스 추가
- Swagger를 사용하기 위해서 SgaggerConfig 클래스를 추가하였다.
- http://localhost:8088/swagger-ui/index.html#/
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("API DOC")
.description("API 설명을 위한 문서")
.version("1.0"));
}
}
Controller에 적용
@RestController
@AllArgsConstructor
@RequestMapping("/jpa")
@Tag(name = "Controller", description = "회원관리를 윈한 컨트롤러입니다.")
public class UserController {
private final UserService userService;
@Operation(
summary = "회원가입 API",
description = "유저아이디, 비밀번호를 입력하여 회원가입합니다.",
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
content = @Content(
schema = @Schema(implementation = RequestUserVO.class),
examples =
{
@ExampleObject(
name = "회원가입 성공 입력값 예제",
value = "{\n" +
" \"userId\": \"유저아이디1\",\n" +
" \"password\": \"1234\",\n" +
"}\n"
)
}
)
),
responses = {
@ApiResponse(
responseCode = "201",
description = "가입요청 성공",
content = @Content(
schema = @Schema(implementation = ResponseUserVO.class),
examples = {
@ExampleObject(
name = "가입요청 성공 예시",
value = "{\"message\":\"가입이 완료되었습니다.\",\"success\":true}"
)
}
)
)
}
)
@PostMapping("/users")
public ResponseEntity<?> user(@RequestBody RequestUserVO requestUserVO) {
ResponseUserVO responseUserVO = userService.createUser(requestUserVO);
return ResponseEntity.status(HttpStatus.CREATED).body(responseUserVO);
}
}
@Tag(name = "Controller", description = "회원관리를 위한 컨트롤러입니다.")
- 이 어노테이션은 OpenAPI 스펙의 태그를 정의한다. name과 description 속성을 사용하여 API 문서에 표시될 태그 이름과 설명을 지정할 수 있다.
@Operation
- 특정 API 엔드포인트의 세부 정보를 기입할 수 있게 해준다.
- summary: API의 간단한 설명
- description: API의 상세 설명
- requestBody: 요청 본문의 내용
- responses: API 응답에 대한 정보
@io.swagger.v3.oas.annotations.parameters.RequestBody
- 요청 본문에 대한 설명을 추가할 수 있게 한다.
- content: 요청 본문에 포함될 데이터의 형식과 예제를 설명
@Content
- 요청 또는 응답의 내용을 설명할 수 있게 해준다.
- schema: 요청 또는 응답 데이터의 스키마를 정의
- examples: 요청 또는 응답의 예제를 정의
@Schema
- 요청 또는 응답 데이터의 스키마를 정의할 수 있게 한다. implementation에는 실제 데이터 구조를 나타내는 클래스를 기입한다.
@ExampleObject
- 요청 또는 응답 데이터의 예제를 정의
- name: 예제의 이름을 정의합니다.
- value: 예제의 값을 정의합니다.
@ApiResponse
- 특정 응답 코드에 대한 설명을 추가합니다.
- responseCode: 응답 코드(예: "201")를 정의
- description: 응답에 대한 설명을 제공
- content: 응답 본문에 포함될 데이터의 형식과 예제를 설명
어노테이션 추가 후
설명 및 예제가 추가되어 해당 앤드포인트의 기능을 한눈에 파악할 수 있게 되었다. 모든 엔드포인트마다 이렇게 상세하게 작성할 예정은 아니지만, 이번기회에 Swagger에서 주로 사용하는 어노테이션들과 그 역할을 정리해 볼 수 있어서 좋았다.