OpenAPI 3 - Swagger

2024. 3. 4. 02:01SpringBoot

현재 SpringBoot에서는 유지보수 되지 않고 버그가 많은 springfox 대신 springdoc를 주로 사용을 주로 하는데, springdoc-openapi 라이브러리는 아래의 항목들을 지원한다.

  • OpenAPI 3
  • Spring Boot 1, Spring Boot 2, Spring Boot 3
  • JSR-303 (ex. @NotNull, @Min, @Max, @Size)
  • Swagger-ui
  • OAuth 2

SpringDoc OpenAPI UI 버전

SpringDoc OpenAPI UI 버전 (maven repository)

 


application.yml 설정

springdoc:
  version: '@project.version@'
  api-docs:
    path: /api-docs
  default-consumes-media-type: application/json
  default-produces-media-type: application/json
  swagger-ui:
    operations-sorter: alpha
    tags-sorter: alpha
    path: /
    disable-swagger-default-url: true
    display-query-params-without-oauth2: true
    doc-expansion: none
  paths-to-match:
    - /api/**
  • springdoc
    • api-docs.path
      • 기본값 : /v3/api-docs
      • spring boot 웹 애플리케이션의 api를 OpenAPI 3을 이용하여 json 형식화 한것의 경로
    • default-consumes-media-type
      • 기본값 : application/json
      • request media type 의 기본 값
    • default-produces-media-type
      • 기본값 : /*
      • response media type 의 기본 값
    • swagger-ui.operations-sorter
      • 기본값 : 컨트롤러 내에서 정의한 api 메서드 순
      • 태그 내 각 api의 정렬 기준
      • alpha(알파벳 오름차순), method(http method 순)
    • swagger-ui.tags-sorter
      • 태그 정렬 기준
    • swagger-ui.path
      • 기본 값 : /swagger-ui.html
      • Swagger HTML 문서 경로
    • swagger-ui.disable-swagger-default-url
      • swagger-ui default url인 petstore html 문서 비활성화 여부
      • v1.4.1 이상 버전부터 지원합니다.
    • swagger-ui.display-query-params-without-oauth2
      • 기본 값 : false
      • json화 된 config파일 대신 파라미터를 이용하여 swagger-ui에 접근하도록 합니다.
      • api-docs(/api-docs) 및 swagger-ui.configUrl(/api-docs/swagger-config)를 두번씩 호출하는 것을 방지합니다.
      • v1.4.1 이상 버전부터 지원합니다.
    • swaggerui.doc-expansion
      • 기본 값: list
      • tag와 operation을 펼치는 방식에 대한 설정
      • String=["list", "full", "none"]
      • none으로 설정할 경우, tag 및 operation이 모두 닫힌채로 문서가 열립니다.
    • paths-to-match
      • OpenAPI 3 로 문서화할 api path 리스트

@Controller

@Tag(name = "인증", description = "인증 관련 api 입니다.")	// (1) 
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Operation(summary = "로그인 메서드", description = "로그인 메서드입니다.")	// (2)
    @ApiResponses(value = {	// (3)
    	// (4)
        @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = LoginResponse.class))),
        @ApiResponse(responseCode = "400", description = "bad request operation", content = @Content(schema = @Schema(implementation = LoginResponse.class)))
    })
    @PostMapping(value = "login")
    public ResponseEntity<LoginResponse> login(LoginRequest loginRequest) {
        LoginResponse loginResponse = new LoginResponse("accessTokenValue", "refreshTokenValue");
        return ResponseEntity.ok().body(loginResponse);
    }
}

 

(1) @Tag : api 그룹 설정을 위한 어노테이션 입니다.

name 속성으로 태그의 이름을 설정할 수 있고, description 속성으로 태그에 대한 설명을 추가할 수 있습니다.

@Tag에 설정된 name이 같은 것 끼리 하나의 api 그룹으로 묶게 됩니다.

 

(2) @Operation : api 상세 정보를 위한 어노테이션 입니다.

summary 속성으로 api에 대한 간략한 설명, description 속성으로 api에 대한 상세 설명을 추가할 수 있으며, responses, parameters 속성 등을 추가로 적용할 수 있습니다.

 

(3) @ApiResponses : 바로 아래에서 설명하는 여러 개의 @ApiReponse를 묶기 위한 어노테이션 입니다.

 

(4) @ApiResponse : api의 response 설정을 위한 어노테이션 입니다.

responseCode 속성으로 http 상태 코드를 설정할 수 있고, description으로 response에 대한 설명을 추가할 수 있습니다. @ApiResponse 설정을 통해 응답 결과로 나올 수 있는 response 구조를 미리 확인할 수 있게 됩니다.

api 조회 성공 및 실패 시 발생될 상태 코드 및 Response 구조를 설정하고자 할 때 유용하게 사용될 수 있습니다.

(implementation에는 responseBody로 제공될 클래스 타입만 설정할 수 있습니다.)

 

@Parameter : api parameter 설정을 위한 어노테이션 입니다.

name으로 파라미터의 이름, description으로 설명, in으로 파라미터의 위치를 설정할 수 있습니다.

Reference

https://springdoc.org/

https://tall-developer.tistory.com/27

https://blog.jiniworld.me/145?category=961894

'SpringBoot' 카테고리의 다른 글

[Spring Cloud] Netflix Eureka  (0) 2024.04.04
Spring Cloud  (0) 2024.04.04