Springboot 3에서 Swagger 생성법

Jin·2024년 3월 28일
1
post-thumbnail

환경
자바 17
스프링부트 3.2.3

예전에는 spring fox를 사용했던 거 같은데 3버전으로 되면서 spring doc을 쓰는게 맞다고 한다.

build.gradle

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

application.properties

springdoc.packages-to-scan= com.demo.project (패키지명)
springdoc.default-consumes-media-type= application/json;charset=UTF-8
springdoc.default-produces-media-type= application/json;charset=UTF-8
springdoc.swagger-ui.path= /swagger-ui.html
springdoc.swagger-ui.disable-swagger-default-url= true
springdoc.swagger-ui.display-request-duration= true
springdoc.swagger-ui.operations-sorter=alpha

SwaggerConfig.java

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {


    @Bean
    public OpenAPI openAPI() {
        Info info = new Info()
                .version("v1.0.1")
                .title("Hello")
                .description("안녕하세요?");

        String jwt = "JWT";
        SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwt);
        Components components = new Components().addSecuritySchemes(jwt, new SecurityScheme()
                .name(jwt)
                .type(SecurityScheme.Type.HTTP)
                .scheme("bearer")
                .bearerFormat("JWT")
        );

        return new OpenAPI()
                .info(info)
                .addSecurityItem(securityRequirement)
                .components(components);
    }
}

로그인을 넣어서 accessToken을 넣어서 해야하니까 security 부분도 넣게 되었다.

설명 작성하기

@Tag(name ="Itemlist API", description = "아이템 리스트에 대한 API")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/journeys/{journey_id}/itemlist")
public class ItemlistController {
    private final ItemService itemService;
    @Operation(summary = "한 여정에 대한 아이템 리스트 다 불러오기", description = "특정 여정에 대한 모든 아이템을 가져오는 API입니다.")
    @Parameter(name = "journey_id", description = "조회할 여정의 ID")
    @GetMapping
    public ResponseEntity<Object> readItemlist(@PathVariable("journey_id") int journeyId) {
        try {
            List<Item> itemList = itemService.readItemlist(journeyId);
            if (itemList.isEmpty()) {
                Message message = new Message("404", "아이템 목록이 비어 있습니다.");
                return new ResponseEntity<>(message, HttpStatus.NOT_FOUND);
            } else {
                Message message = new Message("200", "아이템 목록을 가져오기 성공", itemList);
                return new ResponseEntity<>(message, HttpStatus.OK);
            }
        } catch (Exception e) {
            Message message = new Message("500", "아이템 목록 읽기 서버 오류로 인해 아이템 목록을 가져올 수 없습니다.");
            return new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

@ Tag, @Operation과 @Parameter

http://localhost:8080/swagger-ui/index.html
server.servlet.context-path에 경로 넣었으면 (예: /api)
http://localhost:8080/api/swagger-ui/index.html
이런식으로 하면 됨!

profile
go-getter

2개의 댓글

comment-user-thumbnail
2024년 4월 4일

와 몰랏던 사실

1개의 답글