0

I have a following REST end-point in my Spring Boot Application.

/employees

This returns following response.

{
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "department": "IT",
    "salary": "$5000"
    ...
    //There are more here
}

Now, I need to have this end-point used by two different clients. But the need to know only part information from this end-point.

So for client1, the output would be as below:

{
    "id" : 1,
    "firstName" : "John",
    "lastName" : "Doe"
}

And for the other client(client2), the response should be.

{
    "id" : 1,
    "department": "IT",
    "salary": "$5000"
}

How can I approach this problem is best possible way?

Client1 and Client2 would be distinguished by their authentication details. Maybe a configuration which specifies how the response entity needs to be filtered. That way, whenever I am configuring a new client, I can create a new configuration for the client and that takes care of the response filtering.

divinedragon
  • 5,105
  • 13
  • 50
  • 97

3 Answers3

0

You can do it like:

Client - 1:

ResponseEntity<ObjectType1> result = restTemplate.exchange(url, HttpMethod.POST, ObjectType1.class);

Client - 2:

ResponseEntity<ObjectType2> result = restTemplate.exchange(url, HttpMethod.POST, ObjectType2.class);

Where your custom objects should look like so

public class ObjectType1{
   int id;
   String firstName;
   String lastName;

   //default Constructor & getter & setters
}

public class ObjectType1{
    int id;
    String department;
    String salary;

    //default Constructor & getter & setters
}

In above cases, spring/ object mapper will automatically map the returned response/parameters with your required object parameters(objectType1 or objectType2)

Afridi
  • 6,753
  • 2
  • 18
  • 27
  • This becomes a pretty hard-wiring of the stuff. Tomorrow my clients increase, I will have to make code modifications. I was looking for a more generic/configurable option where I don't have to create new classes. Probably some configuration files, and it takes care of that. – divinedragon May 16 '17 at 15:30
0

you can autowire HttpServletRequest object , in the controller class, and then use it to get client details like header or user-agent information. Then these info can be used to check the client type and accordingly response date can be build and send.

0

You should investigate json views feature of Jackson. You can use the same object but filter the fields based on views. You can find some more details at this question

Community
  • 1
  • 1
user871199
  • 1,420
  • 19
  • 28