Programing/Springboot

[API documentation 자동화] spring boot swagger UI 적용 방법

리커니 2023. 1. 26.
반응형

API의 Document를 자동으로 제공해주는 swagger UI 설정방법을 알아보겠습니다.

 

springboot 2.7.7

springsecurity

gradle

 

 

1. dependencies 를 추가

/*swagger*/
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
/*security*/
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.7.5'

 

2.WebMvcConfig.java 생성

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/swagger-ui/")
                .setViewName("forward:/swagger-ui/index.html");
    }
    
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .consumes(getConsumeContentTypes())
                .produces(getProduceContentTypes())
                .select()
                .apis(RequestHandlerSelectors.basePackage("API 패키지명"))
                .paths(PathSelectors.any())
                .build();
    }


    private Set<String> getConsumeContentTypes() {
        Set<String> consumes = new HashSet<>();
        consumes.add(MediaType.APPLICATION_JSON_VALUE);
        consumes.add("application/x-www-form-urlencoded");
        return consumes;
    }

    private Set<String> getProduceContentTypes() {
        Set<String> produces = new HashSet<>();
        produces.add(MediaType.APPLICATION_JSON_VALUE);
        return produces;
    }
    /**기타 설정*/
}

 

swagger 페이지 연결에 필요한 설정을 해줍니다.

 

 

3.security 에 swagger 연결 경로 허용 추가

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                    .csrf().disable() 
					/*...*/
                    /*swagger 관련 허용*/
                    .antMatchers("/v2/api-docs",  "/configuration/ui",
                        "/swagger-resources/**", "/configuration/security",
                        "/swagger-ui/**", "/webjars/**","/swagger/**").permitAll()
                    .anyRequest().authenticated()
					/*...*/
                    .and().build();
    }
}

 

4. swagger 접속확인

 

http://localhost:{설정 port}/{설정 context}/swagger-ui/index.html 로 접속을 확인합니다.

 

 

이렇게 설정만 하게 되면 API document를 따로 생성할 필요 없이 자동으로 생성되게 됩니다.

제공되는 API 부터 각 API의 Method, 파라메터, 예상결과, Model, 테스트 까지 깔끔한 UI로 제공되게 됩니다.

반응형

댓글

💲 추천 글