Swagger로 API 문서 자동화

최승원·2020년 4월 19일
1

Spring Boot

목록 보기
1/1
post-thumbnail

개요

REST API를 만들 때 문서화를 잘하는 것은 중요하다.

더우기 API를 변경할 때마다 레퍼런스 문서에 똑같이 명시해주어야한다. 이것을 수작업으로 반영하는 것은 매우 지루한 일이므로, 이것을 자동화하는 것은 필수다.

Swagger를 통해 spirng api 문서 자동화를 할 수 있다.

Swagger 설정

의존성 추가

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'

자바 설정

package com.ioil.comethru.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    private String version;
    private String title;

    @Bean
    public Docket api() {
        version = "V1";
        title = "API " + version;

        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .groupName(version)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/v1/api/**"))
                .build();
    }

}

HelloController 생성

package com.ioil.comethru.web;

import com.ioil.comethru.web.dto.HelloResponseDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("/hello/dto")
    public HelloResponseDto helloDto(@RequestParam("name") String name,
                                     @RequestParam("amount") int amount) {
        return new HelloResponseDto(name, amount);
    }

}

결과 확인

실행하여 제대로 API 문서가 생성되었는지 확인한다.

profile
Java & Backend Developer

0개의 댓글