Book/스프링부트 핵심가이드

Swagger - REST API 명세 문서화

블로그 주인장 2023. 10. 26.

명세 문서화

  • 명세 : 해당 API가 어떤 로직을 수행하는지 설명하고 이 로직을 수행하기 위해 어떤 값을 요청하며 이에 따른 응답값으로는 무엇을 받을 수 있는 지 정리한 자료이다.
  • API는 개발 과정에서 계속 변경되므로 명세 문서도 주기적인 업데이트가 필요하다.

Swagger

명세 작업은 번거롭고 시간 또한, 오래 걸리기 때문에 이 같은 문제를 해결하기 위해서 사용하는 오픈소스 프로젝트이다.

 

Maven 의존성 추가

  • pom.xml 파일에 있는 <dependencies> 안에 해당 문구를 추가해준다.
<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

gradle 의존성 추가

  • build.gradle 파일에 있는 dependencies에 해당 문구를 추가해준다.
dependencies {
    implementation 'io.springfox:springfox-boot-starter:3.0.0'
    implementation 'io.springfox:springfox-swagger-ui:3.0.0'
}

Swagger 설정 코드 작성

이 클래스는 설정(Configuration)에 관한 클래스로 "config" 패키지를 생성한 후에 그 안에 생성한다.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.api"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Open API Test With Swagger")
                .description("설명 부분")
                .version("1.0.0")
                .build();
    }
}
  1. RequestHandlerSelectors.basePackage()  : Swagger에서 스캔할 패키지의 범위를 설정
  2. 현재 프로젝트의 루트 패키지인 'com.springboot.api'로 설정하여 하위패키지와 클래스 모두 스캔하여 문서를 생성

Swagger 페이지

프로젝트에서 애플리케이션을 실행한 후에 웹 브라우저에 http://localhost:8080/swagger-ui.html

접속하여 Swagger 페이지가 출력된다.

Swagger 명세 추가

@RequestParam을 활용한 GET 메서드에 대한 명세 세부 내용을 설정한다.

package com.springboot.api.controller;

import com.springboot.api.dto.MemberDto;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {

    @GetMapping("/request1")
    @ApiOperation(value = "GET 메서드 예제", notes = "@RequestParam을 활용한 GET-METHOD")
    public String getRequestParam1(@ApiParam(value = "이름", required = true) @RequestParam String name,
                                   @ApiParam(value = "이메일", required = true) @RequestParam String email) {
        return name + " " + email;
    }
    
}
  • @ApiOperation : 대상의 API의 설명을 작성하기 위한 어노테이션이다.
  • @ApiParam
    • 매개변수에 대한 설명 및 설정을 위한 어노테이션이다.
    • 메서드의 매개변수 뿐만 아니라 DTO 객체를 매개변수로 사용할 경우 DTO 클래스 내의 매개변수에도 정의할 수 있다.

Swagger [Try it out]

[Try it Out] 버튼을 클릭하면 각 항목의 값을 기입하면 통신 테스트를 할 수 있다.

 

[Execute] 버튼을 누르면 자동으로 완성된 URL을 확인할 수 있고, 그에 대한 결과값도 받아볼 수 있다.

반응형

댓글