Swagger
- 간단한 설정으로 프로젝트의 API 목록을 웹에서 확인 및 테스트 할 수 있게 해주는 Library
- Swagger를 사용하면 Controller에 정의되어 있는 모든 URL을 바로 확인할 수 있음
- API 추가 또는 변경 시 문서에 적용해야하는 불편함 해결
💡 FrontEnd 개발자는 화면과 로직에 집중하고,
BackEnd 개발자가 만든 문서 API를 보며 데이터 처리!
Swagger 적용
1. dependency 추가, 설정
pom.xml
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
root-context.xml
<resources mapping="/swagger-ui/**" location="classpath:/META-INF/resources/webjars/springfox-swagger-ui/" />
<context:component-scan base-package="com.danbi.mvc.config" />
2. SwaggerConfig.java
package com.danbi.mvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api(){
final ApiInfo apiInfo = new ApiInfoBuilder()
.title("직원 관리 API")
.description("<h3>직원관리시 사용하는 RestApi에 대한 문서를 제공합니다.</h3>")
.contact(new Contact("EMPLOYEE", "http://emp.com", "emp@email.com"))
.license("MIT License")
.version("9.0")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
.apis(RequestHandlerSelectors.basePackage("com.danbi.mvc.controller"))
.paths(PathSelectors.ant("/*/empapi/**"))
.build();
}
}
@EnableSwagger2 : Swagger2 사용
3. Swagger가 적용될 Model (DTO)
package com.danbi.mvc.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(value="직원 정보", description = "직원 정보를 보여줍니다.")
public class Emp {
@ApiModelProperty("직원 번호")
private int num;
@ApiModelProperty("직원 이름")
private String name;
@ApiModelProperty("직원 급여")
private int salary;
}
@ApiModel : 모델에 설명 추가
@ApiModelProperty : 모델의 요소에 설명 추가
4. Swagger가 적용될 Controller
package com.danbi.mvc.controller;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.danbi.mvc.dto.Emp;
import com.danbi.mvc.model.service.EmpService;
import io.swagger.annotations.ApiOperation;
@RestController
@CrossOrigin("*")
@RequestMapping("/empapi")
public class EmpRestController {
@Autowired
private EmpService svc;
@PostMapping("/emp")
@ApiOperation(value="Emp 객체 목록을 등록한다.",response=Emp.class)
public ResponseEntity<?> insert(@RequestBody Emp emp) throws SQLException {
int r = svc.insert(emp);
if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.CREATED); //201
return new ResponseEntity<Void> (HttpStatus.NO_CONTENT); // 204
}
@DeleteMapping("/emp/{num}")
@ApiOperation(value="{num}에 해당하는 Emp 객체를 삭제한다.",response=Emp.class)
public ResponseEntity<?> delete(@PathVariable int num) throws SQLException {
int r = svc.delete(num);
if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.OK); //200
return new ResponseEntity<Void> (HttpStatus.NO_CONTENT); // 204
}
@PutMapping("/emp")
@ApiOperation(value="Emp 객체를 변경한다.",response=Emp.class)
public ResponseEntity<?> update(@RequestBody Map<String, Integer> map) throws SQLException {
int r = svc.update(map);
if (r == 1) return new ResponseEntity<Integer>(r, HttpStatus.CREATED); //201
return new ResponseEntity<Void> (HttpStatus.NO_CONTENT); // 204
}
@GetMapping("/emp")
@ApiOperation(value="Emp 객체 목록을 반환한다.",response=Emp.class)
public ResponseEntity<?> search() throws SQLException {
List<Emp> emps = svc.search();
if (emps != null && emps.size()>0) return new ResponseEntity<List<Emp>>(emps, HttpStatus.OK);
return new ResponseEntity<Void> (HttpStatus.NO_CONTENT);
}
@GetMapping("/emp/{num}")
@ApiOperation(value="{num}에 해당하는 Emp 정보를 반환한다.",response=Emp.class)
public ResponseEntity<?> select(@PathVariable int num) throws SQLException{
Emp emp = svc.select(num);
if(emp != null) return new ResponseEntity<Emp> (emp, HttpStatus.OK);
return new ResponseEntity<Void> (HttpStatus.NO_CONTENT);
}
}
@ApiOperation : 요청 URL에 매핑된 API 에 대한 설명
동작 영상
다음과 같이 API 확인 및 테스트가 가능하다!!
'WEB > 기타' 카테고리의 다른 글
Maven 이란? (0) | 2023.03.25 |
---|---|
Web Server와 WAS (0) | 2023.01.14 |