고민하게 된 이유
처음 프로젝트를 할 때는 아무 생각 없이 코드만 적는, 프론트를 생각하지 않는 방법으로 진행했다.
그러다가 swagger를 알게 되면서, 각종 오류 메세지와 api를 간편하게 전달할 수 있다는 사실을 알았다.
스웨거 (Swagger)란?
- 스웨거는 Web API 문서화를 위한 도구이다.
- 스웨거 홈페이지에서는 스웨거를 OAS(Open API Specification)이라고 소개하고 있다.
- 말 그대로 API들이 가지는 명세(Spec)을 관리하기 위한 프로젝트이다.
- Web API를 수동으로 문서화 하는 것은 굉장히 힘든일인데, Web API의 스펙이 변경되었을 때 문서 역시 변경되어야 하는데 이를 유지하는 것이 쉽지 않다.
- Swagger를 사용하면 Web API가 수정되더라도 문서가 자동으로 갱신 되기 때문에 편리하다.
자 본격적으로 스웨거를 우리의 프로젝트에 적용시켜보자.
1. gradle 추가
//swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
사실 의존성만 추가해도 기본적인 스웨거 페이지는 돌아갈 것이다.
2. yml 파일 설정
# Swagger
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /api-docs/json
groups:
enable: true
cache:
disabled: true
use-fqn: true
default-consumes-media-type: application/json;charset=UTF-8
default-produces-media-type: application/json;charset=UTF-8
3. securityConfig 설정
로그인 구현을 했다면 필수적으로 열어두어야 한다.
.requestMatchers("/static/js/**","/static/css/**","/static/img/**"
,"/swagger-ui/**","/api-docs/**").permitAll() //스웨거는 인증 피함
4. controller 양식 설정
사실 이 내용은 필요한 사람만 써도 된다. 필자는 이러한 틀을 가지고 사용 중이다.
@Operation(summary = "유저 글 작성", description = "해당 유저가 글을 씁니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "유저 글 작성 성공"),
@ApiResponse(responseCode = "400", description = "잘못된 요청 값"),
@ApiResponse(responseCode = "401", description = "헤더 없음 or 토큰 불일치", content = @Content(schema = @Schema(example = "INVALID_HEADER or INVALID_TOKEN")))
})
@PostMapping("/save")
public ResponseEntity<String> savePost(Principal principal, @RequestBody PostRequestDto requestDto) {
postService.savePost(Long.parseLong(principal.getName()), requestDto);
return new ResponseEntity<>("글 작성 완료", HttpStatus.OK);
}
5. 접속
http://localhost:8080/swagger-ui/index.html#/
--
Swagger를 통해서 api 명세서를 더 보기 간편하게 전달하는 방법은 다양하다.
'springboot' 카테고리의 다른 글
[SpringBoot] orElse와 orElseGet 차이점 (0) | 2024.08.10 |
---|---|
[SpringBoot] GPT 3.5 AI 사용하기 (0) | 2024.03.24 |
[SpringBoot] KOMORON을 이용해서 형태소 분석하기 (0) | 2024.03.23 |
[SpringBoot] 인텔리제이 안에서 데이터베이스 접근하기 (0) | 2024.03.23 |
[SpringBoot] Swagger 간편 어노테이션 정리 (0) | 2024.03.21 |