5.9 KiB
5.9 KiB
SpringDoc OpenAPI
SpringDoc OpenAPI는 Spring Boot 애플리케이션에서 OpenAPI 3 문서를 자동으로 생성해주는 라이브러리입니다.
기존 SpringFox보다 간결하고 최신 OpenAPI 표준을 준수하며, 유지보수가 활발한 것이 장점입니다.
주요 특징
- Spring Boot와 완벽한 호환
- Swagger UI 자동 제공
- REST API 문서를 코드에서 바로 생성
- OpenAPI 3 표준 지원
SpringDoc OpenAPI 설정
Spring Boot 3 기준으로 Maven 또는 Gradle에 다음 의존성을 추가합니다.
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6")
Spring Boot 애플리케이션을 실행한 후, 브라우저에서 다음 URL로 접속합니다.
http://localhost:8080/swagger-ui.html
http://localhost:8080/v3/api-docs
swagger-ui.html을 열면 API 문서를 자동으로 확인할 수 있습니다.
SpringDoc OpenAPI 기본 사용법
컨트롤러에서 API 문서 자동 생성
아래와 같이 Spring Boot 컨트롤러에 OpenAPI 어노테이션을 추가하면,
Swagger 문서가 자동으로 생성됩니다.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/users")
@Tag(name = "User API", description = "사용자 관리 API")
public class UserController {
@GetMapping
@Operation(summary = "사용자 목록 조회", description = "모든 사용자의 목록을 조회합니다.")
public List<Map<String, String>> getUsers() {
return List.of(Map.of("id", "1", "name", "Alice"));
}
@GetMapping("/{id}")
@Operation(summary = "사용자 정보 조회", description = "특정 사용자의 정보를 조회합니다.")
public Map<String, String> getUser(@PathVariable String id) {
return Map.of("id", id, "name", "Alice");
}
@PostMapping
@Operation(summary = "사용자 추가", description = "새로운 사용자를 추가합니다.")
public String addUser(@RequestBody Map<String, String> user) {
return "User " + user.get("name") + " added!";
}
}
설명
@Tag(name = "User API", description = "사용자 관리 API")→ API 그룹을 정의@Operation(summary = "제목", description = "설명")→ API 설명 추가- API 문서는
http://localhost:8080/swagger-ui.html에서 확인 가능
요청 및 응답 모델 정의 (@Schema)
Swagger 문서에서 요청과 응답 데이터를 명확하게 정의하려면 DTO 클래스에 @Schema 어노테이션을 사용합니다.
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "사용자 정보")
public class UserDto {
@Schema(description = "사용자 ID", example = "1")
private Long id;
@Schema(description = "사용자 이름", example = "Alice")
private String name;
// 생성자, Getter, Setter 생략
}
@Schema(description = "설명")→ 필드 설명 추가example = "1"→ API 문서에서 예제 값 표시
API 응답 코드 설정 (@ApiResponse)
각 API 메서드에 응답 코드를 명시할 수 있습니다.
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@GetMapping("/{id}")
@Operation(summary = "사용자 정보 조회", description = "특정 사용자의 정보를 조회합니다.")
@ApiResponse(responseCode = "200", description = "성공")
@ApiResponse(responseCode = "404", description = "사용자를 찾을 수 없음")
public UserDto getUser(@PathVariable Long id) {
return new UserDto(id, "Alice");
}
@ApiResponse(responseCode = "200", description = "성공")→ HTTP 응답 코드 설명 추가
OpenAPI 문서 커스터마이징
Spring Boot의 application.yml 또는 application.properties에서 OpenAPI 문서를 설정할 수 있습니다.
springdoc:
api-docs:
enabled: true # API 문서 활성화
swagger-ui:
path: /swagger-ui.html # Swagger UI 경로 변경
operations-sorter: method # API 정렬 방식 (메서드명 기준)
show-actuator: true # Actuator API 문서 포함 여부
커스텀 OpenAPI 설정 (Security 포함)
Spring Boot 애플리케이션에서 JWT 인증을 Swagger UI에 적용하려면 OpenAPI 빈을 직접 설정할 수도 있습니다.
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info().title("사용자 API")
.version("1.0")
.description("사용자 관리 서비스"))
.addSecurityItem(new SecurityRequirement()
.addList("BearerAuth"))
.schemaRequirement("BearerAuth",
new SecurityScheme().name("Authorization")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT"));
}
}
- JWT 인증을 위한
SecurityScheme설정 가능 - API 문서에 보안 설정을 추가할 수 있음
5. 정리
| 기능 | 설명 |
|---|---|
| Swagger UI | http://localhost:8080/swagger-ui.html에서 확인 가능 |
| 자동 문서 생성 | @Operation, @Tag 등을 사용하여 API 설명 추가 |
| DTO 모델 문서화 | @Schema를 사용하여 요청/응답 모델 정의 |
| 응답 코드 정의 | @ApiResponse로 HTTP 응답 코드 설명 가능 |
| 보안 적용 | JWT, OAuth2 등의 인증을 문서에 포함 가능 |