在REST API设计中找到或创建成语? [英] find-or-create idiom in REST API design?

查看:83
本文介绍了在REST API设计中找到或创建成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有一个用户"资源,对名称"有唯一的约束.您将如何设计REST API来处理查找或创建"(按名称)用例?我看到以下选项:

say we have a 'user' resource with unique constraint on 'name'. how would you design a REST API to handle a find-or-create (by name) use case? I see the following options:

客户端:

POST /user
{"name":"bob"}

服务器:

HTTP 409 //or something else

客户端:

GET /user?name=bob

服务器:

HTTP 200 //returns existing user

选项2:一个请求,两个响应代码

客户端:

option 2: one request, two response codes

client:

POST /user
{"name":"bob"}

服务器:

HTTP 200 //returns existing user

(如果实际创建了用户,则返回HTTP 201)

(in case user is actually created, return HTTP 201 instead)

客户端:

POST /user
{"name":"bob"}

服务器:

HTTP 409 //as in option1, since no CREATE took place
{"id": 1, "name":"bob"} //existing user returned

推荐答案

我相信做到这一点的正确" RESTful方法是:

I believe the "correct" RESTful way to do this would be :

GET /user?name=bob
   200: entity contains user
   404: entity does not exist, so
        POST /user { "name" : "bob" }
           303: GET /user?name=bob
                200: entity contains user

我还是Post-Redirect-Get模式的忠实拥护者,它将需要服务器使用新创建的用户的uri向客户端发送重定向.这样,您在POST情况下的答复将在其主体中包含状态代码为200的实体.

I'm also a big fan of the Post-Redirect-Get pattern, which would entail the server sending a redirect to the client with the uri of the newly created user. Your response in the POST case would then have the entity in its body with a status code of 200.

这确实意味着到服务器的1或3次往返. PRG的最大优点是可以防止客户端在重新加载页面时重新发布,但是您应该阅读有关它的更多信息,以确定它是否适合您.

This does mean either 1 or 3 round-trips to the server. The big advantage of PRG is protecting the client from rePOSTing when a page reload occurs, but you should read more about it to decide if it's right for you.

如果与服务器之间的往返次数过多,则可以执行选项2.通过阅读

If this is too much back-and-forth with the server, you can do option 2. This is not strictly RESTful by my reading of https://tools.ietf.org/html/rfc2616#section-9.5:

由POST方法执行的操作可能不会导致资源 可以通过URI识别的内容.在这种情况下,请输入200(OK)或204 (无内容)是适当的响应状态,具体取决于是否 响应是否包含描述结果的实体.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

如果您可以偏离标准,并且担心往返,那么选择2是合理的.

If you're okay with veering away from the standard, and you're concerned about round-trips, then Option 2 is reasonable.

这篇关于在REST API设计中找到或创建成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆