在 RESTful 应用程序中,使用“资源”URL 来提供 JSON 数据和访问数据的页面是个好主意吗?如果不是,我应该如何区分这两者?
假设我有一个页面 /routes
并且我有一个列出所有路线的页面。我应该这样做吗:
HTML 页面
GET /routes
Accept: text/html
Response:
<h1>Routes</h1>
<p>blah blah blah</p>
... <table></table>
<script>
$.getJSON('/routes').done(insertDataIntoTable);
</script>
JSON 响应
GET /routes
Accept: application/json
Response:
[
{"number": "95", "start": "Place d'Orléans", "end": "Barrhaven Centre"},
{"number": "96", "start": "Hurdman", "end": "Kanata"},
{"number": "97", "start": "Bayshore", "end": "Airport/Aéroport"},
/* etc... */
]
这似乎是错误的,因为这两个请求指向相同的 URL/URI,但返回不同的资源(一个是应用程序页面,另一个是数据)。为 Accept: text/html
提供这样的内容似乎更合适:
GET /routes
Accept: text/html
Response:
<table>
<thead>
<tr><th>Number</th><th>Start</th><th>End</th></tr>
</thead>
<tr><td>95</td><td>Place d'Orléans</td><td>Barrhaven Centre</td></tr>
<!-- etc... -->
</table>
(我可能不会这样做,因为它不是很有用。)
我考虑过几种选择:
- 如上所述使用 HTTP
Accept
header - 使用查询参数(例如
/routes?type=html
) - 为页面使用不同的路径(例如,
/routes
用于数据,/pages/routes
用于应用程序) - 使用扩展(例如,
/routes
用于数据,/routes.php
用于应用程序)
1和2好像不太对。我不太热衷于 3 尽管页面本身就是一种资源,但它并不完全代表应用程序中的实体。选项 4 看起来很丑。
我试过查看主要网站的作用,它们都提供来自不同主机/子域的数据(例如:facebook.com
/graph.facebook.com
, twitter.com
/api.twitter.com
) 这不是我的选择。
有什么想法吗?这个问题不应该主要基于意见,因此非常感谢引用。
最佳答案
数字 4 看起来是最佳选择,因为 HTML 页面是与 API 中的资源不同类型的资源。
将页面与 API 资源分开似乎是个好主意。
来自 twitter 和 Facebook 的示例也支持这种方法。
关于json - 在 REST 中提供 HTML 应用程序页面和 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25375393/