由于现有匹配资源,资源创建 POST 失败时的 HTTP 响应代码 [英] HTTP response code when resource creation POST fails due to existing matching resource

查看:23
本文介绍了由于现有匹配资源,资源创建 POST 失败时的 HTTP 响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我们有一个 API,可以通过 POST 来创建一个新员工

Imagine we have an API where a new Employee can be created through a POST to

www.example.com/api/employees

员工可以描述为,

{
  name: "John Smith",
  tax_number: "ABC123"
}

税号对所有人来说都是独一无二的.如果进行了创建,并且已经存在姓名和税号与现有记录匹配的记录,则可以安全地假设请求者希望返回对该记录的引用(使用它的内部 ID 和其他数据,客户端可能不会已经,例如,创建于,更新于).

The tax number is universally unique for all humans. If a create were made, and a record already existed in which the name and tax number matched an existing record, it is safe to assume the requester would like a reference to that record returned (with it's internal id and other data the client may not have, eg. created at, updated at).

返回该资源的 HTTP 状态代码是什么?我想重定向可以仅返回 id,但我更愿意将整个对象包含在响应中.

What would the HTTP status code be for returning that resource? I suppose a redirect could be used with a return of just the id, but I'd prefer to enclose the entire object in the response.

这种情况是简单重复错误所独有的,从某种意义上说,如果尝试重复,则意味着您希望创建的记录已经存在 - 而不是它与现有记录冲突.

This case is unique to a simple duplicate error, in the sense that if a duplication is attempted it means the record you wish to create already exists- as opposed to it conflicting with an existing record.

推荐答案

我认为如果您将资源发布到 API,您会期望代码 201 表明该资源已创建,并且主体将(可以)包含资源.否则你首先必须检查资源是否已经创建,但这需要两次调用.

I think if you Post a resource to an API, you expect a code 201 that will state that the resource was created, and the body will (can) contain the resource. Otherwise you first have to check if the resource is already created, but this will need two calls.

否则,您的状态代码为 409 :

otherwise, you have the status code 409 :

由于与资源的当前状态冲突,请求无法完成.

The request could not be completed due to a conflict with the current state of the resource.

在阅读了来自 amundsen、Ruby 和 Richardson 的 Restfull Web Apis 之后

after reading on Restfull Web Apis from amundsen, Ruby and Richardson

最好使用 409 状态代码,表明与服务器上存在的资源存在冲突.将那个冲突"资源的 url 放在响应的 Location Header 中,并在正文中添加一条冲突消息

Best would be to use the 409 status code that states that there is a conflict with a resource that exists on the server. Put the url of that "conflicted" resource in the Location Header of the response and add a message of the conflict in the body

这篇关于由于现有匹配资源,资源创建 POST 失败时的 HTTP 响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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