Swagger 공식 홈페이지에 가봤는데 swagger가 하나만 있는줄 알았는데 여러 툴이 있었다.
아무 것도 모르는데 여기서 어떻게 찾아야 할지 막막했다.
뭔가 Swagger UI인 것 같은데 또 quick start같은 것을 보면 또 아닌 것 같았다.
yaml로 작성한 적이 없는데 yaml로 직접 작성해야 하는게 너무 당황스러웠다.
어떻게 찾아야할지 고민하다가 일단 index화면에서 살펴보니 swagger가 spring에서만 사용하는 것이 아니었다.
그래서 spring에서 사용하던 어노테이션 방식을 알아야 해서
gpt에게 물어보았다. spring에서 swagger를 어떻게 사용하고 공식문서는 어디있는지 알려달라고 물었다.
springdoc-openapi를 알려주었다.
https://springdoc.org/#getting-started
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
들어가서 문서를 살펴보니 찾고 싶었던 것 같은데 예시코드가 한눈에 안 들어왔다.
그래서 처음부터 읽어가기로 했다.
Springdoc-openapi
- Springdoc-openapi는 java 라이브러리이고 Spring Boot 프로젝트를 사용하여 API 문서 생성을 자동화해준다.
- Spring Boot2 이하는 Springdoc-openapi v1.8.0까지만 지원된다.
- Springdoc-openapi는 런타임에 애플리케이션을 검사할 때 작동한다.
- 자동으로 JSON / YAML 그리고 HTML 포맷으로 API들을 문서로 생성한다. (-> Swagger가 공홈에서 왜 yaml파일로 작성되어있는지 알게 되었다.)
- 이 라이브러리는
- openAPI 3
- Spring Boot 3
- JSR-303 (특히, @NotNull, @Min, @Max, @Size)
- Swagger-UI
- OAuth2
- GraalVM native images
를 지원한다. - Swagger 제품 중 Swagger UI를 사용 ( -> 기본 포맷을 작성하지 않는 것으로 보아 UI툴을 사용한다는 예상이 맞았던 것 같다.)
Springdoc-openapi 적용하기
- build.gradle에
implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.7.0'
# 혹은
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.7.0")
# 을 추가한다. ( 작성 당시 최신 안정화 파일이 2.7.0 버전이다. )
Swgagger UI 페이지는 'http://server:port/context-path/swagger-ui.html'에서 이용 가능
'http://server:port/context-path/v3/api-docs'에서 json 파일을 생성 가능
'http://server:port/context-path/v3/api-docs.yaml'에서 yaml파일을 생성 가능
- 코드에 추가하기
@Tag(name = "User", description = "User API") // Controller 단위로 관리
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
// @Operation를 이용해 해당 API가 어떤 리소스를 나타내는지 간략한 설명을 추가할 수 있다.
@Operation(summary = "Get user", description = "특정 유저의 상세 정보를 조회한다.")
// @ApiResponses를 이용해 해당 API의 Response 정보들을 나타낼 수 있다.
@ApiResponses(value = {
// @ApiResponse는 단일 Response에 대한 정보를 나타낸다.
@ApiResponse(responseCode = "200", description = "성공",
// content는 response의 데이터 포맷을 알려준다
content = {@Content(schema = @Schema(implementation = UserRes.class))}),
// 만약 데이터 타입이 List인 경우
// {@Content(mediaType = "application/json",
// array = @ArraySchema(schema = @Schema(implementation = UserRes.class)))}
@ApiResponse(responseCode = "404", description = "해당 ID의 유저가 존재하지 않습니다."),
})
@GetMapping("/{userId}")
public UserRes getUser(
// @Schema와 @Parameter로 설명 가능하다.
@Positive(message = "유저 ID는 양수입니다.")
@Schema(description = "User ID", example = "1")
@PathVariable Long userId,
@Positive(message = "유저 ID는 양수입니다.")
@Parameter(name = "loginId", description = "로그인 유저 ID 값",
example = "3", required = true)
@RequestParam final Long loginId
//, @RequestBody @Valid UserUpdateReq request
) {
return userService.getUser(userId, loginId);
}
}
RequestDTO와 responseDTO에 대한 명세
// @Schema로 클래스와 필드를 설명할 수 있다.
@Schema(description = "User response")
@Getter
@AllArgsConstructor
public class UserRes {
@NotBlank(message = "사용자 이름을 입력해주세요.")
@Length(max = 20, message = "사용자 이름은 20글자 이하로 입력해야 합니다.")
@Schema(description = "user name", example = "Kim")
private String name;
@NotBlank(message = "사용자 닉네임을 입력해주세요.")
@Length(max = 20, message = "사용자 닉네임은 20글자 이하로 입력해야 합니다.")
@Schema(description = "user nickname", example = "kim")
private String nickname;
}
- 액추에이터 지원(Spring-boot-actuator)
Spring-boot-actuator 엔드포인트도 추가하려면
springdoc.show-actuator=true
을 추가하면 Swagger-UI와 Openapi 엔드포인트를
어플리케이션 포트를 통해서 확인가능 'http://server:port/actuator/swagger-ui'
액추에이터 관리 포트를 분리하는 것을 권장(CORS 허용 확인)
액추에이터 관리 포트에서 Swagger-UI를 보이려면
springdoc.use-management-port=true
를 추가해주어야 한다.
그러면
'http://server:management-port/actuator/swagger-ui'
에서 이용 가능하다.
예를 들어, management-port=9090으로 되어 있으면
'http://localhost:9090/actuator/swagger-ui'
에서 swagger ui를 볼 수 있다.
- 공식문서 예제코드
https://github.com/springdoc/springdoc-openapi
GitHub - springdoc/springdoc-openapi: Library for OpenAPI 3 with spring-boot
Library for OpenAPI 3 with spring-boot. Contribute to springdoc/springdoc-openapi development by creating an account on GitHub.
github.com
https://github.com/springdoc/springdoc-openapi-demos
GitHub - springdoc/springdoc-openapi-demos: Demo for OpenAPI 3 with spring-boot
Demo for OpenAPI 3 with spring-boot. Contribute to springdoc/springdoc-openapi-demos development by creating an account on GitHub.
github.com
javascript용 : https://github.com/swagger-api/swagger-ui
GitHub - swagger-api/swagger-ui: Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beauti
Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API. - swagger-api/swagger-ui
github.com