Back-End/Spring
Springdoc - OpenApi (swagger)
HappyWeasel
2020. 12. 23. 10:06
현재 Spring Boot에서 swagger를 지원하는 라이브러리 중 추천하는 라이브러리는 2가지가 있다.
1. springfox
- 2년간 업데이트가 안 되다가 최근에 업데이트 되었다.
- 이번에 업데이트가 되면서 webflux도 지원한다.
2. springdoc
- 현재 꾸준한 업데이트를 지원하고 있다.
- 참고 : springdoc.org/
OpenAPI 3 Library for spring-boot
Library for OpenAPI 3 with spring boot projects. Is based on swagger-ui, to display the OpenAPI description.Generates automatically the OpenAPI file.
springdoc.org
swagger doc
swagger.io/tools/open-source/open-source-integrations/
build.gradle
// spring doc open api
implementation 'org.springdoc:springdoc-openapi-ui:1.5.2'
application.yml
# Spring Doc Config
springdoc:
api-docs:
path: /api-docs #doc default path : /v3/api-docs
groups.enabled: true
swagger-ui:
path: /swagger-ui.html #swagger default path : /swagger-ui.html
display-request-duration: true
groups-order: DESC
OpenApiConfig.class
@OpenAPIDefinition(info = @Info(title = "API 명세서", description = "API 서버"))
@SecuritySchemes(
value = {
@SecurityScheme(name = "basicAuth", type = SecuritySchemeType.HTTP, scheme = "basic"),
@SecurityScheme(name = "bearerAuth", type = SecuritySchemeType.HTTP, scheme = "bearer")
})
@Configuration
public class OpenApiConfig {
@Profile({"local", "dev"})
@Bean
public GroupedOpenApi privateApi() {
String[] paths = {"/test/**", "/test2/**"};
return GroupedOpenApi.builder().group("private").pathsToMatch(paths).build();
}
}
interface로 Api 파일 만들어서 cotroller에서 구현하면 코드가 깔끔해진다.
@Tag(name = "Guest", description = "Guest API")
public interface Api {
@Operation(
summary = "guest",
tags = {"Guest"},
security = @SecurityRequirement(name = "basicAuth"))
@ApiResponses(
value = {
@ApiResponse(
responseCode = "1000",
description = "성공",
content = {
@Content(
mediaType = "application/json",
schema = @Schema(implementation = CustomResponse.class))
})
})
CustomResponse Login(@RequestBody DeviceRequest deviceRequest);
DTO
@Data
public class DeviceRequest {
@Schema(required = true, example = "true", description = "마케팅 정보 앱 알림 수신 동의")
@NotNull
private Boolean pushYn = true;
}