<목차>
1. API 명세
2. Schemas 명세
Springdoc OpenAPI 는 다양한 어노테이션을 활용해 API 문서를 쉽게 생성하고 관리할 수 있도록 해준다.
다음과 같은 Get API 기준으로 각종 어노테이션을 적용해보자.
@GetMapping
public ResponseEntity<ProductResponseDto> getProduct(Long number) {
ProductResponseDto productResponseDto = productService.getProduct(number);
return ResponseEntity.status(HttpStatus.OK).body(productResponseDto);
}
[API 명세]
컨트롤러에 적용하는 어노테이션에 대해 알아보자.
- @Operation
- 특정 End-point의 메타데이터를 정의하는데 사용된다.
- 설명, 응답, 태그 등의 정보를 설정할 수 있다.
- summary : API 상세를 보기 전, 간단한 요약
- description : API 설명
- tags : API 그룹화
- responses : 응답에 대한 처리
@Operation(
summary = "Get a Product by product number",
description = "Returns a single product based on the provided number",
tags = {"Products"},
responses = {
@ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = ProductResponseDto.class))),
@ApiResponse(responseCode = "404", description = "Product not found")
}
)
@GetMapping
public ResponseEntity<ProductResponseDto> getProduct(Long number) {
ProductResponseDto productResponseDto = productService.getProduct(number);
return ResponseEntity.status(HttpStatus.OK).body(productResponseDto);
}
- @Parameters
- 메소드 파라미터에 대한 설명을 추가하는데 사용
- description : 파라미터에 대한 설명
- required : 필수 값 여부 true / false
- example : 예시
@Operation(
summary = "Get a Product by product number",
description = "Returns a single product based on the provided number",
tags = {"Products"},
responses = {
@ApiResponse(responseCode = "200", description = "Successful operation", content = @Content(schema = @Schema(implementation = ProductResponseDto.class))),
@ApiResponse(responseCode = "404", description = "Product not found")
}
)
@GetMapping
public ResponseEntity<ProductResponseDto> getProduct(@Parameter(description = "제품 번호", required = true, example = "1") Long number) {
ProductResponseDto productResponseDto = productService.getProduct(number);
return ResponseEntity.status(HttpStatus.OK).body(productResponseDto);
}
[Schemas 명세]
- @Schema 어노테이션은 모델 속성에 대한 자세한 설명을 제공하는데 사용된다.
- 아래 예시를 보면, DTO와 같은 모델 클래스에 별도의 설명을 기재하지 않는다면, ChageProductNameDto 와 같이 선언된 타입만 보여지게 된다.
- 하지만, @Shchema 어노테이션을 활용하면 필드명, 예시, 설명 등을 추가하여 ProductResponseDto 와 같이 보여줄 수 있다.
public class ProductResponseDto {
@Schema(name = "number", description = "제품을 식별하는 Key 값", example = "123")
private Long number;
@Schema(name = "name", description = "제품의 이름", example = "연필")
private String name;
@Schema(name = "price", description = "제품의 가격", example = "3000")
private int price;
@Schema(name = "stock", description = "제품의 재고 수량", example = "200")
private int stock;
}
'Spring & Spring boot' 카테고리의 다른 글
[Springboot] 테스트 코드 - 2 - TDD 테스트 주도 개발이란? (0) | 2024.08.05 |
---|---|
[Springboot] 테스트 코드 - 1 - 테스트 개요 (0) | 2024.08.04 |
[Springboot] springdoc 을 사용하여 Swagger 설정하기 - 1 (0) | 2024.08.04 |
[Spring Boot] JPA - 4. CRUD Example (0) | 2024.08.04 |
[Spring Boot] JPA - 3. Entity & Repository (0) | 2024.07.26 |