본문으로 바로가기

[Spring] Open API 3 (with Swagger3)

category Framework/Spring 2022. 1. 11. 18:15

1. Swagger 란?

Swagger 는 OAS(Open Api Specification)를 위한 프레임워크입니다.

개발자들의 필수 과제인 API 문서화를 쉽게 할 수 있도록 도와주며, 파라미터를 넣어서 실제로 어떤 응답이 오는지 테스트도 할 수 있습니다.

또한, 협업하는 클라이언트 개발자들에게도 Swagger 만 전달해주면 API Path 와 Request, Response 값 및 제약 등을 한번에 알려줄 수 있습니다.

 

2. 적용

2.1 의존성 추가

/* build.gradle */

dependencies {
    // ..
	implementation 'org.springdoc:springdoc-openapi:1.6.3'
	implementation 'org.springdoc:springdoc-openapi-ui:1.6.3'
    // ..
}

2.2 Configuration

@Configuration
public class OpenApiDocsConfig {

    @Bean
    public OpenAPI openAPI() {

        Contact contact = new Contact()
                .name("Contact Your Name")
                .email("chlwn.lee@gmail.com");

        License license = new License().name("Copyright(C) CWY Corporation All rights reserved.");

        Info info = new Info()
                .title("API Documentation")
                .version("1.0.0")
                .description("API Description")
                .termsOfService("http://swagger.io/terms/")
                .contact(contact)
                .license(license);

        return new OpenAPI()
                .components(new Components())
                .info(info);
    }
}
  • Docket: Swagger 설정의 핵심이 되는 Bean
  • useDefaultResponseMessages: Swagger 에서 제공해주는 기본 응답 코드 (200, 401, 403, 404). false 로 설정하면 기본 응답 코드를 노출하지 않음
  • apis: api 스펙이 작성되어 있는 패키지 (Controller) 를 지정
  • paths: apis 에 있는 API 중 특정 path 를 선택
  • apiInfo:Swagger UI 로 노출할 정보

2.3 Properties

...
springdoc:
#  api-docs:
#    path: /api-doc
#
  default-consumes-media-type: application/json
  default-produces-media-type: application/json
#  swagger-ui:
#    operations-sorter: alpha
#    tags-sorter: alpha
#    path: /swagger-ui.html
#    disable-swagger-default-url: true
  paths-to-match:
    - /auth/**
    - /api/**
  paths-to-exclude:
    - /
...

2.4 Controller 적용

@Operation(summary = "Find User By ID", description = "Find User By ID")
@ApiResponses({
        @ApiResponse(responseCode = "200", description = "OK"),
        @ApiResponse(responseCode = "400", description = "BAD REQUEST"),
        @ApiResponse(responseCode = "404", description = "NOT FOUND"),
        @ApiResponse(responseCode = "500", description = "INTERNAL SERVER ERROR")
})
@GetMapping("/{id}")
public UserDto userById (@PathVariable(value = "id") Long id) {
    return userService.getById(id);
}

2.4 실행 후 접속

로컬 실행 후 아래의 URL 로 접속하면 된다.

 

3. 적용된 설정 확인

Swagger UI

 

Reference

'Framework > Spring' 카테고리의 다른 글

[Spring] 00. Spring Triangle 스프링의 핵심 3대 요소  (0) 2022.01.14
[Spring] Security 가 적용된 Test  (0) 2022.01.14
[Spring] Swagger 3  (0) 2022.01.11
[Spring] Filter & Interceptor  (0) 2021.12.22
[Spring] MyBatis Log 설정하기  (0) 2021.12.16