HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🍗
[New] 조규현팀
/
🏗️
Tech Store
/
🚁
Swagger - SpringDoc
🚁

Swagger - SpringDoc

담당자들
카테고리
Skill
주제
API 문서화
나의 블로그
완료율%
프로젝트
인스타뀨램
상태
완료
 
notion image

🔎 들어가기전에

Open API와 OpenAPI

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

Swagger와 OpenAPI

  • 예전에는 Swagger 이름으로 불렸다가 2015년에 전환되어 OpenAPI 3.0 Specification으로 칭합니다.
  • OpenAPI = 사양, REST API 디자인에 대한 정의
  • Swagger = 사양 구현을 위한 도구 => API들이 갖고있는 specification을 정의할 수 있는 tool 중 하나
  • Swagger와 OpenAPI의 차이
  • OpenAPI란 ?

🍉 Springfox-swagger vs springdoc-openapi

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

⛄️ 우리는 spring doc을 사용합니다.

🦁 Setting

1. build.gradle dependency 추가

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

2. 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")) ); }; } }
  • spring fox와 달리 다른 config 설정을 해주지 않아도 됩니다.
    • notion image
  • 기존의 yml 파일에 설정했던 저희 팀 swagger의 정보입니다. 이 부분은 위 코드의 .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)); }

🐥 UI 보기

notion image
  • http://localhost:8080/swagger-ui.html 로 들어갈 수 있습니다.

🏓 JSon 형식으로 보기

notion image
 
  • instakyuram 아래의 /v3/api-docs 를 누르면 josn 형식의 파일을 볼 수 있습니다. => 이 파일은 export하면 postman에서도 사용할 수 있습니다.
  • 위의 사진에 보시면 security config 에서 설정해준 것들을 볼 수 있습니다.

🪐 변경된 점

  • 기존 @Api(tags ="") 에서 @Tag(name ="") 로 변경되었습니다.
    • 해당 어노테이션은 컨트롤러를 설명합니다.
  • @Operation은 동일하게 가져가지만 summary, description만 사용합니다.
    • 해당 어노테이션은 HTTP 메서드에 대한 명세입니다.
      • notion image
  • request와 respoonse를 따로 명시해주지 않아도 request값과 response 요청을 정리해줍니다.
  • response를 예외마다 구분해서 정리해줍니다.

GetMapping 에서 object 받기

 
notion image
  • 해당 api는 기존에 lock 설정용으로 만들어둔 api를 수정했습니다. 원래 patch이지만 해당 부분 테스트를 위해 Get으로 변경했습니다.
 
notion image
  • 위의 코드 형태를 swagger로 보면 request를 id 처럼 받는게 아니라 row 처럼 받고 있습니다.
 
notion image
  • 코드에 @ParameterObject 를 추가해주면 ?
 
notion image
  • 네 ! 아무것도 안 나옵니다. 왜냐하면 record 이기 때문이죠 ! 이부분은 멘토님께서 찾아 봐주신다고 하셨습니다 ! ⇒ 멘토님 say ! default는 record로 가고 해당 파라미터가 필요한 부분만 class로 갑시다
  • record를 class로 변경해주고 getter를 만들어주면
notion image
  • 이렇게 위의 id 처럼 값을 쉽게 받아올 수 있습니다 !
  • 멘토님께서 @ParameterObject 를 사용하라고 말씀해주셨습니다 !
 

 

💁🏻 swagger를 사용하면서 (멘토님 say)

  • 작은 곳에서도 성능향상을 기대할 수 있습니다.
  • 프론트는 api 명세를 보고 개발합니다.
    • 현재 프로젝트에서 프론트를 개발할 때 백엔드 서버를 띄우고 스웨거를 보고 연동 하는걸 바랬습니다.
    • 코드기반이 아닌 문서를 기반으로한 개발
  • 테스트 할 때도 postman 말고 스웨거에서 api 써보면 좋지 않을까요?

🐯 멘토님이 공유해주신 링크

  • baeldug 의 spring doc을 사용한 Spring REST API 문서화
www.baeldung.com
https://www.baeldung.com/spring-rest-openapi-documentation
  • security 설정
OpenAPI 3 Library for spring-boot
springdoc-openapi java library helps to automate the generation of API documentation using spring boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on spring configurations, class structure and various annotations. Automatically generates documentation in JSON/YAML and HTML format APIs. This documentation can be completed by comments using swagger-api annotations.
OpenAPI 3 Library for spring-boot
https://springdoc.org/#how-to-configure-global-security-schemes
OpenAPI 3 Library for spring-boot
  • springdoc-openapi 공식 : 어노테이션 찾기 가능
OpenAPI 3 Library for spring-boot
springdoc-openapi java library helps to automate the generation of API documentation using spring boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on spring configurations, class structure and various annotations. Automatically generates documentation in JSON/YAML and HTML format APIs. This documentation can be completed by comments using swagger-api annotations.
OpenAPI 3 Library for spring-boot
https://springdoc.org/
OpenAPI 3 Library for spring-boot