1

I have a collection of people with id's assigned to them. I want the user to have the Ability to retrieve people collection using multiple ID's ( 0 to many).I can do this if I have one id as the parameter:

@Path( "{people/id}" )
@GET
public PeopleDTO findOne ( @PathParam( "id" ) int id ) {
    return PersonDAO.findOne( id );
}

How do I write a similar method where user can specify multiple id's and that will retrieve info for that many people? Or to say it differently, I want to output collection of people accepting filter for 0...* IDs.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
user3528213
  • 1,415
  • 3
  • 15
  • 18
  • Take a look at [this question](http://stackoverflow.com/questions/3629225/is-it-possible-to-configure-jax-rs-method-with-variable-number-of-uri-parameters) – Branislav Lazic Jun 10 '15 at 18:19
  • You are welcome. Google more next time before posting question on SO. – Branislav Lazic Jun 10 '15 at 18:21
  • Please, please, the answer in that link is a _horrible_ solution for this problem. You are making the URI completely unRESTful if you do this. Trying to do something like `.../people/1/2/4/5/6/7` to identify a subset of the parent collection is just ugly. Use a query parameter to filter the parent collection instead. – Paul Samsotha Jun 11 '15 at 00:24

1 Answers1

2

Since you are not trying to access a single resource, then you are trying to access the collections of resources, only you just want a subset. This is pretty common for things like pagination. For that you can just have a query parameter to filter. For instance you can use

.../people?filterIds=1,3,5,6,7,8

Then just use @QueryParam

@GET
@Path("people")
public PeopleDTO getPeople(@QueryParam( "filterIds" ) String id ) {

This can be used to get all the people or a filtered list. You just need to parse the string. First check if it's null, if it is, then it's a request for a full list.

You could also may it more object oriented, and use something like Filtered

@GET
@Path("people")
public PeopleDTO getPeople(@QueryParam( "filterIds" ) Filtered filtered ) {
    String[] values = filtered.getValues();

You can take a look at this to see that can be accomplished. Use something like

public class Filtered {

    private String[] values;
    public String[] getValues() { return values; }
    public void setValues(String[] values) { this.values = values; }

    public static Filtered fromString(String param) {
        if (param == null) return null;

        Filtered filtered = new Filtered();
        filtered.setValues(param.split(",");
        return filtered;
    }
}
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720