限制对 RESTful API 中特定字段的更新
假设我有一个对象 Widget,由 Id 和 Name 组成。假设我公开了一个端点 /widget,客户端可以在其中发布新的 Widget 对象。如果我希望Id字段始终由服务器设置,客户端不可修改,但对客户端仍然可见,如何声明Id字段不可修改?如果这有什么区别的话,我正在使用 RESTeasy。
Let's say I have an object, Widget, comprised of an Id and a Name. Let's say I expose an endpoint, /widget, where clients can POST new Widget objects. If I want the Id field to always be set by the server, not modifiable by the client, but still visible to clients, how can I declare that the Id field is not modifiable? I'm using RESTeasy if that makes any difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以想到几个选择。
首先,您确定需要公开 ID 作为表示的一部分吗?或者用新发布的资源的位置进行响应就足够了吗?
您的客户发帖:
您回应:
除此之外,我认为与您的客户进行一些简单、易于理解的约定是可以的。我认为大多数开发人员都明白 ID 可能是系统生成的(特别是,因为您正在执行 POST 而不是 PUT)。对于不太明显的情况,您有任意只读字段(或其他验证或显示信息),我认为提供元数据的链接可能是有意义的:
元数据的外观取决于您,但沿着这些思路可能对你有用:
这是一种很好的、格式中立的(它适用于 XML 和 JSON)方式向客户端提供信息,如果他们真的想要,他们可以针对它进行编程来动态构建表单(我用它来提供验证信息、特定于语言的标签,以及数据类型信息)。
我希望这有帮助。
约翰
I can think of a few options.
First, are you sure you need to expose the ID as part of the representation? Or is it enough to respond with the location of the new posted resource?
Your client posts:
And you respond:
Beyond that, I think it's OK to have some simple, well-understood conventions with your clients. I think most developers understand that an ID is likely to be system-generated (especially, since you're doing a POST and not a PUT). For less obvious cases, where you have arbitrary read-only fields (or other validation or display information), I think it may make sense to provide a link to metadata:
What the metadata looks like is up to you, but something along these lines might work for you:
That's a nice, format-neutral (it works well for both XML and JSON) way to provide information to the client, and if they really want to, they can program against it to build forms on the fly (I use it to provide validation information, language-specific labels, and data type information).
I hope this helps.
John
你在服务器上编写代码,可以自由地做任何它想做的事。这包括根据需要添加或更改数据。检查 AtomPub 协议第 9.2 节,其中明确指出:
You write the code on the server that free to do whatever it wants. And that includes adding or changing data as needed. Check the AtomPub protocol section 9.2 that explicitly states: