如何构建 REST 资源层次结构? [英] How to structure REST resource hierarchy?
问题描述
我是服务器端 Web 开发的新手,最近我阅读了很多关于实现 RESTful API 的文章.我仍然坚持的 REST API 的一个方面是如何构建标识客户端可以与之交互的资源的 URI 层次结构.具体来说,我一直在决定制作层次结构的详细程度以及在资源由其他资源类型组成的情况下该怎么做.
I'm new to server side web development and recently I've been reading a lot about implementing RESTful API's. One aspect of REST API's that I'm still stuck on is how to go about structuring the URI hierarchy that identifies resources that the client can interact with. Specifically I'm stuck on deciding how detailed to make the hierarchy and what to do in the case of resources being composed of other resource types.
这里有一个例子,希望能说明我的意思.想象一下,我们有一个 Web 服务,可以让用户从其他用户那里购买产品.所以在这个简单的例子中,有两个顶级资源用户和产品.这是我开始构建 URI 层次结构的方式,
Here's an example that hopefully will show what I mean. Imagine we have a web service that lets users buy products from other users. So in this simple case, there are two top level resources users and products. Here's how I began to structure the URI hierarchy,
对于用户:
/users
/{id}
/location
/about
/name
/seller_rating
/bought
/sold
对于产品:
/products
/{id}
/name
/category
/description
/keywords
/buyer
/seller
在这两种情况下,每个层次结构中的对象都引用另一个层次结构中对象的子集.例如 /users/{id}/bought
是一些用户购买的产品列表,它是 /products
的子集.此外,/products/{id}/seller
引用了销售特定产品的用户.
In both of these cases objects in each hierarchy reference a subset of the objects in the other hierarchy. For example /users/{id}/bought
is a list of the products that some user has bought, which is a subset of /products
. Also, /products/{id}/seller
references the user that sold a specific product.
由于这些 URI 引用其他对象或其他对象的子集,API 是否应该支持这样的内容:/users/{id}/bought/id/description
和 /products/{id}/buyer/location
?因为如果支持这些类型的 URI,有什么可以阻止这样的 /users/{id}/bought/{id}/buyer/bought/{id}/seller/name
或类似的东西错综复杂?另外,在这种情况下,由于服务器中的路由器必须解释任意长度的 URI,您将如何处理路由?
Since these URI's reference other objects, or subsets of other objects, should the API support things like this: /users/{id}/bought/id/description
and /products/{id}/buyer/location
? Because if those types of URI's are supported, what's to stop something like this /users/{id}/bought/{id}/buyer/bought/{id}/seller/name
, or something equally convoluted? Also, in this case, how would you handle routing since the router in the server would have to interpret URI's of arbitrary length?
推荐答案
目标是构建方便的资源标识符,不要试图交叉引用所有内容.您不必在 URL 表示中重复您的数据库关系:)
The goal is to build convenient resource identifiers, don't try to cross-reference everything. You don't have to repeat your database relations in URL representation :)
/product/{id}/buyer
之类的链接不应该存在,因为该资源已经有了标识符:/user/{id}
Links like /product/{id}/buyer
should never exist, because there already is identifier for that resource: /user/{id}
尽管拥有 /product/{id}/buyers-list
是可以的,因为买家列表是产品的属性,在其他上下文中不存在.
Although it's ok to have /product/{id}/buyers-list
because list of buyers is a property of product that does not exist in other contexts.
这篇关于如何构建 REST 资源层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!