athina
athina

Reputation: 23

List of enums in an @RequestParam object

Say I have a GET endpoint in Spring Boot controller, which accepts an object as @RequestParam

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam FilterParams filterParams) {
  return fooDao.getFoos(filterParams);
}

where FilterParams is a class which contains a List attribute (or whatever other list of Objects)

public class FilterParams {
  public List<Bar> bars;
}

and Bar is an enum (for this example)

public enum Bar {
  Baz, Zap
}

If we post a GET request on this endpoint with a list of filterParameter attributes seperated by "," i.e. curl -X GET localhost:8080/foos?bars=BAZ,ZAP, Spring fails to parse it as a List and tries to deserialize one single value BAZ,ZAP into an enum. If it weren't an enum, it would also behave the same, i.e. deserialize parameter id=1,2 into a single element of a list of Strings. Is it possible to override this behaviour? And if so, how would one achieve this?

I do know that i could achieve this by declaring multiple parameters as /foos?bars=BAZ&bars=ZAP but it is not convenient for me

Upvotes: 2

Views: 3677

Answers (1)

user1555543
user1555543

Reputation: 51

I don't think query parameters will be converted to an Object. One other way to handle this case, declare the request parameter as a String. Update your documentation to say that the request parameter supports coma separate values. You can parse this String and map it to an enum. This approach will help in the long run when you want to support new values.

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bars") String filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be passed arround in the code
  return fooDao.getFoos(filterParams);
}

Passing the following URL should work now: curl -X GET localhost:8080/foos?bars=BAZ,ZAP

One other approach would be to declare the query parameter as a List.

@GetMapping(value = "/foos")
public List<Foo> getFoos(@RequestParam("bar") List<String> filterParams) {
// Parse the String using coma as delimiter, map the String to an enum so that enum can be  passed arround in the code
  return fooDao.getFoos(filterParams);
}

In this case, the URL might get long based on the number a parameters your service supports: curl -X GET localhost:8080/foos?bar=BAZ&bar=ZAP

Upvotes: 2

Related Questions