2024.04.07 - [Project/협업 툴] - 개발자 API 협업 툴 - Swagger
개발자 API 협업 툴 - Swagger
요즘은 프론트엔드와 백엔드가 따로 독립적으로 분리가 된 상태에서 개발을 하는 경우가 많다. 따로 개발을 하고, API 엔드 포인트를 통해서 프론트 엔드와 서버가 통신을 하는 것이다. 위와 같
junhyuk-develop.tistory.com
우선, 글쓴이는 Spring Boot 3.2.2 , Swagger 2.0.4 를 사용한다.
아래와 같이 build.gradle 에 의존성을 추가해준다.
Build.gradle
//swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
본인에게 맞는 swagger 버전을 받으면 받으면 된다.
내 스프링 부트에 맞는 swagger 버전을 모르겠으면, 아래의 글을 참고 바란다.
2024.04.02 - [Spring] - Spring boot 버전에 맞는 라이브러리 버전 찾기
Spring boot 버전에 맞는 라이브러리 버전 찾기
평소 개발을 하면서 여러가지 라이브러리들을 다운받게 되는데, 이들은 다 버전들이 존재한다. 구글링해도 나와 같은 작업 환경을 가진 사람들이 아니기 때문에, 버전의 호환성 문제가 발생하
junhyuk-develop.tistory.com
그리고, application.properties 에 swagger의 설정값들을 추가해주어야 한다.
여러 properties가 있는데 자세한 내용은 아래의 공식 문서를 참고바란다.
Springdoc-openapi Properties
springdoc-openapi core properties Parameter name Default Value Description springdoc.api-docs.path /v3/api-docs String, For custom path of the OpenAPI documentation in Json format. springdoc.api-docs.enabled true Boolean. To disable the springdoc-openapi e
springdoc.org
아래의 코드는 내 application.properties에 있는 swagger 설정값이다.
Application.properties
springdoc.swagger-ui.groups-order=desc
springdoc.swagger-ui.tags-sorter=alpha
springdoc.swagger-ui.operations-sorter=method
springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.display-request-duration=true
springdoc.swagger-ui.default-model-expand-depth=2
springdoc.swagger-ui.default-models-expand-depth=2
springdoc.api-docs.path=/api-docs
springdoc.show-actuator=true
springdoc.default-produces-media-type=application/json
springdoc.default-consumes-media-type=application/json
springdoc.writer-with-default-pretty-printer=true
springdoc.model-and-view-allowed=true
springdoc.paths-to-match=/api/**
springdoc.swagger-ui.path : swagger-ui 접근 경로. default 값은 /swagger-ui.html이다. ( 본인은 생략 )
springdoc.swagger-ui.groups-order : 각 API의 그룹 표시 순서 → path, query, body, response 순으로 출력
springdoc.swagger-ui.tags-sorter : 태그 정렬 순서 → 알파벳 순 정렬 ( method 방식도 가능 )
springdoc.swagger-ui.operations-sorter : 컨트롤러 정렬 순서 → method는 delete - get - patch - post - put 순으로 정렬 (알파벳 방식도 가능)
springdoc.swagger-ui.disable-swagger-default-url : swagger-ui default url인 petstore html의 비활성화 설정
springdoc.swagger-ui.display-request-duration : swagger-ui에서 try 했을 때 request duration을 알려주는 설정
springdoc.api-docs.path : openAPI 접근 경로. default 값은 /v3/api-docs
springdoc.show-actuator : Spring Actuator의 endpoint까지 보여줄 것인지?
springdoc.default-produces-media-type=application/json : request media type 의 기본 값
springdoc.default-consumes-media-type=application/json : response media type 의 기본 값
springdoc.paths-to-match : 해당 패턴에 매칭되는 controller만 swagger-ui에 노출
springdoc.swagger-ui.default-model-expand-depth=2 : 단일 모델을 펼치는데 사용되는 깊이, ui에서 2단계까지만 노출
springdoc.swagger-ui.default-models-expand-depth=2 : 모델 컬렉션을 펼치는데 사용되는 깊이, ui에서 2단계까지만 노출
SwaggerConfig
@OpenAPIDefinition(
info = @Info(
title = "balance_board API Docs",
description = "API Docs",
version = "1.0.0"
)
)
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
return new OpenAPI();
}
}
이제 설정은 끝났고, 컨트롤러에 어노테이션을 추가해보자.
Controller
@Tag(name = "Main Page", description = "Main Page API")
public class MainApiController {
여기서 @Tag 를 사용해서 머리말을 작성했다. 아래와 같이 컨트롤러별로 페이지가 나뉜다.
그 아래 메서드별로 api가 분리되어 있다.
이를 구현하기 위한 어노테이션을 api 엔드포인트 메서드에 추가해보자.
Controller - Method
@PostMapping("/new/vote")
@Operation(summary = "Create VOTE", description = "투표 실행")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Success",
content = {@Content(schema = @Schema(implementation = VoteResponseDTO.class))}),
@ApiResponse(responseCode = "400", description = "Fail",
content = {@Content(schema = @Schema(implementation = VoteFailResponseDTO.class))})
})
현재 서비스에서 사용하는 하나의 예시를 가져왔다.
@Operation을 통해 메서드 별로 머리말을 만든다.
자세히 보기 버튼을 누르면 아래와 같다.
원하는 컨트롤러, 메서드별로 위와 같은 어노테이션을 통해 작성해주면 쉽게 swagger-ui에서 확인이 가능하다. 물론, 테스트도 Try를 통해 가능하다.
DTO
우리가 API 통신을 할 때 필요로 하는 Json 데이터 형식을 위해 DTO를 사용한다.
쉽게 말하면, 요청 데이터 형식, 응답 데이터 형식을 뜻한다.
이에 대한 것도 자세하게 확인할 수 있다.
이렇게 swagger-ui.html의 하단을 보면 Schemas 로 해당 DTO들에 대한 데이터 값들이 나열되어 있다.
이 또한, 스프링에서 어노테이션을 추가해주어야 한다.
위의 DTO의 코드 중 일부이다.
@Schema(title = "MEM_REQ_01 : 회원 가입 요청 DTO")
@Builder
@NoArgsConstructor
public static class CreateMemberRequestDTO {
@NotBlank
@Email
@Schema(description = "email", example = "aaa@gmail.com")
private String email;
@NotBlank
@Schema(description = "password", example = "1231!@aa")
private String password;
@NotBlank(message = "닉네임을 입력해주세요.")
@Size(min = 3, max = 10, message = "닉네임은 3글자 이상 10글자 이하로 입력해야 합니다.")
@Schema(description = "닉네임", example = "몽글몽글")
private String nickname;
@Schema 를 사용하여 DTO의 머리말을 작성해주고, 내부의 각 데이터 별로 @Schema를 통해 설명을 덧붙힌다.
이렇게 작성한 뒤, /swagger-ui/index.html 에 들어가면 바로 확인 가능하다.
본인이 local에서 실행한다면, localhost:8080/swagger-ui/index.html 로 들어가면 swagger-ui를 확인할 수 있다.
'Project > 협업 툴' 카테고리의 다른 글
개발자 API 협업 툴 - Swagger (0) | 2024.04.07 |
---|