오늘 공부한 내용
- 코드카타 2문제
- Spring 심화 프로젝트 작성
새로 알게된점
Swagger - UI 란?
- 애플리케이션의 RESTful API 문서를 자동으로 구성하는 특수 도구를 말한다.
프로젝트 내에서 지정한 url들을 아래와 같이 자동으로 문서화해준다.

이곳에서 간단히 api를 볼 수 있을 뿐만 아니라, 요청과 응답 테스트 또한 진행할 수 있다.
이런 점들이 백엔드와 프론트엔드 간의 협업과 소통을 돕는다.
Swagger - UI를 사용하기 위한 설정
build.gradle 추가 설정
의존성에 springdoc-openapi-ui를 추가한다.
dependencies {
// spring doc
implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.3.0'
}
Config 파일 구성
package com.sparta.missionreport.global.config;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@OpenAPIDefinition(info = @Info(title = "Mission Log App",
description = "Mission Log App Api 명세서",
version = "v1"))
@SecurityScheme(name = "Bearer Authentication",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "Bearer")
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.components(new Components());
}
}
@Configuration 어노테이션을 통해서 OpenAPI 관련 문서를 생성하며,
@OpenAPIDefinition, @SecurityScheme 어노테이션을 SwaggerConfig에 적용하면, 위의 페이지의 Authorize버튼을 구현할 수 있다.
이 버튼은
회원정보로 발급받은 토큰을 입력하면 그 시점부터 swagger-ui에서 테스트로 보내는 요청은 모두 그 회원의 권한으로 보낼 수 있다.
로그인되지 않은 사용자, 로그인한 회원, 관리자 이러한 종류의 회원 권한들로 다양하게 요청 테스트를 진행할 수 있다.
.properties 파일 설정
# swagger
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
# spring doc
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.tags-sorter=alpha
springdoc.show-login-endpoint=true
객체를 생성할 수 있는 빌더를 builder() 함수를 통해 얻고 거기에 셋팅하고자 하는 값을 셋팅하고 마지막에 build()를 통해 빌더를 작동 시켜 객체를 생성한다.
controller 설정
@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Tag(name = "2. Board Controller", description = "Board Controller")
@SecurityRequirement(name = "Bearer Authentication")
public class BoardController {
private final BoardService boardService;
@Operation(summary = "보드 생성")
@PostMapping("/boards")
public ResponseEntity<CommonResponseDto> createboard(
@AuthenticationPrincipal UserDetailsImpl userDetails,
@RequestBody @Valid BoardDto.CreateBoardRequest createBoardRequest) {
BoardDto.Response response = boardService.createBoard(userDetails.getUser(),
createBoardRequest);
return ResponseEntity.status(
HttpStatus.CREATED)
.body(new CommonResponseDto(HttpStatus.CREATED.value(), "보드가 작성되었습니다.", response));
}
위의 예시는 익명게시판에서 보드를 생성하기위한 컨트롤러 의 Create 부분 이며
Controller의 상단에 @Tag 어노테이션과 @Operation 어노테이션을 추가한다.
@Tag / api 그룹 설정을 위한 어노테이션
name 속성으로 태그의 이름을 설정할 수 있고, description 속성으로 태그에 대한 설명을 추가할 수 있다.
@Tag에 설정된 name이 같은 것 끼리 하나의 api 그룹으로 묶게 된다.
@Operation / api 상세 정보 설정을 위한 어노테이션
summary 속성으로 api에 대한 간략한 설명, description 속성으로 api에 대한 상세 설명을 추가할 수 있으며, responses, parameters 속성 등을 추가로 적용할 수 있다.
Request, Response 객체 설정
public class BoardDto {
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "보드 생성 요청 dto")
public static class CreateBoardRequest {
@NotBlank
@Schema(description = "보드 이름", defaultValue = "개발 전체 진행 완료하자")
private String name;
public Board toEntity(User createdBy) {
return Board.builder().name(name).createdBy(createdBy).build();
}
}
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "보드 수정 요청 dto")
public static class UpdateBoardRequest {
@Schema(description = "보드 이름", defaultValue = "보드 이름 수정 test")
private String name;
@Schema(description = "보드 색상", defaultValue = "blue")
private Color color;
@Schema(description = "보드 설명", defaultValue = "보드, 수정 완료하기")
private String description;
@Schema(description = "보드 마감 일자", defaultValue = "2023-01-03 09:00")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime deadLine;
}
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "보드 정보 반환 dto")
public static class Response {
@Schema(description = "보드 id", defaultValue = "1L")
private Long id;
@Schema(description = "보드 이름", defaultValue = "제발...문제없이 작동해주세요")
private String name;
@Schema(description = "보드 설명", defaultValue = "카드, 댓글 기능 구현 완료하기")
private String description;
@Schema(description = "카드 색상", example = "red")
private String color;
@Schema(description = "생성 유저 이메일", defaultValue = "sparta@gmail.com")
private String createdBy;
@Schema(description = "보드 작업자 리스트", defaultValue = "[\"spsta@gmail.com\", \"worker1@gmail.com\",\"worker2@gmail.com\"]")
private List<String> boardWorkers;
@Schema(description = "보드 생성 일자", defaultValue = "2023-01-01T00:00:00")
private LocalDateTime createdAt;
public static BoardDto.Response of(Board board) {
return Response.builder()
.id(board.getId())
.name(board.getName())
.description(board.getDescription())
.color(board.getColor().getColor())
.createdBy(board.getCreatedBy().getEmail())
.boardWorkers(board.getBoardWorkerList().stream().map(BoardWorker::getUserEmail)
.toList())
.createdAt(board.getCreatedAt())
.build();
}
}
}
위의 예시처럼 @Schema 를 이용하여 각부분의 설명, 기본값을 설정하여 기입할수 있다.
@Schema / Request, Response 객체에 대한 설정을 위한 어노테이션
description으로 설명을 추가할 수 있고, defaultValue으로 기본적으로 사용할 값을 설정할 수 있으며, example을 통해 예시를 설정할 수도 있다.
느낀점
Postman이 아닌 Swagger-UI 라는 새로운 API 테스트 프로그램을 프로젝트 하면서 배우게 되었다.
혼자 작성해서 확인해야하는 Postman에 비해 Swagger-UI는 코드 작성시 팀원들과 토의로 일정 규칙하에 작성하면 기본값을 설정한상태로 테스트가 가능하기에 좀더 효율적으로 시행할수 있다.
프로젝트를 하면서 팀원들에게 새로운 것을 배울때 마다 감사를 느끼며 더욱더 열심히 해야겠다고 생각한다.
'개발자 일지 > TIL' 카테고리의 다른 글
스파르타 내일배움캠프 91일차 240104 / 마지막 프로젝트 시작 (1) | 2024.01.06 |
---|---|
스파르타 내일배움캠프 90일차 240103 / KPT (1) | 2024.01.06 |
스파르타 내일배움캠프 85일차 231228 (1) | 2023.12.29 |
스파르타 내일배움캠프 84일차 231227 (0) | 2023.12.29 |
스파르타 내일배움캠프 83일차 231226 / 심화프로젝트 시작 (0) | 2023.12.26 |