Swagger는 RESTful API를 설계하고 문서화하는데 사용되는 오픈 소스 프레임워크입니다.
Swagger는 API의 구조를 정의하는데 사용할 수 있는 여러 도구와 라이브러리를 제공합니다. 이를 통해 API의 구조를 정의하는데 사용할 수 있는 여러 도구와 라이브러리를 제공합니다. 이를 통해 API 문서를 자동으로 생성하고, API를 테스트하는 인터페이스를 제공할 수 있습니다.
Swagger 라이브러리를 프로젝트에 추가합니다.
build.gradle dependencies에 한 줄을 추가 합니다.
(Spring boot 3.0 버전부터 하나만 선언
dependencies {
// swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'
}
Swagger 설정 파일을 생성합니다.
config 폴더 안에 Swagger.class(yaml) 파일을 생성
Swagger의 기본적의 정보를 정의한 파일입니다.
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 Swagger {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(info);
}
Info info = new Info().title("Swagger Test").version("0.0.1").description(
"<h3>Swagger test</h3>");
}
컨트롤러에서 Swagger 어노테이션을 사용하는 방법입니다.
@Tag
API 엔드포인트를 그룹화하는데 사용합니다.
@Operation
API 메서드에 대한 문서화 정보를 제공합니다.
메서드의 설명, 요청/응답 모델, 파라미터 등을 지정할 수 있습니다.
@ApiResponses
Swagger에서 API 메서드의 응답 정보를 문서화하는 데 사용되는 주석(Annotation)입니다.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Tag(name = "Example Controller", description = "This is an example controller")
public class ExampleController {
@GetMapping("/hello")
@Operation(summary = "accountId 조회", description = "accessKey와 secretKey로 accountId를 조회하는 메서드입니다.",
parameters = {
@Parameter(in = ParameterIn.HEADER, name = "region", description = "test1", required = true, example = "test1"),
@Parameter(in = ParameterIn.HEADER, name = "access-key", description = "test2", required = true, example = "test2"),
@Parameter(in = ParameterIn.HEADER, name = "secret-access-key", description = "test3", required = true, example = "test3")
})
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = BaseResponseStatus.class),
examples = {@ExampleObject(
name = "SuccessRequestExample",
value = "{\"success\": true, \"id\": -\"}"
),
@ExampleObject(
name = "BadRequestExample",
value = "{\n" +
" \"success\":false,\n" +
" \"id\":\"\",\n" +
" \"message\":\"The security token included in the request is invalid. (Service: Sts, Status Code: 403, Request ID: -)\"\n" +
"}"
)
})),
@ApiResponse(responseCode = "400", description = "조회 실패", content = @Content(
examples = @ExampleObject(
name = "ClientBadRequestExample",
value = "{\n" +
" \"timestamp\": \"2024-06-16T06:36:10.860+00:00\",\n" +
" \"status\": 400,\n" +
" \"error\": \"Bad Request\",\n" +
" \"path\": \"test\n" +
"}"
))),
@ApiResponse(responseCode = "500", description = "서버 응답 실패", content = @Content(
examples = @ExampleObject(
name = "ServerBadResponseExample",
value = "{\n" +
" \"timestamp\": \"2024-06-04T06:51:14.175+00:00\",\n" +
" \"status\": 500,\n" +
" \"error\": \"Internal Server Error\",\n" +
" \"path\": \"/test\"\n" +
"}"
))),
})
}
import io.swagger.v3.oas.annotations.media.Schema;
public class UserDto {
@Schema(description = "The unique identifier of the user", example = "1")
private Long id;
@Schema(description = "The name of the user", example = "John Doe")
private String name;
// Getters and Setters
}
위와 같이 설정한다면 애플리케이션을 실행하고 http://localhost:8080/swagger-ui.html로 들어간다면 Swagger UI에 API 메서드의 정의한 내용 및 API 테스트를 할 수 있습니다.
[참고]