REST 集合,好的做法:GET api/CollectionA/<collection id>/CollectionB?



我需要能够获取基于对象集合的集合。为此,我正在考虑几种方法,但不确定哪一种最有意义,所以我会把它们都发布出来。如果有更好的方法我可能没有考虑,那么请随时发布您的建议:)

例如,我将使用产品和评论(即对产品的评论)作为资源。

目标:我们想获得所有产品的评论

方法A:

POST api/Products { json: filters, limits, etc } // returns api/Products/<id>
GET api/Products/<id>/Reviews { json: filters, limits, etc } // returns json array 
// ... of reviews present in products
// id in this case would refer to the collection, which would be cached

方法B:

GET api/Reviews { json: filters } // returns json array of reviews, but needs to 
// ... have either all of the product ids passed as an array (not practical with 
// ... huge collections), or needs to have all of the api/Products filters passed, 
// ... in which case making the code unDRY

方法C:

GET api/Reviews { json: filters: { products: 'api/Products?filters' }...
// is this reasonable?

提前感谢您的帮助,如果这个问题不存在,我很抱歉,我还是REST 的新手

方法D:

access individual products
GET api/Product/<id>
access collection of products:
POST api/Products?filters=stuff..
GET api/Products/<id>
access collection of products' reviews
POST api/Products/<id>/Reviews?filters=stuff
GET api/Products/<id>/Reviews/<id>
... this would thus allow us to cache the result easily, does this seem reasonable to you? 

目标:我们想获得所有产品的评论

基本上,GET /api/products/<id>应该返回一个product,而GET /api/products/<id>/reviews应该返回给定product的所有reviews

如果要获取所有products,则将使用GET /api/products。由于您将reviewsproducts都视为资源,因此我建议您公开所有reviews:

GET /api/reviews

但是您可能想要products他们的reviews。这意味着使用/api/products(例如一组过滤器)获取一些产品,并使用reviews扩展结果集。这个expand术语来自OData协议:http://www.odata.org/documentation/uri-conventions#ExpandSystemQueryOption.

你可以做:

GET /api/products?$expand=reviews
GET /api/products?filter=foo&$expand=reviews

此URI的意思是:"标识products的集合以及与每个product关联的每个reviews

相关内容

最新更新