Question

Currently I am designing how to deal with routing in a versioned rest API where the version is not part of the url, but sent via a header variable.

I have considered/seen things like:

Re-writing the url based on the header variable i.e. the request /orders {X-Media-Type: v1} would rewrite to /v1/orders and then we could have a @Path("/v1/orders") OrderV1Resource {} and thus making v2 would be trivial @Path("/v2/orders") OrderV2Resource {}. (my first preference) How to use a servlet filter in Java to change an incoming servlet request url?

Having a Single @Path("/orders") OrderResource {} where each of it's methods have an injected HeaderParam and I could check the header variable and then decide which Order API implementation I wanted to use (which seems very messy to me)

// pseudo-java code
@Path("/orders") 
OrderResource {
   OrderV1Impl v1Impl;
   OrderV2Impl v2Impl;
   @GET
   public List<Order> findAll(@HeaderParam header) {
       version = header.get("accepts")
       if(version.equals("v1")) { return v1Impl.findAll() }
       else if(version.equals("v2")) { return v2Impl.findAll() }
       return error
   }
}

Or just bundling them up in seperated JARS and having a service look at the header and route to the correct version. (seems to make sense if the app grows to be really large)

Was it helpful?

Solution

I ended up passing the version in via a header then used this to route the desired resource via a javax.servlet.Filter.

Example Accept header: Accept: application/vnd.datarank.v1+json

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top