1

I'm trying to get my head around this RESTful scenario in Jersey: I have two resources, User and Item, and i want to retrieve all the items connected to a certain user and all the users connected to a certain item. In short, there exists a many-to-many relationship between User and Item.

I came across this RESTful design:

  • All the items connected to a certain user: GET .../users/{user_id}/items
  • All the users connected to a certain item: GET .../items/{item_id}/users

How can I implement this in Jersey? I found this solution, but it's related to sub-resources nested in the root resource, whereas in my case User and Item are both root resources accessible via their own URIs.

Community
  • 1
  • 1
gRizzlyGR
  • 306
  • 2
  • 9

3 Answers3

3

The following should work.

@Path("users")
public class UserResource {

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{user_id}/items")
    public Response getItems(@PathParam("user_id") String userId) {
        //get the items and return a response
    }
}

@Path("items")
public class ItemResource {

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{item_id}/users")
    public Response getUsers(@PathParam("item_id") String itemId) {
        //get the users and return a response
    }
}
badoit
  • 43
  • 5
2

I decided to implement the solution suggested here, that is to create specific resources that represent the relantionships described above.

The code that models the items-related-to-users relationship is this:

@Path("users/{userId}/items")
public class RelatedItemResource {

    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Item> getRelatedItems(@PathParam("userId") String userId) {
        // returns list of related items
    }

    // Other methods    
}

The code that models the users-related-to-items relationship is this:

@Path("items/{itemId}/users")
public class RelatedUserResource {

    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<User> getRelatedUsers(@PathParam("itemId") String itemId) {
        // returns the list of related users
    }

    // Other methods
}
Community
  • 1
  • 1
gRizzlyGR
  • 306
  • 2
  • 9
0

For all users connected to a certain item, this sounds more like a search criteria to get a list of users. So i would suggest this path : /users?item={itemid}. Given this notation you can really build a flexible search criteria endpoint where every query parameter is optional and is respected if some value is given in it.

Sikorski
  • 2,653
  • 3
  • 25
  • 46