Spring Boot에 Swagger 2 통합을 통한 REST API 문서 자동 생성

Swagger 2란?

Swagger 2는 RESTful 웹 서비스의 설계, 문서화, 테스트를 지원하는 강력한 오픈소스 프레임워크입니다. Spring Boot 애플리케이션과 쉽게 통합되어 API 문서를 자동으로 생성하고, 브라우저 기반 UI를 통해 실시간으로 API를 테스트할 수 있습니다.

주요 어노테이션 소개

  • @Api: 컨트롤러 클래스에 적용하여 그룹화된 API의 용도를 설명합니다.
  • @ApiOperation: 개별 엔드포인트 메서드에 사용되며, 해당 API 동작에 대한 설명을 제공합니다.
  • @ApiParam: 단일 파라미터에 대한 설명을 추가합니다. 기본값, 필수 여부 등을 설정 가능합니다.
  • @ApiImplicitParams@ApiImplicitParam: 여러 HTTP 요청 파라미터(예: 쿼리 또는 헤더)를 설명할 때 사용됩니다.
  • @ApiModel: DTO 또는 폼 객체 클래스에 적용하여 모델의 의미를 명시합니다.
  • @ApiModelProperty: 모델 클래스 내 필드에 적용하여 각 속성의 역할을 설명합니다.
  • @ApiIgnore: 특정 메서드나 파라미터가 문서에 포함되지 않도록 제외시킵니다.

의존성 추가

Maven 기준으로 다음과 같은 의존성을 pom.xml에 포함해야 합니다. Guava 버전 충돌을 방지하기 위해 일부 의존성을 제외 처리합니다.

<!-- Swagger 2 Core -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <exclusions>
        <exclusion>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- Guava 재정의 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1-jre</version>
</dependency>

<!-- Swagger UI -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Swagger 구성 설정

다음과 같이 Java Configuration 클래스를 작성하여 Swagger를 활성화하고 문서 정보를 정의합니다.

@Configuration
@EnableSwagger2
public class ApiDocumentationConfig {

    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                // @ApiOperation이 붙은 메서드만 문서화 대상으로 선택
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 모든 경로 허용
                .paths(PathSelectors.any())
                .build()
                // 보안 설정 (예: JWT 토큰)
                .securitySchemes(List.of(apiKey()))
                // 문서 메타정보 설정
                .apiInfo(metadata());
    }

    private ApiInfo metadata() {
        return new ApiInfoBuilder()
                .title("足浴兄弟 API 문서")
                .description("온라인 예약 시스템 백엔드 API")
                .version("1.0.0")
                .termsOfServiceUrl("http://localhost:8080/terms")
                .build();
    }

    private ApiKey apiKey() {
        return new ApiKey("Authorization", "token", "header");
    }
}

컨트롤러에 어노테이션 적용

실제 API 엔드포인트에 Swagger 어노테이션을 부착하여 문서를 완성합니다.

@RestController
@RequestMapping("/api/v1")
@Api(tags = "인증 관리")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    @ApiOperation(value = "사용자 로그인", notes = "휴대폰 번호와 비밀번호로 인증 수행")
    public ResponseEntity<ApiResponse<TokenResult>> login(
            @Valid @RequestBody LoginRequest request) {
        TokenResult result = authService.authenticate(request.getPhone(), request.getPassword());
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    @GetMapping("/logout")
    @ApiOperation("로그아웃")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "token", value = "액세스 토큰", required = true, paramType = "header")
    })
    public ResponseEntity<ApiResponse<Void>> logout(@RequestHeader("token") String token) {
        authService.invalidate(token);
        return ResponseEntity.ok(ApiResponse.success());
    }
}

DTO 클래스에 모델 정의

@Data
@ApiModel(description = "로그인 요청 데이터 구조")
public class LoginRequest {

    @ApiModelProperty(value = "사용자 휴대폰 번호", example = "13800138000", required = true)
    @NotBlank(message = "휴대폰 번호는 필수입니다.")
    private String phone;

    @ApiModelProperty(value = "비밀번호", example = "password123", required = true)
    @NotBlank(message = "비밀번호는 필수입니다.")
    private String password;
}

정적 리소스 매핑 (CORS 환경에서 필요)

Spring MVC에서 CORS를 사용하는 경우, Swagger UI 리소스 접근을 허용하도록 정적 핸들러를 설정해야 합니다.

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(false)
                .maxAge(3600);
    }
}

모든 설정 완료 후, 애플리케이션 실행 주소에 http://localhost:8080/swagger-ui.html 접속 시 Swagger UI가 표시됩니다.

태그: swagger2 spring-boot rest-api api-documentation springfox

5월 25일 14:12에 게시됨