250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 보안
- JQuery
- 그리드
- 엑셀 업로드
- 스트림
- poi
- 대용량 업로드
- Javascript
- DevOps
- 제이쿼리그리드
- mom
- sqlserver
- jqGrid
- rabbitmq
- 자바8
- 자동배포
- stream api
- mssql
- java
- ci/cd
- Stream
- MessageQueue
- ORM
- apache.poi
- spring
- docker
- Jenkins
- 자동빌드
- JPA
- QueryDSL
Archives
- Today
- Total
개발 메모장
[Spring] Swagger(스웨거) 사용방법 본문
728x90
#. Swagger란 무엇인가?
- RESTful 웹 서비스를 생성, 삭제, 설명 및 시각화하기 위한 프레임워크입니다.
- 사람이 읽을 수 있는 형식으로 API를 설계해 주는 역할을 합니다.
- 대화형 API문서, 클라이언트 SDK, 서버 스텁을 자동으로 생성하는 도구를 제공합니다.
- 즉, API문서 생성을 자동화하고 테스트 및 탐색을 위한 UI를 제공하는 것을 의미합니다.
#. 스웨거 사용방법
- 스웨거 사용을 위한 라이브러리를 추가합니다.
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
- 스웨거를 처리할 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 {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Test API")
.description("테스트를 위한 Swagger 문서 작성")
.version("1.0")
.build();
}
}
- DocumentationType 은 사용할 swagger의 버전을 지정합니다. 작성된 내용은 swagger 2를 사용합니다.
- apis(RequestHandlerSelectors.any()) 는 접근할 패키지의 컨트롤러의 문서화를 위해 지정할 수 있습니다.
지정을 하기 위해선 .any() 대신 .basePackage("com.swagger_Test.controller")를 입력해 처리가 가능합니다. - paths(PathSelectors.any()) 는 문서화를 위한 경로를 모두 선택하기 위해 사용합니다.
- apiInfo()는 API정보 설정을 하는 메서드입니다. 타이틀, 부가설명, 버전 등 api에 대한 메타데이터를 설정합니다.
#. Controller 설정하기
- 스웨거 화면에서 보여주기 위해 처리해야 할 내용입니다.
- @Api 어노테이션을 사용해 화면에 보일 이름을 입력합니다.
import io.swagger.annotations.Api;
@RestController
@RequestMapping("/api-direct")
@Api(value = "api-direct Test", tags = "api-direct")
public class SwaggerTestController {
@GetMapping("/game")
public String direct(String gubun) {
String game = "";
if("1".equals(gubun)) {
game = "overWatch";
} else if("2".equals(gubun)) {
game = "fc온라인";
}
return game;
}
}
- 위와 같이 입력하고 url을 이용해 접근해 봅니다.
- url의 경우 2 버전대는 swagger-ui.html로 접근 가능하며, 3 버전대는 swagger-ui/ 로 접근 가능합니다.
- 접근하려 하니 아래와 같이 id 및 pw를 입력하라는 alert이 발생했습니다.
- 스프링 시큐리티를 사용하기에 접근을 위해서 인증하라는 것입니다.
- security config를 통해 처리하도록 하겠습니다.
#. SecurityConfig
- 직접 id와 pw를 지정해 클라이언트가 인증하는 방법이 있으며, 아래와 같이 특정 url을 접근허용 하는 방식이 있습니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("1234")
.password("1234")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/v2/api-docs/**", "/swagger-ui**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
#. UI 확인하기
- 위와 같이 설정하여 url에 접근하면 아래와 같은 화면이 보입니다.
- 데이터를 입력하고 excute 하면 아래와 같이 응답값을 확인할 수 있습니다.
#. API를 테스트하는 툴인 postman, insomnia 등을 사용해도 되지만 API문서화라는 장점과 하나하나 설정하기 귀찮을 때 쉽게 처리가 가능하기에 이용하면 좋을 것 같습니다.
===========================================================
틀린 내용이 있거나 이견 있으시면 언제든 가감 없이 말씀 부탁드립니다!
===========================================================
728x90
'Spring' 카테고리의 다른 글
[Spring] Swagger 3.0 - API 문서화 (0) | 2024.07.04 |
---|---|
[Spring] 스프링 시큐리티(Spring Security) (0) | 2024.02.07 |