Study Record

24/02/14 - Swagger, MappingJacksonValue, HATEOUS

고고잉93 2024. 2. 15. 13:19
728x90
@JsonIgnoreProperties(value = {"password","ssn"})
public class User {

	//@JsonIgnore
    @Schema(title = "사용자 id",  description = "비번입렵")
    private String password;
    
    //@JsonIgnore
    @Schema(title = "사용자 id",  description = "ssn입력")
    private String ssn;

◈ Restful Web Services개발

■  Response 데이터 제어하기(외부에 데이터를 보여주고 싶지 않을때)

 ●  @JsonIgnoreProperties(value = {"password","ssn"}) OR //@JsonIgnore 어노테이션 추가하기

 

■ MappingJacksonValue

● SimpleBeanPropertyFilter : Jackson 라이브러리에서 제공하는 필터 클래스이며 .filterOutAllExcept() 매서드로 속성 지정

SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("id", "name", "joinDate", "ssn");

  - id, name, joinDate, ssn 속성만을 포함하고 나머지는 제외하는 필터(filter) 생성.

 

● FilterProvider

  - 생성한 필터를 관리하는 인터페이스

@JsonFilter("UserInfo")
public class AdminUser {
FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo", filter);

 - SimpleFilterProvider.addFilter : 위에서 생성한 filter를 AdminUser클래스에서 설정한 "UserInfo"라는 필터이름으로 적용

 

● MappingJacksonValue

AdminUser adminUser = new AdminUser();

MappingJacksonValue mapping = new MappingJacksonValue(adminUser);
mapping.setFilters(filters);

 

.setFilters를 사용하여 필터 적용.

 

■ HATEOAS(Hypermedia as the Engine od Application State)

  - Rest API를 사용하는 클라이언트가 전적으로 서버와 동적인 상호작용이 가능하도록 하는것.

      → → 클라이언트가 서버로 요청을 할때, 요청에 필요한 하이퍼링크(URI)를 포함시켜서 응답하는것.

 

● Hateoas 사용 예시

계좌번호가 "12345"인 계좌의 정보를 조희 하는 경우에 해당 계좌의 상태 ( 잔여 금액 등등..)에 따라 접근 가능한 추가

API들이 LINKS라는 이름으로 제공된다.

 

기존의 전형적인 REST API 응답

 

HATEOAS 적용

https://joomn11.tistory.com/26

 

● 적용하기

public EntityModel<User> retrieveUser(@PathVariable int id) {
    User user =service.findOne(id);

  EntityModel : Spring HATEOAS에서  제공하는 클래스로 단일 객체에 대한 모델을 나타낸다. 

EntityModel entityModel = EntityModel.of(user);

 

 .of 매서드를 사용하여 user를 감싸 EntityModel을 생성한다.

WebMvcLinkBuilder linTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
entityModel.add(linTo.withRel("all=users")); //all-users -> http://localhost:8082/users

 

WebMvcLinkBuilder는 HATEOAS에서 제공하는 링크생성 클래스

methodOn 메서드를 사용하여 현재 클래스(this.getClass())에서 retrieveAllUsers 메서드를 호출하는 프록시를 생성.

linkTo(methodOn(this.getClass()).retrieveAllUsers())는 retrieveAllUsers 메서드에 대한 링크를 생성하는 WebMvcLinkBuilder를 반환한다. withRel 메서드는 링크에 대한 관계(rel)를 추가

 

■ Swagger

   - Restful API를 문서화하고 사용자가 쉽게 테스트하고 호출할 수 있도록 하는 도구.

 

1. 백엔드와 프론트 개발자간의 소통을 돕는다.

2. API버전 관리가 용이

 

● 사용법

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

 build.gradle에 dependencies를 추가해준다. 추가만 해줘도 /swagger-ui/index.html 로 사용가능!

 

@Configuration
@OpenAPIDefinition (
        info = @Info(title="Myrestful Service APi",
                     description = "Springboot Restful API입니당",
                     version="v1.0.0")
)
@RequiredArgsConstructor
public class
NewSwaggerConfig {
    @Bean
    public GroupedOpenApi customTestAPI(){
        String[] paths = {"/users/**", "/admin/**"};
        return GroupedOpenApi.builder()
                .group("일반 사용자와 관리자를 위한 User 도메인에대한 api")
                .pathsToMatch(paths)
                .build();
    }
}

추가로 Swagger에 추가적인 정보를 기록해보자.

 

여기서 @Bean GroupedOpenApi를 빈에 등록하고 경로를 {"/users/**", "/admin/**"}; 로 묶어 해당 경로에서의 API만 불러오도록 설정한다.

 

@RestController
@RequiredArgsConstructor
@Tag(name = "user-conttttttotoot",description = "일반 사용자 서비스임니돠")
public class UserController {

    private final UserDaoService service;

    @GetMapping("/users")
    public List<User> retrieveAllUsers() {
        return service.findAll();
    }


    @Operation(summary = "사용자 정보 조회 API",description = "사용자 ID를 이용하여 정보 상세 조회")
    @ApiResponses({
            @ApiResponse(responseCode ="200", description = "okok"),
            @ApiResponse(responseCode ="400", description = "bad request!!!"),
            @ApiResponse(responseCode ="404", description = "user not found!!!!!"),
            @ApiResponse(responseCode ="500", description = "Internal server err"),
    })
    @GetMapping("/users/{id}")
    public EntityModel<User> retrieveUser(

 

@Schema(description = "사용자 상세정보를 위한 도메인 객체")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Schema(title = "사용자 id",  description = "사용자 id자동생성됨")
    private Integer id;

 

728x90

'Study Record' 카테고리의 다른 글

24/02/16  (0) 2024.02.17
24/02/15 SQL Lv2  (0) 2024.02.16
24/02/13 SQL Lv2, User mode/Karnel mode, Switch  (0) 2024.02.13
24/02/09 @ControllerAdvice, @ExceptionHandler, @Valid  (1) 2024.02.10
24/02/08 Network(TCP/IP, UDP) SQL LV1, HashMap  (0) 2024.02.09