#Content Negotiation with Accepts Header.

2 messages · Page 1 of 1 (latest)

novel knoll
#

HTTP has a number of infrequently used features, one of which is the Accepts header.

Lets say I have a route, say /api/products/1232. I have a variety of users of my system with different needs. One only cares about the shipping data, the e-commerce site cares about the marketing stuff, and the accountants care about the historical pricing. Now, in this particular made up example, there are predefined, public mime types for each of those application/vnd.shipping.item+json, application/vnd.commerce.product+json and application/vnd.pricing.history+json. The normal way a client would say which representation you want is to pass the mime-type in the Accepts header, and the server would return a response matching that mime type or return a 406 Not Accpetable

I could just pass all those into @ApiProduces but from what I can tell that assumes that each mime type would use the same schema.

This is not required by the OpenApI spec (https://swagger.io/docs/specification/media-types/). The example uses the same Schema reference, but there is no reason why you couldn't point to different schemas for each mimetype (indeed, having the same schema for multiple mime types is kind of pointless, unless one is specific and the other the generic application/json.

As to how I would accomplish the feat of returning different schemas? Thats a future me problem but the simplest (and least elegant) solution would be to include the request object in the arguments, and return different Types based on the contents of the accepts header. A better solution would be if the @Get() and other decorators allowed you to set a list of mime types to respond with so you could have multiple functions for the same path but each responding to different Accepts headers. The best, IMO, solution would be to have the method return a superset of the data and use your own ClassSerializerInterceptor to return the right schema

-Adam

ornate phoenix