Tuesday, February 6, 2018

Execute different methods based on accept header and set priority when no accept header provided

I had a REST API which was accepting a file upload and in response generating another file. This was working fine without any issue with below code:
@POST 
@Path("/convert")
@Produces("application/octet-stream")
@Consumes(MediaType.MULTIPART_FORM_DATA)
 But, later I had to add a requirement where in certain cases the response in NOT stream but a JSON object. I wanted to keep the API same but behave differently only for limited number of cases. After looking into some Jersey docs and some testing below is what implemented
@POST
@Path("/convert")
@Produces("application/octet-stream;qs=1")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@POST
@Path("/convert")
@Produces("application/json;qs=.5")
@Consumes(MediaType.MULTIPART_FORM_DATA) 
Note that both of the APIs have signature, and only difference is in response type. With these signatures client when passes "accept" header as  "application/octet-stream" then first method is called. And when "accept" header is "application/json" then second method is called.
In addition to this, I also used the "quality" (note qs), this is set to 1 for first method and 0.5 for the second method. Because of this my code change was backward compatible. Which means, when no accept header is provided. In that case the first method is called because qs=1.