6

我们的 REST API 之一将导致执行一个长时间运行的进程。与其让客户端等待很长时间,我们更愿意立即返回响应。

因此,让我们考虑这个用例:申请人提交申请,最终会有结果。由于这是一个非常大规模的平台,我们不能将应用程序持久化到存储中,而必须将其放入队列中进行处理。

在这种情况下,返回应用程序最终将存在的 URI(例如http://example.com/application/abc123 )是否可以接受?

类似地,将结果文档的 URI(代表有关应用程序的决定)作为应用程序资源表示的一部分返回是否可以接受?结果文档将在几分钟内不会创建,并且对其 URI(或应用程序的 URI)的 HTTP GET 将导致 404,直到它们被持久化。

在这种情况下,最佳做法是什么?分发资源的“未来”URI 是否可以接受?

4

2 回答 2

8

我看不出这种设计有什么问题,但请仔细查看HTTP 状态代码列表以获得更好的响应。恕我直言,第一个请求应返回 202 Accepted:

请求已被接受处理,但处理尚未完成。

同时对最终结果的 URL 的请求应返回 204 No Content (?):

服务器成功处理了请求,但没有返回任何内容

当然,当处理完成时,它最终应该返回 200 OK。

于 2012-10-07T18:50:46.700 回答
2

来自“ RESTful Web Services Cookbook

问题

您想知道如何为执行计算或验证数据等任务提供资源抽象。

解决方案

将处理函数视为资源,并使用 HTTP GET 获取包含处理函数输出的表示。使用查询参数为处理函数提供输入。

This entails just GET requests on a URI that represents the processing function. Your example 'http://example.com/application/abc123' URI. When returning a response you would include what information you have by now and use HTTP codes to indicate the status of the processing as already suggested by Tomasz.

However..., you should not use this approach, if the subsequent application processing stores or modifies data in any way.

GET requests should never have side effects. If the submittal of the application leads in anyway (even if only after being processed in from queue) to new information / data being stored, you should use a PUT or a POST request with the application's data in the request's body. See "Why shouldn't data be modified on an HTTP GET request?" form more information.

If they application's submittal stores or modifies data, use the pattern for asynchronous processing: a POST or PUT request with the application's details.

For example

POST http://example.com/applications

which returns "201 Created" with the URI of the new application resource.

or

PUT http://example.com/applications/abc123

which returns "201 Created" and

Both would also return any resource information that is already known at that time.

You can then safely perform GET requests on the URI of the new resource as they now only retrieve data - the results of the application processing so far - and no data is stored or modified as a result of the GET.

To indicate the application's processing progress, the GET request can either return some specific status code in the response (queued, processing, accepted, rejected), and/or use the HTTP response codes. In either case a "200 OK" should only be returned when the application's processing is complete.

于 2012-10-08T06:46:01.303 回答