通过添加标头或正文参数添加指令'如何'来执行REST API请求?(Add instruction 'how' to perform a REST API request by adding header or body param?)

想象一个简单的REST API,它允许通过向POST /users发送JSON资源来创建用户帐户,如下所示。 默认情况下,它会向用户发送确认电子邮件。

{ "username": "john@appleseed.com", "password": "secret" }

但是,有时候有充分的理由不发送基于用例的确认,例如另一个API客户端,或者管理员代表他们注册用户。

由于它对创建的资源没有任何影响,但更多的是如何创建用户的指令,它是否应该与请求体分开? 最好的方法是什么?

指定自定义标头Confirmation: no-confirmation 添加查询参数?confirmation=false 将send_confirmation字段添加到请求正文

Imagine a simple REST API that allows to create a user account, by sending a JSON resource to POST /users as in the following. By default it sends out a confirmation email to the user.

{ "username": "john@appleseed.com", "password": "secret" }

However sometimes there are good reasons for not sending out a confirmation based on the use case, e.g. another API client, or admins signing up users on their behalf.

Since it doesn't have any implications on the created resource but is more of an instruction how to create the user, should it be separate from the request body? What's the best way to do this?

Specify a custom header Confirmation: no-confirmation Add a query param ?confirmation=false Add a send_confirmation field to the request body

最满意答案

我们按顺序选择:

通常应该避免添加标题值以指示一些语义差异。 API应该是“可浏览的”,这意味着它只能在链接之后被发现。

从REST角度来看,添加查询参数完全等同于创建另一个URI。 如何暴露它并不重要,重点是客户端需要遵循它所在的先前“状态”的一些链接。这实际上是可以的,只要指向这些资源的链接指示您描述的不同语义:像管理员创建用户,创建自己的用户等。

另请注意,API不一定会公开是否发送确认。 API应该公开“目的”,然后服务器可以决定用例是否保证确认电子邮件。

将send_confirmation放在JSON表示中。 如果这是用户可用的功能,这是可以的。 例如,我可以要求确认电子邮件。 如果我不能,并且它仅用于区分不同的用例,那么我宁愿选择选项2。

简介 :对于您描述的情况,我会选择选项2:管理员和普通用户的不同资源。

Let's take the options in order:

Adding a header value to indicate some semantic difference should be generally avoided. The API should be "browseable", meaning it should be discoverable following links only.

Adding a query parameter is, from REST perspective completely equal to creating another URI. It does not really matter how you expose it, the point is that the client needs to follow some links from the previous "state" it was in. This is actually ok, as long as the links to these resources indicate the different semantics you described: like creating users by admin, users creating themselves, etc.

Also note, that the API should not necessarily expose whether a confirmation is sent. The API should expose the "purpose", the server then can decide whether the use-case warrants a confirmation email.

Putting a send_confirmation in the JSON representation itself. This is ok, if this is a functionality available for the user. For example I can ask for a confirmation email. If I can't, and it is only used for differentiating different use-cases, then I would rather prefer option 2.

Summary: For the case you are describing I would pick option 2: different resources for admins and normal users.

更多推荐