gpt4 book ai didi

api - Rest api design : POST to create with duplicate data, would-be IntegrityError/500,什么是正确的?

转载 作者:可可西里 更新时间:2023-11-01 15:08:03 24 4
gpt4 key购买 nike

我有一个普通的、基本的 REST api,例如:

/
GET - list
POST - create

/<id>
GET - detail
PUT - replace
PATCH - patch
DELETE - delete

当 POST 进入 / 时,我通常创建一个对象并创建一个新的id。一些(一个)字段是(是)必须是唯一的。因此,具有此类重复数据的 POST 可能会导致:

  1. 500 - 完整性错误
  2. 让它更像一个PUT/PATCH/<id>并更新现有记录
  3. 捕获/避免错误并返回某种 4XX
  4. 我没有想到的其他事情。

1似乎是:请求要么不好,要么我可以处理。处理这种情况的正确方法是什么?

最佳答案

@StevenFisher 是正确的。 409 Conflict是正确的 react 。

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

例如,/上的 GET 可能会告诉客户他们可以按如下方式创建用户

HTTP/1.1 200 OK
<users href="/">
<create href="/" method="post">
<username type="xs:token" cardinality="required"/>
<password type="password" cardinality="required"/>
</create>
... other hypermedia controls, like search ...
</users>

按照超媒体控制并尝试创建用户名为“Skylar Saveland”的用户可能会导致

HTTP/1.1 409 Conflict
<users href="/">
<create href="/" method="post">
<username type="xs:token" cardinality="required"
error="The username 'Skylar Saveland' is already taken. Please select another username"/>
<password type="password" cardinality="required"/>
</create>
... other hypermedia controls, like search ...
</users>

同样,尝试创建没有密码的用户可能会导致

HTTP/1.1 409 Conflict
<users href="/">
<create href="/" method="post">
<username type="xs:token" cardinality="required"/>
<password type="password" cardinality="required"
error="A password must be specified"/>
</create>
... other hypermedia controls, like search ...
</users>

或者您可能有多个错误,例如,

HTTP/1.1 409 Conflict
<users href="/">
<create href="/" method="post">
<username type="xs:token" cardinality="required"
error="The username 'Skylar Saveland' is already taken. Please select another username"/>
<password type="password" cardinality="required"
error="A password must be specified"/>
</create>
... other hypermedia controls, like search ...
</users>

注意:适当的 media type will need to be created继续上面的内容,这将解释超媒体控件的结构(包括表单上的错误属性)并定义各种元素名称(例如,用户、用户名、密码等)的含义。

关于api - Rest api design : POST to create with duplicate data, would-be IntegrityError/500,什么是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com