API 对已执行或不需要的操作的响应应该是什么

What should be the API Response for already performed or unneeded operations

当我的 JsonAPI 被要求执行一些已经完成或没有意义的操作时,我应该 return 什么响应(代码 + 内容)?

示例:假设我想请求发表一篇文章。文章草稿通过特定端点更新(此处无关),有特定端点发布(我们感兴趣的响应)

4 种不同的场景,我需要弄清楚每次发送什么类型的响应:

  1. 从未请求发布,并且文章包含所有发布强制信息,请求发布是有意义的,所以我 returning 一个 202 接受的响应,其中包含文章资源"publication requested at" 属性

  2. 一个成功的发布发布请求已经sent/acknowledged,中间没有人来得及审阅。我应该 return ?

  3. 之前的发布请求已经过某人审核并被接受(该文章现已发布)。 API 再次收到对这篇已经发表的文章的发表请求,没有意义,我该怎么办 return ?

  4. 该文章未填写所有必填信息,有人提出发表请求。我必须通知用户他的请求由于错误而未被批准。我在想这个我可以 return 验证错误列表。听起来公平吗?

你的前两颗子弹...

  • 从未请求发布,并且文章具有所有发布强制信息,请求发布是有意义的,所以我 return 对包含 [=69= 的文章资源的 202 接受响应]属性
  • 一个成功的发布发布请求已经sent/acknowledged,中间没有人来得及审阅。我应该 return 做什么?

...接受 202:

202 Accepted: The request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, and may be disallowed when processing occurs.

你的第三个项目符号:

  • 先前的发布请求已由某人审核并被接受(该文章现已发布)。 API 再次收到对这篇已经发表的文章的发表请求,没有意义,我该怎么办 return ?

我可能会在这里使用 303 重定向:

303 See other: The response to the request can be found under another URI using a GET method. When received in response to a POST (or PUT/DELETE), the client should presume that the server has received the data and should issue a redirect with a separate GET message.

但您也可以考虑 308 永久重定向:

308 Permanent Redirect (RFC 7538): The request and all future requests should be repeated using another URI. 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. So, for example, submitting a form to a permanently redirected resource may continue smoothly.

但我更倾向于 303。

你的最后一颗子弹:

  • 该文章未填写所有必填信息,有人提出发表请求。我必须通知用户他的请求由于错误而未被批准。我在想这个我可以 return 验证错误列表。听起来很公平?

这是标准 "bad client request" (4xx),有错误:

400 Bad Request: The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).

请确保在列举响应中的错误时不要公开服务的实现细节。

记住:

  • 2xx 响应表示成功
  • 3xx 响应表示重定向
  • 4xx 响应表明客户端失败
  • 5xx 响应表明服务请求的应用程序部分失败

来源:List of HTTP status codes