HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🛁
공부기록
/
🍀
Spring
/
🏐
Swagger 적용해보기
🏐

Swagger 적용해보기

들어가기전 Swagger와 OpenAPISpringfox-swagger vs Springdoc-openapi우리는 SpringDoc을 사용하자 !세팅 - 의존성 추가세팅 - security config 설정어디가 어떻게 변경되었을까?
 

들어가기전

  • Open API와 OpenAPI 뭐가다름?
    • Open API : 개방된 API로 누구나 사용될 수 있도록 API의 endpoint가 개방되어있다. ex) 우체국의 우편번호 API
    • OpenAPI : OpenAPI Specipiation(OAS) 라고 부르며 이는 REST API를 정의된 규칙에 맞게 API 스펙을 json이나 yaml로 표현하는 방식이다.
      • 즉 REST API 디자인에 대한 정의(Specification) 표준
 

Swagger와 OpenAPI

  • 예전에는 Swagger 이름으로 불렸따가 2015년에 전환되어 OpenAPI 3.0 Specification으로 칭하게 되었다.
  • OpenAPI = 사양, REST API 디자인에 대한 정의
  • Swagger = 사양 구현을 위한 도구로 API 들이 갖고있는 specification을 정의할 수 있는 tool중 하나이다.
  • 둘의 차이는?
    • What is OpenAPI? Swagger vs. OpenAPI | Swagger Blog
      This year marked the official release of OpenAPI 3.0, the latest version of the OpenAPI specification.For those involved in API development, the release of OAS 3.0 is, well... kind of a big deal.Why? One of the most notable reasons why the release is so important is that OpenAPI 3.0 is the first ...
      What is OpenAPI? Swagger vs. OpenAPI | Swagger Blog
      https://swagger.io/blog/api-strategy/difference-between-swagger-and-openapi/
      What is OpenAPI? Swagger vs. OpenAPI | Swagger Blog
  • OpenAPI란?
    • OpenAPI 란? (feat. Swagger)
      Overview 이 문서에서는 API의 기본적인 정의는 알고 있다는 전제하에 OpenAPI와 Swagger의 개념, 차이점, 비교적 최근(2017-07-26) 업데이트한 OpenAPI 3.0에 대해서 알아보도록 하겠습니다. 1. OpenAPI? Open API? 검색창에 OpenAPI라고 치면 수많은 결과가 나옵니다. 근데 의미가 통일되지 않고 중구난방인데요... 그래서 더 헷갈립니다. 저도 이게 대체 무슨 뜻인가 싶었습니다. 그래서 정리하는 정확한 정의!
      https://gruuuuu.github.io/programming/openapi/
      OpenAPI 란? (feat. Swagger)
 

Springfox-swagger vs Springdoc-openapi

  • 공통점은?
    • Swagger를 사용하고 API 문서를 쉽게 쓸 수 있도록 해준다.
    • 스프링 프레임워크를 사용하는 프로젝트에서 사용하는 라이브러리
  • Springfox
    • 2018년까지 많은 사람들이 사용하다가 2018년 6월 업데이트가 중지되었다가 2020년 6월 새로운 버전을 출시함
  • SpringDoc
    • 2019년 7월 출시되어 업데이트가 없어진 springfox 대신에 사람들이 많이 사용하기 시작했다.
    • webflux non-blocking 비동기 방식의 웹 개발을 지원한다.
 

우리는 SpringDoc을 사용하자 !

세팅 - 의존성 추가

implementation 'org.springdoc:springdoc-openapi-ui:1.6.9' implementation 'org.springdoc:springdoc-openapi-security:1.6.9'
 

세팅 - security config 설정

@Configuration @Profile({"dev", "local", "mem"}) public class SwaggerConfig { @Bean public OpenApiCustomiser customOpenApi() { return openApi -> { String bearer = "bearer"; openApi .info(new Info().title("instakyuram")) .components( openApi.getComponents().addSecuritySchemes( bearer, new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme(bearer) .bearerFormat("JWT") .in(SecurityScheme.In.HEADER) .name("Authorization") ) ) .addSecurityItem( new SecurityRequirement() .addList(bearer, Arrays.asList("read", "write")) ); }; } }
  • Springfox와 달리 다른 config 설정을 해주지 않아도 된다.
notion image
  • 기존의 yml 파일에 설정했던 팀 스웨거 정보이다. 이 부분의 위 코드의 .info(new Info().title(”instakyuram”))에 추가할 수 있다.
 

어디가 어떻게 변경되었을까?

  • 기존의 코드(Spring fox)
@Api(tags= "팔로우, 팔로잉 api") @RestController @RequestMapping("/api/friendships") public class FollowRestController { private final FollowService followService; public FollowRestController(FollowService followService) { this.followService = followService; } @Operation( summary = "팔로우 가능 여부 판단", description = "팔로우 할 수 있는 대상인지 확인합니다.", responses = { @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "팔로우 가능 여부 true/false"), } ) @GetMapping("/{memberId}") public ApiResponse<Boolean> isFollowed(@AuthenticationPrincipal JwtAuthentication auth, @PathVariable Long memberId) { public ApiResponse<Boolean> isFollowed( @AuthenticationPrincipal JwtAuthentication auth, @Parameter( name = "팔로우 할 대상의 식별 값", description = "사용자 id 값(숫자)을 입력합니다.", in = ParameterIn.PATH, required = true ) @PathVariable Long memberId) { return new ApiResponse<>(followService.isFollowed(auth.id(), memberId)); }
 
  • Spring Doc 사용된 코드
@Tag(name = "팔로우, 팔로잉 api") @RestController @RequestMapping("/api/friendships") public class FollowRestController { private final FollowService followService; public FollowRestController(FollowService followService) { this.followService = followService; } @Operation(summary = "팔로우 가능 여부 판단", description = "팔로우 할 수 있는 대상인지 확인합니다.") @GetMapping("/{memberId}") public ApiResponse<Boolean> isFollowed( @AuthenticationPrincipal JwtAuthentication auth, @PathVariable Long memberId) { return new ApiResponse<>(followService.isFollowed(auth.id(), memberId)); }