티스토리 뷰

SPRING 🍃

Spring Swagger

절취선 2022. 3. 13. 17:53
반응형

🚀 What is Swagger?

Swagger를 사용하면 기계가 읽을 수 있도록 API의 구조를 설명할 수 있다.
정리하자면 우리가 별도로 UI를 HTML 파일로 제작하지 않아도 Swegger 에서 필요한 문서 형태를 모두 제공하고 결과값 또한 보여주는 툴이다.

Swgger 공식 홈페이지

프로젝트 예시

Spring Cloud 프로젝트에 들어가기전에 API문서를 별도로 만들 필요없이 빠른 개발 할 수 있도록 도와주는 툴을 설정한다.

Controller 구현

@Api
@RestController
public class FileUploadController {

    @Autowired
    FileUploadService fileUploadService;

    @ApiOperation("이미지 파일 업로드")
    @PostMapping("/v1.0/upload/image")
    public ImageFileUploadResult transfer(
            @RequestParam("userKey") String userKey,
            @RequestPart("imageFile") MultipartFile multipartFile) {
        ImageFile imageFile = fileUploadService.upload(multipartFile);
        return ImageFileUploadResult.builder()
                .fileName(imageFile.getFileName())
                .fileId(imageFile.getFileId())
                .fileSize(imageFile.getFileSize())
                .build();
    }
}
어노테이션 설명
@Api 클래스를 Swagger 리소스 대상으로 표시
@ApiOperation 요청 URL 에 매핑된 API 에 대한 설명
@ApiParam 요청 Parameter에 대한 설명 및 필수여부, 예제값 설정
@ApiResponse 응답에 대한 설명

Swagger Config

Swagger을 사용하기 위해서는 기본 설정을 필요로한다.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelExpandDepth(3)
                .defaultModelExpandDepth(3)
                .docExpansion(DocExpansion.LIST)
                .displayRequestDuration(false)
                .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null)
                .build();
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("photo api")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("photo upload api")
                .description("사진 업로드 api")
                .version("1.0.0")
                .build();
    }
}

아래 페이지에서 사용자가 필요로 하는 설정을 구성 후 사용할 수 있다.

정리

Swagger는 API를 구현을 도와주는 Tool일 뿐이며 필요할때 문서를 찾아서 구현하면 되겠다.

시간내서 공부할 필요성은 없다는 것이다.

🧾Reference

Spring Cloud

Swegger 기본 사용법

Swagger Editor

반응형

'SPRING 🍃' 카테고리의 다른 글

Servlet 과 JSP 차이  (0) 2022.03.16
드디어 도착했다! Spring Cloud  (0) 2022.03.11
유튜브API로 채널 정보 가져오기  (0) 2022.03.05
댓글 기능 추가  (0) 2022.03.04
엔티티 매핑 최적화  (0) 2022.03.03
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함