1

I learned that writing @Consumes and @Produces annotations on every endpoint is good programming. However, if I declare the type in the endpoint, do I still need the annotation?

What is good programming?

@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf") // Content type declared in annotation
@Path(GET_BILL_FOR_SYSTEM)
public Response getBillForTheSystem(@QueryParam(value = "year") Long year) {
    return Response.ok( billSheetService.getBillForTheSystem(year) )
            .type( "application/pdf" ) // Content type declared in response builder
            .header( "Content-Disposition", "attachment; filename=\"BillForTheSystem.pdf\"" )
            .build();
}
Jorn
  • 20,612
  • 18
  • 79
  • 126
Paul
  • 1,344
  • 4
  • 19
  • 37

1 Answers1

0

You are correct. There is no functional reason to declare the value of the response content type twice. In fact, such duplication is often frowned upon.

However, if you have tooling that inspects your code to generate documentation, it might be able to read the annotation but not the type returned by the code itself. So in that case, I'd prefer leaving only the annotation.

Jorn
  • 20,612
  • 18
  • 79
  • 126
  • 1
    It's actually used for content-negotiation. It's not duplication. One is for the response while the other is for the request. The annotation will tell the requester that application/pdf is what the endpoint produces. So when a client uses an Accept header that is not application/pdf, it will get a 406 Not Acceptable response. This is what should be expected and is good practice. Always use the annotations. – Paul Samsotha Oct 25 '21 at 07:43
  • https://stackoverflow.com/a/51182697/2587435 – Paul Samsotha Oct 25 '21 at 07:47
  • @PaulSamsotha so, we should use only the annotation. Duplication is still bad. – Jorn Oct 25 '21 at 11:40