일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 테스트 코드
- Array
- Repository 테스트
- jvm
- 디자인 패턴
- OOP
- 스터디
- 마이크로서비스 아키텍처
- do...while
- 트랜잭션 락
- 파스칼 케이스
- 배열
- 비링크
- Service 테스트
- 스네이크 케이스
- DTO
- Java
- 원시 자료형
- Entity
- 공유락
- 낙관락
- @Version
- springDataJpa
- 스프링 부트
- Controller 테스트
- 자료구조
- 비즈니스 로직
- 자바
- @Query
- 배타락
- Today
- Total
menuhwang
[Spring Boot] Swagger : API 명세 본문
Swagger
API 제작 후 사용방법을 모르면 올바른 접근, 사용이 불가능하다.
그래서 API 사용방법 즉, API 명세서를 작성해주어야 한다.
아래는 배틀그라운드의 API Document이다.
Swagger는 이런 명세서를 간단하게 작성해준다.
적용
Dependency 추가
먼저 Swagger를 사용하기 위해 Dependency를 추가해준다.
이 글에서는 Swagger2 3.0.0 버전과 Swagger-ui 3.0.0 버전을 사용한다.
* 많이 사용되는 2.9.2 버전과는 설정에 있어서 조금 차이가 있다.
Gradle
implementation 'io.springfox:springfox-boot-starter:3.0.0'
Maven
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter/3.0.0
springfox-boot-starter 안에 Swagger2와 Swagger-ui를 포함한 필요한 라이브러리들이 존재한다.
Configuration 생성
다음으로 Configuration를 작성한다.
configuration 파일은 따로 config라는 패키지를 생성해서 작성해주었다.
SwaggerConfig.java
@Configuration
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.select()
.apis(RequestHandlerSelectors.basePackage("com.menuhwang.My"))
.paths(PathSelectors.any())
.build();
}
}
접속
configuration 파일까지 작성한 후 application을 실행하고, http://localhost:8080/swagger-ui/index.html 로 접속하면 깔끔한 API 명세 페이지를 만날 수 있다.
* 2.9.2 버전의 경우 http://localhost:8080/swagger-ui.html 로 접속 가능하다.
작성한 API 도 테스트해 볼 수 있으며, curl 스크립트도 알아서 작성해준다.
설정
페이지 기본 정보 설정
먼저, UI의 제목과 설명, 버전들을 설정해보자.
SwaggerConfig.java
@Configuration
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.menuhwang.My"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My Application API Document")
.description("My Application API 명세서입니다.")
.version("alpha 1.0.0")
.build();
}
}
Docket에. apiInfo()를 추가해주고 인자로 ApiInfo를 넣어준다.
ApiInfo는 ApiInfoBuilder로 생성해준다.
Docket.apis(RequestHandlerSelectors.basePackage()) 는 스캔할 패키지 범위를 설정한다.
그 외 ApiInfo 설정
- contact() : 연락처 설정
SwaggerConfig.java
// ...
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My Application API Document")
.description("My Application API 명세서입니다.")
.version("alpha 1.0.0")
.contact(new Contact("menu-Hwang", "https://test.com", "menu@test.com"))
.build();
}
// ...
- license()
- termsOfServiceUrl()
등 추가적으로 설정해줄 수 있다.
세부 설명
이번에는 컨트롤러 메서드에 세부 설명을 설정해보자.
MyController.java
@RestController
@RequestMapping("/api")
public class MyController {
// ...
@ApiOperation(value = "PathVariable 예제", notes = "@PathVariable을 사용한 예제")
@GetMapping(value = "/hello1/{name}")
public String hello1(@ApiParam(value = "이름", required = true) @PathVariable("name") String userName) {
return "Hello-1, " + userName;
}
// ...
}
@ApiOperation 어노테이션은 메서드 이름과 설명을 설정해줄 수 있다.
@ApiParam 어노테이션으로 파라미터의 설명과 필요 여부를 설정할 수 있다.
DTO 설정
DTO 필드에도 설정을 해줄 수 있다.
@ApiModel(value = "회원정보")
public class MyDTO {
@ApiModelProperty(value = "이름")
@ApiParam(value = "이름", required = true)
private String name;
@ApiModelProperty(value = "나이")
@ApiParam(value = "나이", required = true)
private Integer age;
// ...
}
'스터디 > Spring' 카테고리의 다른 글
[Spring Boot] Spring Data JPA (0) | 2022.08.26 |
---|---|
[Spring Boot] 로그 남기기 : Logback (1) | 2022.08.24 |
[Spring Boot] Controller 설계 (0) | 2022.08.22 |
[Spring Boot] 스프링 MVC 모델 레이어드 아키텍처 (0) | 2022.08.19 |
[Spring Boot] 스프링 부트 동작 방식 (0) | 2022.08.19 |