Swagger란?
- Swagger는 개발자가 REST API 서비스를 설계, 빌드, 문서화할 수 있도록 도와준다.
- Spring Boot에서 특정 어노테이션을 달아주면 REST API 문서를 자동으로 구성해준다. 또한, 수정시 즉시 반영된다.
- 간단하게 Resultful API를 요청을 보내고 응답을 수신하는 테스트를 할 수 있다.
Swagger 세팅하기
해당 링크에서 Gradle(Kotlin) 에 있는 코드 복사
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
implementation("io.springfox:springfox-swagger-ui:3.0.0")
build.gradle 안에 위 라이브러리 추가 & reload gradle
dependencies {
implementation("io.springfox:springfox-boot-starter:3.0.0")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("io.swagger.core.v3:swagger-annotations:2.2.8")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("com.mysql:mysql-connector-j")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
application.yml - mysql 접속 정보 & 스웨거 설정 세팅
server:
port: 8080
spring:
datasource:
url: 호스트 url
username: 유저 계정
password: 유저 비밀번호
driver-class-name: com.mysql.cj.jdbc.Driver
mvc:
pathmatch:
matching-strategy: ant_path_matcher
- mvc 옵션 설정안해주면 서버 시작시 에러 - 스프링 부트 2.6 버전 ㅎ문제(https://u-comensee.tistory.com/165)
@Api(tags = ["health-check"]) 스웨거 어너테이션 사용 후 서버 시작
import io.swagger.annotations.Api
@Api(tags = ["health-check"])
@RestController
class HealthCheckController {
@GetMapping("health-check")
fun check() = ResponseEntity.ok(HttpStatus.OK)
}
http://localhost:8080/swagger-ui/index.html#/ 접속
Swagger configuration 설정
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import springfox.documentation.builders.ApiInfoBuilder
import springfox.documentation.builders.PathSelectors
import springfox.documentation.builders.RequestHandlerSelectors
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
@Configuration
@EnableWebMvc
class SwaggerConfig {
@Bean
fun swaggerApi(): Docket = Docket(DocumentationType.OAS_30)
.consumes(getConsumeContentTypes()) // request 타입
.produces(getProduceContentTypes()) // response 타입
.apiInfo(swaggerInfo()) // swagger 문서 정보
.select()
.apis(RequestHandlerSelectors.basePackage("com.project.boilerplate")) // swagger 적용 base패키지
.paths(PathSelectors.any()) // base패키지의 경로 필터링
.build()
.useDefaultResponseMessages(false)
private fun swaggerInfo() = ApiInfoBuilder()
.title("프로젝트 API Specification")
.description("프로젝트 관련 api 설명서 입니다.")
.version("1.0.0")
.build()
private fun getConsumeContentTypes(): Set<String> {
val consumes = HashSet<String>()
consumes.add("multipart/form-data")
return consumes
}
private fun getProduceContentTypes(): Set<String> {
val produces = HashSet<String>()
produces.add("application/json;charset=UTF-8")
return produces
}
}
UserController생성
@Api(tags = ["유저"], description = "유저 도메인 관련 컨트롤러입니다.")
@RestController
@RequestMapping("users")
class UserController {
@GetMapping
fun getUsers() = ResponseEntity.ok(listOf("user1","user2"))
}
http://localhost:8080/swagger-ui/index.html#/ 접속
- SwaggerConfig 에 설정한대로 내용이 변경
- @Api - description 속성과 tags 속성으로 api 관련 컨트롤러 내용 명시
결론
- 단연컨데 Swagger는 간단하게 세팅해서 유용하게 사용할 수 있는 좋은 Open Source이다. 현재까지도 프론트와 협업을 하면서도 많이쓰이는 Open Source중에 하나이다. 현재 기본적인 세팅만 이글에 설명하였고 Swagger에서 제공하는 다양한 어노테이션 기반 기능들은 Swagger Annotation 이 링크를 참고하면 좋다.
reference
'Kotlin' 카테고리의 다른 글
[JPA] 예상치 못한 N+1 문제 해결하기 (1) | 2024.02.27 |
---|---|
[Spring Boot 3.0 / Spring Security 6.0] Controller에서 시큐리티 인증 mocking 후 테스트 하기(401 피하기) (0) | 2024.01.11 |
중복 데이터로 인한 Single{}의 IllegalArgumentException (0) | 2023.08.23 |
[Kotlin] @PreAuthorize를 사용한 인가(Authorization)처리 (0) | 2023.04.29 |
[Kotlin, Spring, JPA] Boilerplate 프로젝트 만들기 (0) | 2023.02.20 |