gRizzlyGR
gRizzlyGR

Reputation: 315

Intertwining resources in Jersey in a mutual way

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:

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.

Upvotes: 1

Views: 110

Answers (3)

gRizzlyGR
gRizzlyGR

Reputation: 315

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
}

Upvotes: 2

Sikorski
Sikorski

Reputation: 2691

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.

Upvotes: 0

badoit
badoit

Reputation: 43

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
    }
}

Upvotes: 3

Related Questions