users@jersey.java.net

Re: [Jersey] Retrieving list of items that belong to another item

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 26 Jan 2009 12:54:55 +0100

On Jan 25, 2009, at 2:01 PM, John O'Conner wrote:

> Hi All,
>
> I have an AccountsResource defined with these REST endpoints:
> /accounts
> /accounts/{id} -- AccountsResource returns an AccountResource
>
> Also I have a GatewaysResource with these endpoints:
> /gateways
> /gateways/{id}
>
> Accounts have gateways. Now what I'd like to do is define an
> endpoint that provides all the gateways of a given account, maybe
> like this:
> /accounts/{id}/gateways
>
> With Jersey, do I simply add another method to the
> AccountsResource.java file like this? I think this uri seems
> reasonable if I want the list of gateways for a particular account,
> especially since a list of gateway ids is in fact a property in my
> Account class:
>
> @Path({id}/gateways)
> public List<Gateway> getGateways(@PathParam("id") long id) {
> List<Gateway> gateways = null;
> // now perform the db query for this list
> return gateways;
> }
>
> Or maybe this belongs in AccountResource instead like this?
> @Path("/gateways")
> public List<Gateway> getGateways() { ...
>
> I noticed that @Path examples often show a "resource" class as the
> return value....but in my case above its just the list of actual
> objects. Is that ok?
>

An @Path without a HTTP-method-based annotation identifies a sub-
resource locator, a Java method, that returns a sub-resource, from
which further matching of the path is performed.


> I have a GatewaysResource already that is providing a list of all
> gateways in the system. Can I reuse that instead? Can I return a
> GatewaysResource from an AccountsResource or from a AccountResource?
>

Yes, as long as you ensure that the GatewaysResource works correctly
as a root resource and as a sub-resource of AccountResource, namely
the scope of the information is reduced for the latter.

   // In the AccountResource

     // Sub-resource locator return GatewaysResource resource
     // for all gateways associated with an account
     @Path("/gateways")
     public Gateway getGateways() {
         return new GatewaysResource(...);
     }

Alternatively you could have two types of gate way resources extending
a common gateway class.

Paul.