使用XML和JSON Content-Type对RESTful API进行版本控制 [英] Versioning a RESTful API with both XML and JSON Content-Type

查看:138
本文介绍了使用XML和JSON Content-Type对RESTful API进行版本控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据

According to this excellent presentation on designing RESTful interfaces, the preferred way to implement versioning is to utilize the Accept-header, using something like:

GET /products HTTP/1.1
Host: example.com
Accept: application/vnd.com.myservice.v2+xml

这对于XML Content-Types来说非常合适,但是是否可以使用相同的方案对等效于JSON的版本进行?

This works perfectly for XML Content-Types, but is possible to use the same scheme for versioning the JSON-equivalent?

即,是否可以要求:

GET /products HTTP/1.1
Host: example.com
Accept: application/vnd.com.myservice.v2+json

响应类似于:

HTTP/1.1 200 OK
Content-Type: application/vnd.com.myservice.v2+xml; charset=UTF-8
Allow: GET, POST

<?xml version="1.0" encoding="utf-8"?>
<products xmlns="urn:com.example.products" 
          xmlns:xl="http://www.w3.org/1999/xlink">
  <product id="1234" xl:type="simple" 
           xl:href="http://example.com/products/1234">
    <name>Red Stapler</name>
    <price currency="EUR">3.14</price>
    <availability>false</availability>
  </product>
</products>

和JSON等价物(某种):

and the JSON equivalent (sort of):

HTTP/1.1 200 OK
Content-Type: application/vnd.com.myservice.v2+json; charset=UTF-8
Allow: GET, POST

[
  {
    id: "1234",
    links: [
      {
        rel: "self",
        href: "http://example.com/products/1234"
      }
    ],
    name: "Red Stapler",
    price: {
      currency: "EUR",
      value: 3.14
    },
    availability: false
  }
]

推荐答案

您可以通过添加内容类型中的版本来实现版本控制:

You can implement versioning either by adding a version in the 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

您可以将内容类型application/vnd.acme.user+xml分为两部分:第一个(application/vnd.acme.user)描述媒体类型,第二个(xml)响应格式.这意味着您可以使用json:application/vnd.acme.user+json之类的另一种格式.

You can split your content type application/vnd.acme.user+xml in two parts: the first one (application/vnd.acme.user) describes the media type, and the second one (xml) the format of the response. That means you can use another format like json: application/vnd.acme.user+json.

在HATEOAS世界中,XML在可读性和语义方面比JSON更好,如果您想使用JSON,您可能会对以下规范感兴趣:

In the HATEOAS world, XML is better than JSON for readability and semantic purposes, if you want to use JSON, you could be interested by this specification: https://github.com/kevinswiber/siren.

这篇关于使用XML和JSON Content-Type对RESTful API进行版本控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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