一般与特定端点 - Restful API 设计

General vs Specific Endpoints - Restful API design

有什么好的理由不为所有资源创建一个通用端点,and/or将所有资源概括为一个?

Facebook 的 Graph API 似乎就是这样构建的。没有 /api/users/api/companies 等。或者它可能只是与服务器上不同资源对话的通用接口?

显然,如果不同的资源具有相似的功能,这种方法可以减少后端的大量代码复制。

Is there any good reason why not to make a general endpoint for all resources, and/or to generalize all resources into one?

是的——但这些原因并不适用于所有情况。

如有疑问,请查看 Chapter 5 of Fielding's dissertation

The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.

特别是关于资源 -- Ian Robinson 在他的演讲中谈到了其中的一些内容:The Counterintuitive Web

Specialization and innovation depend on an open set.

在RPC 中,端点集是封闭的,而可以发送给它的消息集是开放的。您通过创建新消息进行创新。在 REST 中,消息集是封闭的,端点集是开放的——您可以通过创建新的端点来进行创新。

后一种方法的优点是您可以使用通用组件来分配工作,因为它们只需要对有限数量的消息有有限的理解。例如,缓存不需要了解有效负载的详细信息和意图来确定要做什么;他们只需要标识符和一些标准化的元数据,就可以了。

现在,采用 GraphQL,有 a caching story。但不要忽视:该策略不是 "oh, just plug in any commodity web cache".

课程用马;这是一种权衡,而不是 right/wrong 二分法。如果您的项目非常成功,以至于只有 REST 架构限制可以拯救您,那么您已经将问题交给了其他人并退休到您最喜欢的热带岛屿。