RESTful API,如果查询字符串不够长怎么办? [英] RESTful API, what if the query string isn't long enough?

查看:47
本文介绍了RESTful API,如果查询字符串不够长怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个产品资源集合:/products.

我们希望过滤此集合以仅返回具有特定class id 列表之一的成员.例如:

GET/products?classes=100,101,102

这应该返回包含列出的任何类的产品成员的集合.

我们遇到的问题是,我们正在处理数以千计的产品和类,因此 id 的类列表可能有数千个 - 对于查询字符串来说太长了.

我很想尽可能坚持 RESTful 原则,所以我喜欢这样一个事实,即资源 /products?classes=100,101,102 在使用 GET 调用时返回一个过滤产品集合.

显然,我们可以将 id 的列表以 JSON 格式包含在正文中,但这意味着调用 GET/products 不会返回表示资源的状态(资源是 URL),因为主体用于提供过滤器选项.

请求已过滤的集合的最佳方法是什么,但过滤器选项太长而无法使用查询字符串..?

解决方案

来自 @C 的有趣评论.Smith 建议使用设置为 GETX-HTTP-Method-Override 标头进行 POST 调用并传递 id 在正文中.这行得通.

考虑之后我们可能会限制查询字符串中允许的类id的数量,并建议进行多次调用,分解id> 的列表,每组 200 个.提交超过 200 个将返回错误.

GET/products?classes=1004,2342,8753...(限制为 200 个 id)

GET/products?classes=2326,3343,6981...(限制为 200 个 id)

然后可以很容易地将结果拼接在一起.

这个方法可以让你使用 5,000 个 id,例如,通过执行 25 次调用,虽然不理想,但对于我们的用例来说是可以的.

We have a resource collection for products: /products.

We want to filter this collection to only return the members which have one of a list of specific class id's. For example:

GET /products?classes=100,101,102

This should return a collection of product members which have any of the classes listed.

The issue we have, is that we're working with thousands of products and classes, so the class list of id's could be thousands long - too long for a query string.

I'm keen to stick to RESTful principles whenever we can, so I like the fact that the resource /products?classes=100,101,102 when called with GET returns a filtered products collection.

Obviously, we could include the id's list in the body in JSON format, but that would mean that the call GET /products won't return a representation of the state of the resource (the resource being the URL), because the body is being used to provide filter options.

What's the best way to request a collection which is filtered, but the filter options are too long to use the query string..?

解决方案

Interesting comment from @C. Smith who suggests making a POST call using a X-HTTP-Method-Override header set to GET and passing the id's in the body. This would work.

After thinking about it we're probably going to limit the number of class id's allowed in the query string, and suggest making multiple calls, breaking up the id's list into say, groups of 200. Submitting more than 200 would return an error.

GET /products?classes=1004,2342,8753... (limited to 200 id's)

GET /products?classes=2326,3343,6981... (limited to 200 id's)

Then the results can easily be stitched together after.

This method would let you use 5,000 id's for example, by doing 25 calls, which while not ideal, is ok for our use case.

这篇关于RESTful API,如果查询字符串不够长怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆