Swagger
- Open Api Specification(OAS)를 위한 프레임워크이다.
- API들이 가지고 있는 스펙(spec)을 명세, 관리할 수 있는 프로젝트/문서
- API 사용 방법을 사용자에게 알려주는 문서
- Springboot에서 Swagger를 사용하면, 컨트롤러에 명시된 어노테이션을 해석하여 API문서를 자동으로 만들어준다.
- 참고로 Swagger는 Java에 종속된 라이브러리가 아니다.
- URL에
/swagger-ui.heml
으로 접근하면 swagger가 만들어주는 페이지에 접근할 수 있다. - 공식 사이트
Swagger의 기능
- API Design (API 설계)
- Swagger-editor를 통해 api를 문서화하고 빠르게 명세 가능
- API Development
- Swagger-codepen을 통해 작성된 문서를 통해 SDK를 생성하여 빌드 프로세스를 간소화할 수 있도록 도와준다.
- API Documentation
- Swagger-UI를 통해 작성된 API를 시각화시켜준다.
- API Testing
- Swagger-Inspector를 통해 API를 시각화하고 빠른 테스팅을 진행할 수 있다.
- Standardize
- Swagger-hub를 통해 개인, 팀원들이 API 정보를 공유하는 Hub
Swagger 설정
- swagger 설정을 위해
SwaggerConfig
클래스를 생성한다. - 클래스 명은 마음대로 작성 가능
-
예)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; @Configuration @EnableSwagger2 public class SwaggerConfig { private String version; private String title; @Bean public Docket apiV1() { version = "V1"; title = "victolee API " + version; return new Docket(DocumentationType.SWAGGER_2) .useDefaultResponseMessages(false) .groupName(version) .select() .apis(RequestHandlerSelectors.basePackage("com.victolee.swaggerexam.api.v1")) .paths(PathSelectors.ant("/v1/api/**")) .build() .apiInfo(apiInfo(title, version)); } @Bean public Docket apiV2() { version = "V2"; title = "victolee API " + version; return new Docket(DocumentationType.SWAGGER_2) .useDefaultResponseMessages(false) .groupName(version) .select() .apis(RequestHandlerSelectors.basePackage("com.victolee.swaggerexam.api.v2")) .paths(PathSelectors.ant("/v2/api/**")) .build() .apiInfo(apiInfo(title, version)); } private ApiInfo apiInfo(String title, String version) { return new ApiInfo( title, "Swagger로 생성한 API Docs", version, "www.example.com", new Contact("Contact Me", "www.example.com", "foo@example.com"), "Licenses", "www.example.com", new ArrayList<>()); } }
@EnableSwagger2
- Swagger2 버전을 활성화 하겠다는 어노테이션
Docket
- Swager 설정의 핵심이되는 Bean
- API 자체에 대한 스펙은 컨트롤러에서 작성한다.
- 자세히
- 설정 정보
useDefaultResponseMessages()
false
로 설정하면 swagger에서 제공해주는 응답코드(200, 401, 405, 404) 에 대한 기본 메시지르 제거한다.- 불필요한 응답코드와 메시지를 제거하기 위함이며, 컨트롤러에서 명시해줄 것이다.
groupName()
- Docket Bean이 한 개일 경우
- 기본 값은
default
이므로 생략 가능
- 기본 값은
- 여러 Docket Bean을 생성했을 경우
- groupName이 충돌하지 않아야하므로, 여기서는 각 Docket Bean 버전을 사용해줌
- Docket Bean이 한 개일 경우
select()
ApiSelectorBuilder
를 생성한다.
apis()
-api 스펙이 작성되어 있는 패키지를 지정한다.- 컨트롤러가 존재하는 패키지를
basepackage
로 지정하여, RequestMapping(GetMapping, PostMapping…)이 선언된 API를 문서화 한다.
- 컨트롤러가 존재하는 패키지를
paths()
apis()
로 선택되어진 API 증 특정 path 조건에 맞는 APi들을 다시 필터링하여 문서화한다.
apiInfo()
- 제목, 설명 등 문서에 대한 정보들을 보여주기 위해 호출한다.
-
파라미터 정보
1
public ApiInfo( title, description, version, termsOfServiceUrl,contact, license, licenseUrl, vendorExtensions )
컨트롤러
@Api
- 해당클래스가 Swagger 리소스라는 것을 명시한다
value
- 태그를 작성한다.
tags
- 사용하여 여러 개의 태그를 정의할 수도 있다.
@ApiOperation
- 한 개의 operation(즉 API URL과 Method)을 선언한다
value
- API에 대한 간략한 설명(제목같은 느낌으로)을 작성한다
notes
- 더 자세한 설명을 작성해준다.
@ApiParam
- operation의 가능한 reponse를 명시한다.
code
- 응답모드를 작성한다.
message
-응답에 대한 설명을 작성한다.responseHeaders
- 헤더를 추가할 수 있다.
@ApiParam
- 파라미터에 대한 정보를 명시한다.
value
- 파라미터 정보를 작성한다.
required
- 필수 파라미터이면
true
, 아니면false
를 작성한다.
- 필수 파라미터이면
example
- 테스트를 할 때 보여줄 예시를 작성한다.
- 자세히
[참고]
https://swagger.io/
https://real-dongsoo7.tistory.com/58
https://victorydntmd.tistory.com/341#recentComments