[Spring] REST API 명세 문서화(Swagger)

WOOK JONG KIM·2022년 10월 25일
0
post-thumbnail

Swagger

API를 개발하면 명세를 관리해야 함

명세 : 해당 API가 어떠한 로직을 수행하고 있는지 설명하고, 로직을 수행하기 위해 요청값을 통해 요청하며, 응답값으로 무엇을 받을 수 있는지 정리한 자료

명세 문서는 주기적인 업데이트가 필요하고, 번거롭고 시간이 오래 걸림
-> 이를 도와주는 것이 Swagger라는 오픈소스

사용하기 위해 우선 pom.xml 파일에 의존성 추가해야 함

		<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

이후 config 패키지에 SwaggerConfiguration 클래스 작성

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.api"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot Open API Test with Swagger")
                .description("설명 부분")
                .version("1.0.0")
                .build();
    }
}

Swagger에서 스캔할 패키지 범위를 RequestHandlerSelector.basePackage() 메서드로 설정

http://localhost:8080/swagger-ui.html로 접속


세부 내용 추가하기

@ApiOperation : 대상 API의 설명을 작성하기 위한 어노테이션

@ApiParam : 매개변수에 대한 섦여 및 설정을 위한 어노테이션
-> DTO 객체를 매개변수로 사용할 시 DTO 클래스 내의 매개변수에도 정의 가능

@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {

    @ApiOperation(value = "GET 메서드 예제", notes = "@RequestParam을 활용한 Get Method")

    @GetMapping(value = "/request1")
    public String getRequestParam(
            @ApiParam(value = "이름", required = true) @RequestParam String name,
            @ApiParam(value = "이메일", required = true) @RequestParam String email,
            @ApiParam(value = "회사", required = true) @RequestParam String organization
    ){
        return name + " " + email + " " + organization;
    }
}

ApiOperation에 작성된 내용은 그림 상단에 표기

ApiParam에 정의한 내용은 아래 Parameters 영역의 Description 항목에 추가

Swagger에서는 명세 관리 뿐 아니라 통신 시도도 가능

try-out 클릭

execute 버튼을 눌러 자동으로 완성된 요청 URL을 확인할 수 있고, 결괏값 또한 받아볼수 있다

Talend API 대용으로 써보자!

profile
Journey for Backend Developer

0개의 댓글