javaspringrestcontent-negotiation

Is there better approach to Accept Header based content negotiation in Spring API?


I am using Content Negotiation to define multiple response for the same REST API function , by changing the accept header.

  1. Accept header : application/json , should give response as json (used by another service)
  2. Accept header : application/octet-stream , should download the same json response as a file with custom file extension , to be used by UI

Currently i am getting 406 when i pass application/octet-stream in the Accept header.

Is this the right approach ? or should i split the function in to 2 or is it better to use query parameters


Solution

  • Currently i am getting 406 when i pass application/octet-stream in the Accept header.

    Probably, your are using some kind of annotation on your endpoint ...

    Something like: @RequestMapping or (@GetMapping or @PostMapping, etc) ... well, that annotation contains a produces attribute ... that attribute should have the types that your endpoint is expected to produce, in your case: [application/json, application/octet-stream] ...

    Note: the client should indicate to your endpoint, what kind of format he wants ... to do this, the client should specify the format using the Accept http header ...

    Is this the right approach ? or should i split the function in to 2 or is it better to use query parameters?

    For me, it is the right approach because your API is simpler and you're using the mechanisms proposed by the standard ...