Reputation: 8000
I am trying to implement field selectors on my rest API using Spring. Currently I have taken following approach.
I have this model.
public class Employee {
public String name;
public int id;
public Department department;
public Address address;
}
Now if I want to expose this model as rest I will have following end point http://test.com/employees.
In order to support field selection I will have http://test.com/employees?fields=id,name.
To support this I have created a map which have model to its fields mapping and then I use if-else conditions to return only the expected fields.
As this is a standard design or requirement for a rest api, there can/ should be a better approach.
Can somebody guide me to some resource which helps in this case as I could not find anything.
Thanks.
Upvotes: 1
Views: 67
Reputation: 5659
One of ways you can solve this problem is by using Java's Reflection API. You already know the class that you are exposing. For every 'field' that your client requests, check if there is a getter method for that. If so, invoke it and add the value to the response object. If you go this route, do test performance and see if it suits you.
Upvotes: 1