IT 개발 관련/[Spring]

[Spring] Swagger 라이브러리 가이드

Baileyton 2024. 5. 28. 14:22
728x90

Swagger란?

Swagger는 API를 설계, 빌드, 문서화, 소비 및 검증하기 위한 강력한 오픈 소스 프레임워크입니다. 주로 RESTful API에 적합하며, API의 설계 및 개발 프로세스를 효율적으로 관리하고 문서화할 수 있도록 지원합니다. Swagger는 개발자들이 API를 쉽게 이해하고 사용할 수 있도록 API에 대한 명세를 제공하고, 이를 기반으로 자동으로 API 문서를 생성할 수 있습니다.

 

Springboot에 Swagger 적용하기

실습환경

Spring boot 2.7.14

 

build.gradle

// swagger
implementation 'io.springfox:springfox-boot-starter:3.0.0'
implementation 'io.springfox:springfox-swagger-ui:3.0.0'

 

SwaggerConfig 작성

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger 문서 제목")
                .description("Swagger 문서 설명")
                .version("1.0")
                .build();
    }
}

 

application.properties 설정

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

 

문서 정규화 하기

기본적으로 controller에 대한 이름, 메서드 정의, In/out에 대한 정의를 할 수 있다.

  • @ApiOperation(value = "", notes = "") : 특정 API의 요약과 설명을 지정합니다.
  • @ApiResponses : API 결과에 따른 코드와 설명을 추가합니다.
@ApiOperation(value = "조회 API", notes = "ㅇㅇ을 조회합니다.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "성공", response = Class.class),
            @ApiResponse(code = 400, message = "잘못된 요청"),
            @ApiResponse(code = 401, message = "인증 실패"),
            @ApiResponse(code = 403, message = "접근 거부"),
            @ApiResponse(code = 404, message = "데이터를 찾을 수 없음"),
            @ApiResponse(code = 500, message = "내부 서버 오류")
    })

 

이렇게 설정하면 Swagger를 사용하여 API를 설계하고 문서화할 수 있습니다. Swagger UI를 통해 개발자들은 쉽게 API를 테스트하고 이해할 수 있습다.

728x90