如何设计REST风格的搜索/过滤? [英] How to design RESTful search/filtering?
问题描述
我目前正在制订和实施在PHP中一个RESTful API。不过,我已经成功实现我最初的设计。
I'm currently designing and implementing a RESTful API in PHP. However, I have been unsuccessful implementing my initial design.
GET /users # list of users
GET /user/1 # get user with id 1
POST /user # create new user
PUT /user/1 # modify user with id 1
DELETE /user/1 # delete user with id 1
到目前为止pretty标准,对吧?
So far pretty standard, right?
我的问题是与第一个 GET /用户
。我正在考虑在请求体发送参数来过滤列表。这是因为我希望能够没有得到一个超级长的URL指定复杂的过滤器,如:
My problem is with the first one GET /users
. I was considering sending parameters in the request body to filter the list. This is because I want to be able to specify complex filters without getting a super long url, like:
GET /users?parameter1=value1¶meter2=value2¶meter3=value3¶meter4=value4
相反,我想有这样的:
Instead I wanted to have something like:
GET /users
# Request body:
{
"parameter1": "value1",
"parameter2": "value2",
"parameter3": "value3",
"parameter4": "value4"
}
这是更可读并为您提供了更大的可能性,设置复杂的过滤器。
which is much more readable and gives you great possibilities to set complex filters.
总之,的file_get_contents('PHP://输入')
没有返回请求主体的 GET
要求。我也试过 http_get_request_body()
,但共享的主机,我使用不具有 pecl_http
。不知道它会帮助反正
Anyway, file_get_contents('php://input')
didn't return the request body for GET
requests. I also tried http_get_request_body()
, but the shared hosting that I'm using doesn't have pecl_http
. Not sure it would have helped anyway.
我发现这个问题并意识到GET可能是不应该有请求主体。这是一个有点尚无定论,但他们劝告反对。
I found this question and realized that GET probably isn't supposed to have a request body. It was a bit inconclusive, but they advised against it.
所以,现在我不知道该怎么办。如何设计一个RESTful搜索/ filterng功能?
我想我可以使用 POST
,但似乎不是很REST风格。
I suppose I could use POST
, but that doesn't seem very RESTful.
推荐答案
实现一个RESTful的搜索,最好的办法是考虑搜索本身是一个资源。然后,你可以,因为你正在创建一个搜索中使用POST谓词。你不必为了使用一个POST字面上创建在数据库中的东西。
The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.
例如:
Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
"terms": {
"ssn": "123456789"
},
"order": { ... },
...
}
您正在创建从用户的角度进行搜索。这样做的实现细节是不相关的。一些RESTful API可能甚至不需要持久性。这是一个实现细节。
You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.
这篇关于如何设计REST风格的搜索/过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!