在 REST 中,为每个资源表示创建单个内容类型还是具有单独的内容类型? [英] In REST, create a single content type or have seperate content types for each resource representation?

查看:59
本文介绍了在 REST 中,为每个资源表示创建单个内容类型还是具有单独的内容类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想遵循为我的 REST API 使用自定义内容类型的做法,我应该为我的整个项目定义一个自定义内容类型还是为每个资源表示定义自定义内容类型(发送到/从我的 REST API 返回)用于我的项目?

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?

也就是说,如果我正在构建一个书店"REST API,其中服务说在命名空间 com.mycompany.mybookstoreapp 中,我是否创建单一内容类型:

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

或者我是否为可以通过我的 Bookstore REST API 发布/检索的每种类型的数据创建一个内容类型?

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

推荐答案

为每个数据描述一个内容类型似乎是最安全的解决方案.如果您以后出于某些原因想要符合 HATEOAS,那会更容易.另一方面,为所有内容使用一种内容类型并没有多大意义.内容类型描述了特定数据的类型.

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.

关于版本控制,您可以通过三种不同的方式向 API 添加版本控制.首先,您可以在 URI 中添加版本号,这是一种简单的方法:

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

或者您也可以在 Accept 标头中使用限定符,这样您就不会触及您的内容类型:

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

这完全取决于您.第一个解决方案很简单,但不像其他两个解决方案那么 RESTful.但这些解决方案需要更聪明的客户.

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 中,为每个资源表示创建单个内容类型还是具有单独的内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆