官术网_书友最值得收藏!

Separation of the representation and the resource

A resource is just a set of information, and as defined by principle 4, it can have multiple representations; however, its state is atomic. It is up to the caller to specify the desired media type with the Accept header in the HTTP request, and then it is up to the server application to handle the representation accordingly, returning the appropriate content type of the resource together with a relevant HTTP status code:

  • HTTP 200 OK in the case of success
  • HTTP 400 Bad Request if an unsupported format is given or for any other invalid request information
  • HTTP 406 Not Acceptable if an unsupported media type is requested
  • HTTP 500 Internal Server Error when something unexpected happens during the request processing

Let's assume that, at server side, we have items resources stored in an XML format. We can have an API that allows a consumer to request the item resources in various formats, such as application/xml, application/json, application/zip, application/octet-stream, and so on.

It would be up to the API itself to load the requested resource, transform it into the requested type (for example, JSON or XML), and either use ZIP to compress it or directly flush it to the HTTP response output.

The caller would make use of the Accept HTTP header to specify the media type of the response they expect. So, if we want to request our item data inserted in the previous section in XML format, the following request should be executed:

GET /category/watches/watch-abc HTTP/1.1 
Host: my-computer-hostname 
Accept: text/xml 
 
HTTP/1.1 200 OK 
Content-Type: text/xml 
<?xml version="1.0" encoding="utf-8"?>
<Item category="watch">
<Brand>...</Brand>
</Price></Price> </Item>

To request the same item in JSON format, the Accept header needs to be set to application/json:

GET /categoery/watches/watch-abc HTTP/1.1 
Host: my-computer-hostname 
Accept: application/json 
 
HTTP/1.1 200 OK 
Content-Type: application/json 
{
  "watch": {
    "id": ""watch-abc"",
    "brand": "...",
    "price": {
      "-currency": "EUR",
      "#text": "100"
    }
  }
}
主站蜘蛛池模板: 杨浦区| 同江市| 翁牛特旗| 平邑县| 洮南市| 新化县| 阿克| 阿拉善右旗| 乃东县| 庄浪县| 页游| 朝阳县| 舞钢市| 师宗县| 曲周县| 泰顺县| 汶上县| 余干县| 惠州市| 徐州市| 浮梁县| 包头市| 白山市| 从江县| 宁国市| 宜川县| 东安县| 深水埗区| 和静县| 滁州市| 天气| 浏阳市| 黔江区| 外汇| 长兴县| 芮城县| 双牌县| 汕尾市| 合阳县| 濉溪县| 宜宾市|