由于现有匹配资源,资源创建 POST 失败时的 HTTP 响应代码

编程入门 行业动态 更新时间:2024-10-28 15:20:55
本文介绍了由于现有匹配资源,资源创建 POST 失败时的 HTTP 响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

www.example/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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 10:17:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/936284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源   代码   POST   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!