3

I'm using Jersey to implement a RESTful Service with some nested resources. This is a basic example of what I currently have:

@Path("/sites")
public class SiteResource {

    @GET
    @Path("/{siteId}")
    public Site get(@PathParam("siteId") long siteId) {
        Site site = // find Site with siteId

        if (site == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }

        return site;
    }
}

@Path("/sites/{siteId}/articles")
public class ArticleResource {

    @GET
    @Path("/articleId")
    public Article get(@PathParam("articleId") long articleId) {
        Article article = // find Article with articleId

        if (article == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }

        return article;
    }
}

Now imagine I have a Site with siteId = 123 and an Article with articleId = 456. The correct Path to the Article resource would be /sites/123/articles/456. But in my current implementation the siteId is completly irrelevant. You could also use /sites/789/articles/456 to access the resource.

In the ArticleResource#get method I could of course check if the specified Site exists. But this seems rather impractical. If I add another nested resource, I'd have to repeat all the checks.

As this seems to me a common use case, it surprises me that I didn't find any source addressing this problem. So I'm wondering if I'm maybe completely off the track and there is a better way handling nested resources.

Thanks!

1 Answer 1

0

The Article seems to be a child of the Site. So there probably is some kind of relation on the Java and/or database side you can use to get and validate Site and Article.

I'd retrieve the Site including its children and the look if the requested Article is on of those.

If Site and Article where not related, your whole URI scheme would not reflect your resources.

1
  • Yes, the relation between the Site and the Article is also reflected in the Database. The question is where would be the best place to retrieve the Site (or the parent object, to be more generic) and check if it exists? If I do this in ArticleResource#get, I would have to do the same check in every method of every child Resource. May 24, 2013 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.