英文:
RESTful API Create - should it return conflict if exist, or be idempotent and return 200 if values are the same?
问题
如果我有一个用于创建元素的端点,但元素已经存在,最佳/常见的做法是什么?
- 基于具有相同键的对象已存在的事实返回冲突?
- 或者检查现有对象是否相同,如果是,则返回200(或其他良好的状态代码)?
谢谢!
英文:
What title says - if I have an endpoint to create element, but the element already exist, what's the best / common practice? Should I:
- Return conflict based on the fact that an object with the key already exist?
- Or check if the existing object is the same, and if so return 200 instead (or other ok-ish status code)?
Thanks!
答案1
得分: 1
有关内容在RFC 9110,第13.1.1节中:
> 或者,如果请求是一个看起来已经应用到所选表示形式的状态更改操作,源服务器可以用2xx(成功)状态代码回应(即,用户代理请求的更改已经成功,但用户代理可能不知道,可能是因为之前的响应丢失了,或者其他用户代理已经做出了等效更改)。
> 当服务器操作是无操作时返回成功响应是可以的。
但您当然不需要这样做 - 向客户端发送错误响应,指示他们的本地视图已过时,也是可以的。
“最佳”做法,可以理解为,坐下来做数学运算 - 每种实施的成本是多少?它们出现的频率有多高?有哪些好处?成本的多少被推到API的消费者身上,而这是否符合我们需要达到的采用目标,等等。
英文:
There is relevant content in RFC 9110, section 13.1.1
> Alternatively, if the request is a state-changing operation that appears to have already been applied to the selected representation, the origin server MAY respond with a 2xx (Successful) status code (i.e., the change requested by the user agent has already succeeded, but the user agent might not be aware of it, perhaps because the prior response was lost or an equivalent change was made by some other user agent).
> Allowing an origin server to send a success response when a change request appears to have already been applied is more efficient for many authoring use cases, but comes with some risk
Returning a successful response when the server action was a no-op is fine.
But you certainly aren't required to do that - it's also fine to send an error response to the client indicating that their local view of the world is out of date.
"Best" practice, presumably, is to sit down and do the math - what's the cost of each implementation? how frequently does it come up? what are the benefits? How much of the cost is pushed back onto the consumers of the API, and is that consistent with the targets we need to meet to get adoption, and so on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论