
스웨거는 RestAPI를 위한 OpenAPI스펙에 맞춘 문서화를 도와주는 툴이다.

build.gradle에 추가하면 즉시
http://localhost:8080/swagger-ui/index.html#/
에 접속하여 생성된 API문서를 확인할 수 있다.
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.components(new Components())
.info(apiInfo());
}
private Info apiInfo() {
return new Info()
.title("MBTIgram Springdoc")
.description("Springdoc을 사용한 MBTIgram Swagger UI")
.version("1.0.0");
}
}
springdoc:
packages-to-scan: 스캔할 패키지 명
default-consumes-media-type: application/json;charset=UTF-8
default-produces-media-type: application/json;charset=UTF-8
swagger-ui:
path: /
disable-swagger-default-url: true
display-request-duration: true
operations-sorter: alpha
같은 name끼리 같은 API그룹으로 묶을 수 있다.
@Tag(name = "MBTIgram API", description = "MBTIgram API")
@RestController
public class TestController {
...
}

API에서 반환될 Schema에 대한 정보를 작성할 수 있다.(DTO에 대한 설명 등)
@Schema(description = "MBTI분석 결과 DTO")
@Getter
public class MbtiPredictedDto {
@Schema(description = "MBTI 예측 결과")
private String mbti;
}
API 동작에 대한 설명을 적을 수 있다.

API 응답에 대해 적을 수 있다.
@Operation(summary = "인스타그램 MBTI예측", description = "인스타그램 계정의 게시글 텍스트를 추출하여 MBTI를 예측합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "MBTI 조회 성공", content = @Content(schema = @Schema(implementation = MbtiPredictedDto.class))),
@ApiResponse(responseCode = "400", description = "게시글이 없는 계정 조회", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
@ApiResponse(responseCode = "401", description = "비공개 계정 조회", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))),
@ApiResponse(responseCode = "404", description = "존재하지 않는 계정 조회", content = @Content(schema = @Schema(implementation = ApiResponseDto.class)))})
@Transactional
public ResponseEntity<ApiResponseDto> instagramPredict(@Parameter(name = "snsUrl", description = "인스타그램 id")
@Valid @RequestParam String snsUrl){
...
}
}

파라미터에 대한 설명을 적을 수 있다.
이를 적지 않으면 기본 arg0, arg1등으로 설정되므로 꼭 설정하자.

이를 공유하기 위해 배포를 진행하게 되면 CORS문제로 인해 사용할 수 없게 된다.
스프링 어플리케이션에 @OpenApiDefinitino()을 추가하면 해결할 수 있다.
@OpenAPIDefinition(servers = {@Server(url = "/", description = "Default Server URL")})
@SpringBootApplication
public class TestApplication {
...
}
https://jeonyoungho.github.io/posts/Open-API-3.0-Swagger-v3-%EC%83%81%EC%84%B8%EC%84%A4%EC%A0%95/