1

In REST API, I was checking recommendation to version API with accept header as:

Accept: application/vnd.com.myservice.v2+json

Now, server can extract this information and send v2 response. Why are we sending vnd.com.myservice.v2 in accept header where we should only send Accept: application/json? Why shouldn't we create separate header for this?

Sahil Sharma
  • 3,847
  • 6
  • 48
  • 98

1 Answers1

1

Accept is a standard header and is used in media type negotiation. The media type determines how a resource is represented over the wire. Ultimately, that is the API version - just representation of resource.

Accept also has other useful semantics that a custom header doesn't. For example, Accept allows for multiple, quality (e.g. weighted) media types. A client could ask for:

accept: application/vnd.com.myservice.v2+json;q=0.8, application/vnd.com.myservice.v1+json

This indicates to the server that the client prefers V2 of the JSON format with a 80% weight. If it's not available, then the client will also accept V1.

A media type can also use custom parameters. The following is also valid:

accept: application/json;q=0.8;v=2.0, application/json;v=1.0

This says the same thing, but uses a standard media type with a custom parameter instead of a custom media type. This approach is more generic and generally easier to consume in web stacks (in my experience).

I hope that helps.

Chris Martinez
  • 3,185
  • 12
  • 28
  • Just FYI, looks like the `application/json` media type does not allow custom parameters: https://tools.ietf.org/html/rfc4627#section-6 – Grodriguez Oct 09 '19 at 09:13
  • @Grodriguez, any media type _can_ have parameters. Whether they are well-defined or honored by the server is another matter. RFC 4627 has been superseded by RFC 7159. The RFC outlines that JSON documents **must** not use a byte order mark (BOM). This can be problem for parsers who need to handle the difference between UTF-8 vs UTF-16. Media types address this with the generic **charset** parameter. For example, `application/json; charset=utf-8` is completely normal and valid. Clients usually don't ask for specific encodings. – Chris Martinez Oct 11 '19 at 13:05
  • I am not sure about that; others seem to disagree with your interpretation. See, for example https://stackoverflow.com/a/13098683/450398 or https://github.com/pallets/flask/issues/454#issuecomment-4578200 – Grodriguez Oct 14 '19 at 08:00