- RESTful Web API Design with Node.js 10
- Valentin Bojinov
- 311字
- 2021-08-27 18:37:24
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" } } }
- Mastering Ext JS(Second Edition)
- 零基礎學Visual C++第3版
- 數據庫程序員面試筆試真題與解析
- Mastering Google App Engine
- PHP 7+MySQL 8動態網站開發從入門到精通(視頻教學版)
- Android開發:從0到1 (清華開發者書庫)
- Learning Concurrency in Kotlin
- OpenStack Networking Essentials
- Android應用開發實戰
- Learning iOS Security
- Mockito Essentials
- Getting Started with Electronic Projects
- H5+移動營銷設計寶典
- jQuery權威指南
- Learning Ext JS(Fourth Edition)