In REST, create a single content type or have sepe

2019-04-13 03:36发布

问题:

If I want to follow the practice of using a custom content type for my REST API, am I supposed to define a single custom content type for my entire project or define custom content types for each resource representation (what is sent to/back from my REST API) used on my project?

That is, if I am building a "Bookstore" REST API where the services say are in the namespace com.mycompany.mybookstoreapp, do I create a single content type:

Content-Type: application/com.mycompany.mybookstoreapp+xml

Or do I create a content type for each type of data that can be posted/retreived via my Bookstore REST APIs?

Content-Type: application/com.mycompany.mybookstoreapp.user+xml
Content-Type: application/com.mycompany.mybookstoreapp.order+xml
Content-Type: application/com.mycompany.mybookstoreapp.book+xml

回答1:

Describing a content type for each data seems the safest solution. If you want to be HATEOAS compliant later for some reasons, it will be easier. In another hand, it doesn't make much sense to have one content type for everything. The content type describes the type for a specific data.

About versioning, you can add versioning to your API in three different ways. First, you can add the version number in your URIs, this is the easy way:

/api/v1/users

Or you can use your new content type:

application/vnd.acme.user-v1+xml

Or you can also use a qualifier in your Accept header, that way you don’t touch your content type:

application/vnd.acme.user+xml;v=1

It’s really up to you. The first solution is easy but less RESTful than the two other solutions. But those solutions require more smart clients.



标签: rest