본문으로 건너뛰기
Advertisement

3.9 OpenAPI(Swagger)로 API 문서 자동화

REST API를 제공할 때 요청/응답 스펙을 문서로 유지하고, 프론트엔드·외부 연동 개발자가 바로 호출해 볼 수 있게 하는 것이 실무 표준입니다. OpenAPI 3(구 Swagger)와 스프링 부트를 연동하면 컨트롤러 기반으로 API 문서를 자동 생성할 수 있습니다.

작성 기준: Spring Boot 3.2.x, springdoc-openapi-starter-webmvc-ui

1. 왜 API 문서 자동화인가?

  • 수동 문서: 코드와 문서가 어긋나기 쉽고, 버전 업데이트 시 누락이 생깁니다.
  • 자동 생성: 컨트롤러·DTO·애너테이션을 기반으로 문서가 생성되므로, 코드가 곧 문서가 됩니다.
  • Swagger UI: 브라우저에서 API 목록을 보고 바로 요청을 보내 테스트할 수 있습니다.

2. 의존성 추가 (springdoc-openapi)

Spring Boot 3에서는 springdoc-openapi를 사용합니다. (기존 springfox는 Boot 3 미지원)

dependencies {
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
}

별도 설정 없이도 애플리케이션 기동 후 다음 URL로 접근할 수 있습니다.

  • Swagger UI: http://localhost:8080/swagger-ui.html
  • OpenAPI JSON: http://localhost:8080/v3/api-docs

3. 기본 설정 (application.yml)

springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
operationsSorter: method
tagsSorter: alpha

4. API 정보 및 태그 보강

전역 API 설명·버전·태그는 @OpenAPIDefinition, @Info로 보강할 수 있습니다.

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info()
.title("My REST API")
.version("1.0")
.description("서비스 API 명세"));
}
}

5. 컨트롤러·DTO에 설명 추가

@Operation, @Parameter, @Schema로 요청/응답 의미를 문서에 반영할 수 있습니다.

@RestController
@RequestMapping("/api/users")
@Tag(name = "User API", description = "회원 관련 API")
public class UserController {

@Operation(summary = "회원 단건 조회", description = "ID로 회원 정보를 조회합니다.")
@Parameter(name = "id", description = "회원 ID", required = true)
@ApiResponses({
@ApiResponse(responseCode = "200", description = "성공"),
@ApiResponse(responseCode = "404", description = "회원 없음")
})
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<UserResponseDto>> getUser(@PathVariable Long id) {
// ...
}
}
@Schema(description = "회원 응답 DTO")
public record UserResponseDto(
@Schema(description = "회원 ID") Long id,
@Schema(description = "이메일") String email,
@Schema(description = "이름") String name
) {}

6. Spring Security와 함께 사용할 때

Actuator와 마찬가지로 Swagger UI·api-docs 경로를 인증에서 제외하거나, 개발 환경에서만 노출하는 경우가 많습니다.

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}

실무에서는 API 버전(예: /api/v1/)과 OpenAPI 문서 버전을 맞추고, CI에서 v3/api-docs를 JSON으로 추출해 API 컨트랙트 테스트나 클라이언트 코드 생성에 활용합니다.

Advertisement