javaspringrestcontent-negotiation

Ignore accept header in Spring REST WS


I have something like this:

@RestController
public class MyController {

    @GetMapping("/myAddress")
    public Response generateReportAsync(...) {
         ...
    }

}

This web service generates a report file according to the Accept header requested (pdf, xls, csv...). Since the generation is performed asynchronously, the response returned is actually a JSON at first and the report is made accessible later.

My problem is that when I invoke this passing an Accept header like application/pdf I receive a 406 back since the WS replies with a JSON. Is there any way I can force a JSON reply with any Accept header I receive only for this specific mapping?

I've tried playing around with the produces and consumes properties on the GetMapping annotations without luck. Other answers I've found use a global configuration or mess with the HttpResponse. If possible I'd like to use a more declarative approach with annotations.

Thanks!


Solution

  • Sounds like you need to implement a single REST End Point working as follows:

    Now for the important part: All requests must include Accept header listing both application/json and one or more supported report formats (e.g. application/pdf, text/csv), otherwise a 406 Not Acceptable is returned.

    Quality values (;q=) can be used to indicate preference of report format.


    Since different clients might want the same report in different formats, the server should support generation of multiple report files.

    E.g. if a request is received with Accept: application/pdf, application/json;q=0.1, the system will start generating a PDF. If another request is received with Accept: text/csv, application/json;q=0.1, the system will start generating a CSV file, in parallel or queued.

    Subsequent requests will ignore pending/completed reports that are not acceptable. e.g. if a third request is received with Accept: text/csv;q=0.5, application/pdf, application/json;q=0.1, the system will start generating a CSV file, the system will return status response of PDF generation, or download the PDF if completed.