Home > Software design >  Send custom response fields based on user inputs fields in spring
Send custom response fields based on user inputs fields in spring

Time:06-29

I have one requirement, where user will send fields that he wants in response rather than entire JSON:

?fields=name,description

Basically i have employee JSON, which has many fields. But he wants only name and description. He can change it also with other fields. Later he can select other fields and send in request.

How to achieve this?

Thanks in advance.

CodePudding user response:

to access query params use @RequestParam annotation.

@GetMapping("/api/foos")
public String getFoos(@RequestParam String fields) {
    // ...
}

Variable fields will contain the complete string, so you'll have to split it by delimiter, e.g. by using String.split.

Then build the desired response format, if it's a flat structure you could use a Map<String, String>, which will be deserialized to a flat json object.

Map<String,String> response = new HashMap<>();
response.put("fieldName","value");

https://mkyong.com/java/java-how-to-split-a-string/

CodePudding user response:

Definitely, this is a case to avoid over-fetching or under-fetching of data and also a good example for GraphQL API development. Once you develop the GraphQL API with the schema you will have fewer future change impacts. The client can fetch whatever fields needed Link for when to use graphql

  • Related