users@jersey.java.net

[Jersey] Re: Two endpoints with a common URI prefix

From: Marek Potociar <marek.potociar_at_oracle.com>
Date: Mon, 16 Jun 2014 10:46:51 +0200

On 11 Jun 2014, at 20:46, Kevin Hale Boyes <kcboyes_at_gmail.com> wrote:

> I have two business objects that I'd like to create using a POST to two different RESTful endpoints.
> One is an invoice and the other a purchase order so I have two classes: InvoiceResource and POResource.
>
> They both have a common prefix for the @Path of /scm and I'm versioning the API.
> So, for the two resource the full URI that I POST to is:
> /scm/v1/invoices and /scm/v1/purchaseorders.
>
> One of the things I'd like to do is have all versions in the same java class.
> So, I started writing my InvoiceResource like this:
>
> @Path("/scm")
> public class InvoiceResource {
> @POST
> @Path("/v1/invoices")
> @Consumes(MediaType.APPLICATION_JSON)
> @Produces(MediaType.TEXT_PLAIN)
> public String createInvoice(@Context HttpServletRequest request, String inputs) {
> // do stuff
> }
> }
>
> Later when I work on version two I'd add a new method (createInvoiceV2) to the InvoiceResource class with @Path("/v2/invoices").
>
> So far so good.
>
> I then developed a similar class for purchase orders (POResource) but ran into a problem.
> I can't use the same @Path("/scm") annotation for the new class. I get 404 errors.
>
> One of the things that would fix it is to change the class level annotation to @Path("/scm/v1/invoices") but then I'd need a different class file for each new version of the API.
>
> So, my questions:
> Why can't I have the same @Path in different classes?

You can - since JAX-RS 2.0 / Jersey 2.x. JAX-RS 1.1 / Jersey 1.x does not support this. But you can specify the version as a path template and that should work:

@Path("scm/{version}/invoices")
InvoicesResource

@Path("scm/{version}/orders")
OrdersResource


> Why can't I just remove the class level @Path annotation and have the full URI at the class level?

Not sure I get this one. Can you elaborate, please?

> Is there a good way to solve my problem while meeting my requirement/desire to keep all versions in the same class file?

See my suggestion above.

>
> In case it matters, I'm using Jersey 1.17.

It sure does :)

Marek

>
> Thanks,
> Kevin.