0

This is a follow up question on my earlier post at PUT or POST HTTP verb when calling API endpoint which performs both UPDATE and INSERT?

I have a RESTful Web API (written in ASP .Net Core 2.1) which receives a "change-log" from the consuming client app. This is a JSON class containing all the modifications to the database that were performed on the client app while it was working in offline mode. Once the client app goes online, it synchronizes its database with an online/live database by sending the API all the changes that have happened since the last sync. So it sends the API a change-set/change-log with a bunch of UPDATE, INSERT and DELETE lists for the various tables/objects.

On the API side, I don't actually delete anything from the live database - I simply flag things as deleted (so I set a boolean field to true, i.e. deleted = true). So technically, the API only performs INSERTS and UPDATES on the database

What status code should the action method of the API return upon successful completion? Since it is doing a combination of both INSERTS and UPDATES, should it return a 201 Created? Or simply a 200 OK? Or a 200 OK if only updates were performed, else a 201 if any inserts were performed? Also, in the response body, since I'm not actually planning on returning any ID's or objects in the body (since multiple objects wouldve been updated and inserted), I would like to return just plain text saying how many objects were updated, how many were inserted and how many were flagged as deleted. Is this possible, or even a good idea?

Thanks

4

2 回答 2

1

对于RFC 4918207中定义的 HTTP 协议的扩展来说,这似乎是一个很好的情况:

11.1。207 多状态

( 207Multi-Status) 状态码为多个独立操作提供状态。

该文件还规定了以下内容:

13. 多状态响应

在多个状态代码可能适用的情况下,多状态响应传达有关多个资源的信息。[...]

虽然207用作整体响应状态码,但接收方需要查阅多状态响应体的内容,以获取有关方法执行成功或失败的更多信息。响应可用于成功、部分成功以及失败情况。

根元素以任意顺序multistatus包含零个或多个response元素,每个元素都包含有关单个资源的信息。每个“响应”元素必须有一个href元素来标识资源。

[...]

于 2018-09-12T09:57:55.237 回答
1

对我来说,这听起来不像 REST api。如果您通过一个端点一次更新和创建多个资源,这有点违反 REST 原则。

鉴于这更像是一个类似 RPC 的调用,我会200 OK简单地返回表明操作成功。

然而,有一种方法可以把它变成更像 REST 的东西。

如果您有多个资源,则这些资源中的基础数据可以组合并表示为单个资源,一种“集合”资源。

假设该资源托管在/clientstate/<client-id>. 执行 aGET返回整个 'clientstate' 资源。

然后要更新此资源,您将使用PUT替换整个客户端状态。对于客户来说,将多个数据库记录绑定到单个资源是完全不相关的。

如果你PUT用来替换整个客户端状态,那么适当的响应代码应该仍然是200 OK. 或者204 No Content,如果您之后没有返回任何有趣的东西。

建议不要重新使用207 Multi-Status.

于 2018-09-12T10:11:23.460 回答