REST API 设计:可以在 PUT 调用期间更改资源标识符吗? [英] REST API Design : Is it ok to change the resource identifier during a PUT call?

查看:41
本文介绍了REST API 设计:可以在 PUT 调用期间更改资源标识符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想了解更多有关 PUT 调用的 RESTful 设计模式的信息.具体来说,我是否通过在 PUT 调用中更改资源 ID 来违反规范?

I'm curious to learn more about RESTful design patterns around the PUT call. Specifically, am I violating norms by changing the resource ID as part of a PUT call?

考虑以下...

POST /api/event/  { ... } - returns the resource ID (eventid) of the new event in the body
GET  /api/event/eventid
PUT  /api/event/eventid   - returns the (possibly new) resource ID depending on request body
GET  /api/event/eventid   - fails if the original eventid was used in the URI

如果 eventid 代表内部资源(如数据库记录),则 GET 和 PUT 的端点可以快速访问资源.如果 PUT 导致服务器移动底层资源,则 ID 可能会更改.

The endpoints for GET and PUT can quickly access the resource if the eventid represents internal resources (like a database record). If the PUT results in the server moving the underlying resource, the ID can change.

我这样做是否违反规范?

Am I violating norms when I do this?

推荐答案

REST 不是一个严格的规范,而是一组指导方针和最佳实践,可以遵循这些准则和最佳实践来构建易于理解和使用的 Web 服务.因此,没有什么可以阻止您在 PUT 期间更改资源 ID.

REST is not a strict specification, but more a set of guidelines and best practices that can be followed to build web-services that are easy to understand and work with. So there's nothing that prevents you from changing a resource IDs during a PUT.

话虽如此,IMO 这样做是一种不好的做法.REST 背后的想法之一是每个资源都可以使用 URI 进行引用.在您的情况下,此 URI 是路径和(我假设)内部 ID 的串联.这个 URI 可以被其他系统"使用并存储为引用.如果您更改 PUT 上资源的 ID,则会更改 URI,并且对该资源的所有引用都将被破坏 (404).

That being said, doing so is IMO a bad practice. One of the ideas behind REST is that each resource can be referenced using a URI. In your case this URI is the concatenation of the path and (I assume) an internal ID. This URI could be used by other "systems" and stored as references. If you change the ID of a resource on a PUT, you change the URI and all references to that resource will be broken (404).

如果您觉得需要更改作为 URI 一部分的 ID,您可能没有为其选择正确的属性.考虑其他不可变的东西(例如:用 UUID 标记您的资源并使用它而不是内部数据库 ID).

If you feel the need to change the ID that is part of the URI, you may not have picked the right property for it. Consider something else that would be immutable (e.g.: tag your resource with a UUID and use it rather than an internal DB ID).

这篇关于REST API 设计:可以在 PUT 调用期间更改资源标识符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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