반응형
Swagger
API 문서를 자동으로 만들어주는 라이브러리
단순 문서 뿐 아니라 API를 문서내에서 parameter를 넣어가며 바로 실행 해볼 수 있음
rest api 제작 후 따로 테스트 페이지나 postman으로 실행해보는 대신 swagger 문서 만들어서 실행 가능
복잡하지 않은 시스템이라면 rest api 서버에 swagger를 적용시켜두고, 해당 api를 호출하는 작업자에게 복작하게 설명하고 문서 만들 것 없이 swagger 문서 url만 보내서 알아서 작업하게 할 수 있음
Swagger Test
pom.xml 라이브러리 추가
https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
UserDTO
public class UserDTO {
private int no;
private String id;
private String pwd;
private String name;
private java.util.Date enrollDate;
public UserDTO() {}
public UserDTO(int no, String id, String pwd, String name, Date enrollDate) {
super();
this.no = no;
this.id = id;
this.pwd = pwd;
this.name = name;
this.enrollDate = enrollDate;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.util.Date getEnrollDate() {
return enrollDate;
}
public void setEnrollDate(java.util.Date enrollDate) {
this.enrollDate = enrollDate;
}
@Override
public String toString() {
return "UserDTO [no=" + no + ", id=" + id + ", pwd=" + pwd + ", name=" + name + ", enrollDate=" + enrollDate
+ "]";
}
}
반응형
ResponseMessage
public class ResponseMessage {
private int httpStatus;
private String message;
private Map<String, Object> results;
public ResponseMessage(int httpStatus, String message, Map<String, Object> results) {
super();
this.httpStatus = httpStatus;
this.message = message;
this.results = results;
}
public int getHttpStatus() {
return httpStatus;
}
public void setHttpStatus(int httpStatus) {
this.httpStatus = httpStatus;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Map<String, Object> getResults() {
return results;
}
public void setResults(Map<String, Object> results) {
this.results = results;
}
@Override
public String toString() {
return "ResponseMessage [httpStatus=" + httpStatus + ", message=" + message + ", results=" + results + "]";
}
}
SwaggerConfig
http://localhost:8001/swagger-ui/index.html 확인 경로
@Configuration //설정파일이다
@EnableWebMvc //WebMvc 활성화
public class SwaggerConfig {
private ApiInfo swaggerInfo() {
return new ApiInfoBuilder()
.title("GREEDY API")
.description("spring boot swagger 연동 테스트")
.build();
}
@Bean
public Docket swaggerApi() {
return new Docket(DocumentationType.SWAGGER_2) //생김새 설정
.consumes(getConsumeContentTypes())
.produces(getProduceContentTypes())
.apiInfo(swaggerInfo()).select()
.apis(RequestHandlerSelectors.any()) //모든 경로를 API화
// .apis(RequestHandlerSelectors.basePackage("com.greedy.api.section05")) //지정된 패키지만 API화
.paths(PathSelectors.any()) //모든 URL 패턴에 대해 수행
.build()
.useDefaultResponseMessages(false);
}
private Set<String> getConsumeContentTypes() {
Set<String> consumes = new HashSet<>();
consumes.add("application/json;charset=UTF-8");
consumes.add("application/x-www-form-urlencoded");
return consumes;
}
private Set<String> getProduceContentTypes() {
Set<String> produces = new HashSet<>();
produces.add("application/json;charset=UTF-8");
return produces;
}
}
SwaggerTestController
// @Api: 해당 컨트롤러에 내용을 설정
@Api(tags = {"스프링 부트 스웨거 연동 테스트용 컨트롤러"})
@RestController
@RequestMapping("/swagger")
public class SwaggerTestController {
private List<UserDTO> users;
public SwaggerTestController() {
users = new ArrayList<>();
users.add(new UserDTO(1, "user01", "pass01", "홍길동", new java.util.Date()));
users.add(new UserDTO(2, "user02", "pass02", "유관순", new java.util.Date()));
users.add(new UserDTO(3, "user03", "pass03", "이순신", new java.util.Date()));
}
@ApiOperation(value = "모든 회원 목록 조회")
@GetMapping("/users")
public ResponseEntity<ResponseMessage> findAllUsers() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
Map<String, Object> responseMap = new HashMap<>();
responseMap.put("users", users);
ResponseMessage responseMessage = new ResponseMessage(200, "조회 성공!", responseMap);
return new ResponseEntity<>(responseMessage, headers, HttpStatus.OK);
}
@ApiOperation(value = "회원 번호로 회원 조회")
@GetMapping("/users/{userNo}")
public ResponseEntity<ResponseMessage> findUserByNo(@PathVariable int userNo) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
UserDTO foundUser = users.stream().filter(user -> user.getNo() == userNo).collect(Collectors.toList()).get(0);
System.out.println(foundUser);
Map<String, Object> responseMap = new HashMap<>();
responseMap.put("user", foundUser);
return ResponseEntity
.ok()
.headers(headers)
.body(new ResponseMessage(200, "조회 성공!", responseMap));
}
@ApiOperation(value = "신규 회원 추가")
@PostMapping("/users")
public ResponseEntity<?> registUser(@RequestBody UserDTO newUser) throws URISyntaxException {
System.out.println(newUser);
int lastUserNo = users.get(users.size() - 1).getNo();
newUser.setNo(lastUserNo + 1);
users.add(newUser);
return ResponseEntity
.created(URI.create("/entity/users/" + users.get(users.size() - 1).getNo()))
.build();
}
@ApiOperation(value = "회원 정보 수정")
@PutMapping("/users/{userNo}")
public ResponseEntity<?> modifyUser(@RequestBody UserDTO modifyInfo, @PathVariable int userNo) throws URISyntaxException {
System.out.println(modifyInfo);
UserDTO foundUser =
users.stream().filter(user -> user.getNo() == userNo).collect(Collectors.toList()).get(0);
foundUser.setId(modifyInfo.getId());
foundUser.setPwd(modifyInfo.getPwd());
foundUser.setName(modifyInfo.getName());
return ResponseEntity
.created(URI.create("/entity/users/" + userNo))
.build();
}
@ApiOperation(value = "회원 정보 삭제")
@ApiResponses({
@ApiResponse(code = 204, message = "회원 정보 삭제 성공"),
@ApiResponse(code = 400, message = "잘못 입력 된 파라미터")
})
@DeleteMapping("/users/{userNo}")
public ResponseEntity<?> removeUser(@PathVariable int userNo) {
UserDTO foundUser = users.stream().filter(user -> user.getNo() == userNo).collect(Collectors.toList()).get(0);
users.remove(foundUser);
return ResponseEntity
.noContent()
.build();
}
}
반응형
'프로그래밍 > Spring & Spring boot' 카테고리의 다른 글
[Spring boot] RESTAPI_05 Hateoas (0) | 2022.11.03 |
---|---|
[Spring boot] RESTAPI _ 04 Exception & validation(데이터 검증) (0) | 2022.11.03 |
[Springboot] RESTAPI_03 ResponseEntity (0) | 2022.11.03 |
[Spring boot] RESTAPI_02 Response (0) | 2022.11.03 |
[Spring boot ] REST API - 01 REST API & POSTMAN (0) | 2022.11.02 |