gpt4 book ai didi

rest - 使用一长串查询参数设计 RESTful 查询 API

转载 作者:行者123 更新时间:2023-12-03 04:26:37 25 4
gpt4 key购买 nike

我需要设计一个 RESTful 查询 API,它根据一些过滤器返回一组对象。通常的 HTTP 方法是 GET。唯一的问题是,它至少可以有十几个过滤器,如果我们将所有过滤器作为查询参数传递,则 URL 可能会变得很长(长到足以被某些防火墙阻止)。

减少参数数量不是一个选项。

我能想到的一种替代方法是在 URI 上使用 POST 方法并将过滤器作为 POST 正文的一部分发送。这是否违背 RESTfull(进行 POST 调用来查询数据)。

大家有更好的设计建议吗?

最佳答案

请记住,对于 REST API,这完全取决于您的观点。

REST API 中的两个关键概念是端点和资源(实体)。宽松地说,端点要么通过 GET 返回资源,要么通过 POST 和 PUT 等接受资源(或以上的组合)。

众所周知,使用 POST 时,您发送的数据可能会也可能不会导致创建新资源及其关联端点,这些端点很可能不会在 POSTed url 下“事件”。换句话说,当您发布时,您将数据发送到某处进行处理。 POST 端点不是通常可以找到资源的位置。

引用自RFC 2616 (省略无关部分,突出相关部分):

9.5 POST

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • ...
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • ...

...

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created)...

我们已经习惯了代表“事物”或“数据”的端点和资源,无论是用户、消息还是书籍 - 无论问题领域有何要求。但是,端点也可以公开不同的资源 - 例如搜索结果。

考虑以下示例:

GET    /books?author=AUTHOR
POST /books
PUT /books/ID
DELETE /books/ID

这是一个典型的 REST CRUD。但是如果我们添加:

POST /books/search

{
"keywords": "...",
"yearRange": {"from": 1945, "to": 2003},
"genre": "..."
}

此端点没有任何非 RESTful 的地方。它接受请求正文形式的数据(实体)。该数据就是搜索条件 - 与其他任何数据一样的 DTO。该端点生成一个资源(实体)来响应请求:搜索结果。搜索结果资源是临时资源,立即提供给客户端,无需重定向,也不会从其他规范 URL 中暴露。

它仍然是 REST,只不过实体不是书籍 - 请求实体是书籍搜索条件,响应实体是书籍搜索结果。

关于rest - 使用一长串查询参数设计 RESTful 查询 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14202257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com