Implementing Static Filtering for Rest API


 Customize Rest Api Responses - Filtering and More..

Serialization: convert object into stream (Example JSON)

Example we are Return like

we are getting back EntityModel in below method

public EntityModel<User> getUsers() {}

we are getting back List of User in below method

public List<User> getAllUsers() {}


Converting into a Json or to an XML is what is called serialization

Most Popular JSON serialization in Java Is Jackson

  • How About customize the REST Api response returned by Jackson Framewor
    • 1: Customize Field name in response
      • @JSONProperty
Value ("") indicates that the name of field (or, derived nameof an accessor method (setter / getter)) is to be used as the property name without any modifications; a non-empty valuecan be used to specify a different name.Property name refers to the name used externally, as the propertyname in JSON objects (as opposed to internal name of field inJava Object)

public class User {

private Integer id;

@Size(min = 2, message = "Name min size is 2 atleast")

@JsonProperty("user_name")

private String name;

@Past(message = "birthDate should be lessthan from todays date")

@JsonProperty("birth_date")

private LocalDate birthDate;

@Pattern(regexp = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", message = "email in not in proepr format")

private String emailID;

        

//getter setter

}


Output:

  • 2: Return Only Selected Fields
    • Filtering
      • Example: Filtering out the passwords
    • Two Types: of Filtering
      • Static Filtering: Same Filtering for a bean across different REST API
        • @JsonIgnoreProperties, @JsonIgnore
      • Dynamic Filtering: Customize filtering for abean for specific REST API
        • @JsonFilter with filterProvider


Static Filtering:


SomeBean.java

public class SomeBean {

private String field1;

@JsonIgnore

private String field2;

private String field3;

//getter & Constructor

}

FilteringController.java

@RestController

public class FilteringController {

@GetMapping("/filtering")

public SomeBean filtering() {

return new SomeBean("value1", "value2", "value3");

}

}


O/P


{ "field1": "value1", "field3": "value3" }


as in given avobe example we have filter out the field2 so now oly

1 and 3 field will be in json Output


also

@GetMapping("/filtering=list")

public List<SomeBean> filteringList() {

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

}


O/P


@JsonProperties({"field1", "field2"})

at class level




Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API