Reputation: 1597
I have a REST api in Spring Boot:
@GetMapping("/test")
public MyClass getData() {
return something;
}
This endpoint can be requested with up to 10 RequestParams. I know of course all of the 10 possible RequestParams, however client can chose to request with anywhere between 0 to all 10 of the RequestParams.
Now I need a way to handle this without plugging all 10 RequestParams in as parameters in the getData() method. Is it not possible to register all possible RequestParams in a class, and the use that class as parameter ing the getData()?
Something like this:
public class ParamClass {
private @RequestParam("ParamOne") String ParamOne;
private @RequestParam("ParamTwo") Set<String> ParamTwo;
private @RequestParam("ParamThree") Integer ParamThree;
}
And then
@GetMapping("/test")
public MyClass getData(@RequestParam ParamClass params) {
return something;
}
Please note: The parameters can be different types (String, int, Set, etc.) therefore the following solution comes very close but does not solve it because the map requires a consistent value type: how to capture multiple parameters using @RequestParam using spring mvc?
Upvotes: 0
Views: 1991
Reputation: 1
you can use @RequestBody annotation. It will map the HttpRequest body to class object. As spring boot has jackson in its classpath, it will do automatic deserialization of the inbound HttpRequest body onto a Java object.
public class ParamClass {
String paramOne;
String paramTwo;
....
String paramTem;
// default constructor
// all getters
// all setters
}
@PostMapping("/test")
public MyClass getData(@RequestBody ParamClass params) {
return something;
}
Client should send json data to the api /test
Upvotes: 0
Reputation: 2199
You can define all parameters in your method and set them as 'not required'.
@GetMapping("/test")
public MyClass getData(@RequestParam(name="p1", required=false) String p1,
@RequestParam(name="p2", required=false) Integer p2,
...) {
return something;
}
Then you can choose which parameters to define in your url. The others are null. Or you define a default-value in the RequestParam
-Annotation.
Upvotes: 0
Reputation: 198
One way to do that would be receive a Map with the params, the problem is that all the params would have the same type, and you would have to cast to the proper type in your code:
@ResponseBody
public String updateFoos(@RequestParam Map<String,Object> allParams) {
return "Parameters are " + allParams.entrySet();
}
Upvotes: 2