[REST API] REST API의 정적 필터링 구현하기

민지·2024년 3월 14일
0

REST API - Spring Boot

목록 보기
20/27

1. 배울 것

REST API 응답의 customizing하는 방법?

  • Serialization(직렬화) : object -> Stream 전환해주는 프로세스 (JSON)

    • 가장 인기많은 자바의 JSON 직렬화 프레임워크 - Jackson
  • customizing the REST API response, by Jackson framework!

1. response의 field명을 customize하는 법

  • @JSONProperty

    	@Size(min = 2, message = "Name should have atleast 2 characters")
    	@JsonProperty("customized_userName")
    	private String name;
    
    	@Past(message = "Birth Date should be in the past")
    	@JsonProperty("customized_birthDate")
    	private LocalDate birthDate;

2. (REST API response 커스텀화) - 선택된 field만 리턴하기

  • 이를 filtering이라고 한다.
  • 예 - 자바 빈에 정의한 비밀번호가 있다고 하자. JSON response에 비밀번호를 제외하고 싶다면 어떻게 해야 할까?
  • 2가지 타입의 filtering
    • Static Filtering : different REST API라고 하더라도, 빈에 대한 똑같은 필터링이 적용된 것.
      가령 위 그림에서 field2가 비밀번호라고 한다면, 그 어떤 REST API라더라도, 항상 비밀번호를 block시켜 필터링하는 것이다.
      • @JsonIgnoreProperties, @JsonIgnore
    • Dynamic Filtering : 특정 REST API에 맞는, 특정 필터링을 반환하는 것
      어떤 REST API든 항상 동일한 필터링을 반환하는 정적 필터링과 다르게, 동적 필터링은 만약 field2를 1번 REST API에서는 필터링 안하고, 2번 REST API에서는 필터링을 한다면, 각각의 REST API에 맞게 특정 필터링을 적용하는 것을 말한다.
      -> 따라서 response의 일부로 필드를 전송할지 동적으로 결정하는 것
      • @JsonFilter with FilterProvider

2. 정적 필터링 구현 과정

/restfulwebservices/filtering/FilteringController.java New - @JsonIgnore

예를 들어, SomeBean의 field2가 비밀번호이고, REST API의 response에 이를 반환하고 싶지 않다면, 해당 필드를 필터링 대상으로 지정할 수 있다.

@RestController
public class FilteringController {

	@GetMapping("/filtering")
	public SomeBean filtering() {
		return new SomeBean("value1", "value2", "value3");
	}
}

SomeBean - field2에 @JsonIgnore 추가

public class SomeBean {

	public String field1;

	@JsonIgnore
	public String field2;
	
	public String field3;

	public SomeBean(String field1, String field2, String field3) {
		super();
		this.field1 = field1;
		this.field2 = field2;
		this.field3 = field3;
	}

	public String getField1() {
		return field1;
	}

	public String getField2() {
		return field2;
	}

	public String getField3() {
		return field3;
	}

	@Override
	public String toString() {
		return "SomeBean [field1=" + field1 + ", field2=" + field2 + ", field3=" + field3 + "]";
	}

}

실행결과,

list를 추가해도, 여전히 @JsonIgnore을 통해, "field2" 값만 JSON 응답에서 무시된다.

@RestController
public class FilteringController {

	@GetMapping("/filtering")
	public SomeBean filtering() {
		return new SomeBean("value1", "value2", "value3");
	}

	@GetMapping("/filtering-list")
	public List<SomeBean> filteringList() {

		return Arrays.asList(new SomeBean("value1", "value2", "value3"), 
				new SomeBean("value4", "value5", "value6"));
	}
}

/restfulwebservices/filtering/FilteringController.java New - @JsonIgnoreProperties

혹은 위의 @JsonIgnore과 같이, @JsonIgnoreProperties는 클래스에 지정해, field1과 field2를 JSON 응답에서 모두 무시할 수 있다.

@JsonIgnoreProperties({ "field1", "field2" })
public class SomeBean {

	public String field1;

	// @JsonIgnore
	public String field2;
	public String field3;
	.
	.
	.
	// same codes
}

이처럼,

멤버변수에 붙이는 @JsonIgnore과 클래스에 붙이는 @JsonIgnoreProperties를 통해, 정적 필터링을 구현할 수 있었다.

개인적으로 @JsonIgnore 어노테이션이 더 사용하기 편리하다!




참고 및 출처
이 시리즈는 Udemy 강의의 내용을 정리한 것입니다.
https://www.udemy.com/course/spring-boot-and-spring-framework-korean/

profile
배운 내용을 바로바로 기록하자!

0개의 댓글