Is using custom json content-types a good idea

2019-06-15 02:24发布

I'm designing a RESTful API and in an attempt to be descriptive and make documentation clearer I want to declare my content-type http header as follows:

Content-Type: application/vnd.mycorp.mydatatype+json

where mycorp is an identifier unique to my corporation and mydatatype is unique to each data type. An example would be:

Content-Type: application/vnd.ford.car+json

{
"manufactured_year": 2000
, "color": "blue"
, "hp": 160
, "model" "Focus"
, "type": "sedan"
}

This content-type would be required in order for a POST to be valid and would be sent as a part of a response. It seems to me like a nice way to define rules for what should be inside the payload.

I can't seem to find a good resource on whether this is a good idea or if it is even allowed by IETF standards.

So, question is: Which is more feasible, application/vnd.mycorp.mydatatype+json or just application/json?

2条回答
SAY GOODBYE
2楼-- · 2019-06-15 02:32

The question is strongly related to your REST API versioning.

Content type is used to, well, define the type of the content. If you use a standard content type like

application/json

you're saying to the client that the message is in JSON format. This is enough for all the web applications which do not version their API or support only the latest version. If you are going to have clients using different versions of your API, standard content types are not enough. Consider the following scenario:

Take your example as version 1 of the message

Content-Type: application/vnd.ford.carV1+json

{
"manufactured_year": 2000
, "color": "blue"
, "hp": 160
, "model" "Focus"
, "type": "sedan"
}

At some point you decide you want represent the color using hexadecimal code. Therefore you create version 2 of the type

Content-Type: application/vnd.ford.carV2+json

{
"manufactured_year": 2000
, "color": "0000FF"
, "hp": 160
, "model" "Focus"
, "type": "sedan"
}

When the client asks for a car specifies the correct content type, which includes the version. This tells the application whether send the color as hex code or as name.

Here you are versioning the representation of a resource. An alternative to support resource representation versioning is adding the version as custom header (while keeping content-type standard)

Content-Type: application/json
Message-Version: 1.0
查看更多
相关推荐>>
3楼-- · 2019-06-15 02:39

It's allowed, definitely. Whether it's a good idea is another story.

My rule of thumb is that it's a primary data format that's useful across a lot of things, needs to be identified on its own, and you need to interoperate across many applications, definitely give it a media type.

However, if it's just a message in your API among many, and it's only good for one resource (or one resource "type"), just use application/json.

YMMV, of course.

查看更多
登录 后发表回答