是不是 客户端通过 PUT 方法向指定 URL 发送一段 json ,服务端返回 200 表示更新成功?
201 Created
200 OK
一些更具体的信息可以看我的 GitHub 仓库:https://github.com/bolasblack/api-guide#%E8%AF%B7%E6%B1%82%E6%96%B9%E6%B3%95
事实上你确实可以用POST做任何事,但是这个是违反HTTP标准,属于“滥用”。既然用REST,那么最好还是遵守HTTP标准中定义的“语义”。HTTP标准中,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用于请求服务器接受请求中附带的实体,用于在请求的URI指定的位置新建一个资源。
而PUT是
The PUT method requests that the enclosed entity be stored under the supplied Request-URI.
PUT方法请求服务端在指定URI的位置存储附带的实体。
可见,POST是用于新建一个资源,而PUT是用于更新/替换一个资源。
对于PUT方法应用中的各种情况的处理:
If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem.
如果URI指定的资源已经存在,那么附带的实体应该被视为已经存在的资源的修改过的版本。如果指定的资源不存在,那么服务端应当创建一个新的资源。
如果创建了新资源,服务器应当返回201(已创建)告知客户端。如果修改了已经存在的资源,服务端应当返回200(OK)或204(无内容)告知客户端请求已经成功完成。如果资源无法创建或修改,需要返回一个适当的响应码指明错误。
两个问题:
PUT 操作是幂等的。所谓幂等是指不管进行多少次操作,结果都一样。比如我用 PUT 修改一篇文章,然后再做同样的操作,每次操作后的结果并没有不同;POST 操作既不是安全的,也不是幂等的,比如常见的 POST 重复加载问题:当我们多次发出同样的 POST 请求后,其结果是创建出了若干的资源;
更新成功与否取决于你的设计,与返回码无关,不信楼主可以在更新成功的情况下,返回非 200 码(比如 201,以及任何你想要的 比如 404);