如何设计 RESTful 搜索/过滤? [英] How to design RESTful search/filtering?

查看:41
本文介绍了如何设计 RESTful 搜索/过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 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

到目前为止还算标准,对吧?

So far pretty standard, right?

我的问题是第一个 GET/users.我正在考虑在请求正文中发送参数来过滤列表.这是因为我希望能够在不获取超长 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&parameter2=value2&parameter3=value3&parameter4=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://input') 没有返回 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 搜索/过滤功能?

我想我可以使用 POST,但这似乎不是很 RESTful.

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.

这篇关于如何设计 RESTful 搜索/过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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