5

I want to create a REST-GET controller in spring-mvc that takes a list of objects, eg 10 ids as follows:

@RestController
public class MyRest {
   @RequestMapping(method = RequestMethod.GET)
   public Object test(@RequestParam value="id" required=false) List<Integer> ids) {
    Sysout(ids);
  }
}

Anyway when I call it, I have to repeat the id param multiple times:

localhost:8080/app?id=1&id=2&id=3&...

It is possible to change the param to some kind of list? Eg

 app?id=1,2,3,4,5

And if yes, is this advisable? What's better from the client point of view?

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • You can do both but none of them is recommended. If you want to sumbit so much information send some in json/xml format. So, for the answer to your question, use the first format - it is more readable from user perspective. – Ivan T Jan 23 '15 at 13:27
  • 1
    Same requirement is discussed on- http://stackoverflow.com/questions/2602043/rest-api-best-practice-how-to-accept-list-of-parameter-values-as-input – Amit Jan 23 '15 at 13:36

3 Answers3

2

Its better to use POST message with JSON or XML as request body. As you never know how many id's will be passed.

@RestController
public class MyRest {
   @RequestMapping(method = RequestMethod.POST)
   public Object test(@RequestBody IDRequest request) {
    Sysout(ids);
  }
  public static final class IDRequest {
    List<Integer> ids;
    <!-- getter/setters--->
  }
}

where the request will be some kind of a JSON or XML like this

{"ids":[1,2,3,4,5,6,7,8,9]}
Babl
  • 7,446
  • 26
  • 37
  • I disagree. POST is used when you modify the state of the system. In this case, he only wants to retrieve data, so GET is better than POST, even repeating the id param – Roman Oct 31 '19 at 10:42
2

You can provide list of objects to rest service as request param.Here is the example

@RequestMapping(value = "/animals, method = RequestMethod.GET)
   public void test(@RequestParam(value="animalsNames[]") String[] animalsNames) {
    Sysout(animalsNames);
  }

And your request looks like

http://localhost:8080/appname/animals?animalsNames[]=dog,horse  
HTTP Method type : GET
Sunil Kumar
  • 5,477
  • 4
  • 31
  • 38
1

Controller :

 public @ResponseBody String getInfos(HttpServletRequest request,
                @RequestParam @DateTimeFormat( @RequestParam List<Long> ids) {...}

Request :

http://localhost:8080/test/api?ids=1,2,3
Amine ABBAOUI
  • 175
  • 1
  • 12