REST数字或字符串资源标识符? [英] REST numeric or string resource identifiers?

查看:63
本文介绍了REST数字或字符串资源标识符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些研究以帮助我开发REST API,这是我在任何地方都没有深入讨论过的主题.

I'm doing some research to help me develop a REST API and this is one topic I haven't seen discussed in depth anywhere.

如果我在系统中有一个用户,最好使用数字标识符来识别用户

If I have a user in the system, is it better to identify the user using a numeric identifier

/users/1

/users/1

还是使用字符串标识符?

Or using a string identifier?

/users/RSmith

/users/RSmith

我可以看到每种方法的潜在优点和缺点,字符串标识符更易于阅读,更难以发现(无法递增以找到有效的用户),并且不需要在数据库中存储另一个数字id(I不想通过API公开数据库ID).数字标识符没有固有的含义,因此可以保证它是不可变的,而使用字符串ID的用户可能希望重命名资源,从而更改资源URI.

I can see hypothetical potential pros and cons to each approach, string identifiers are more human readable, less discoverable (can't be incremented to find valid users), and don't require storing another numeric id in the database (I wouldn't want to expose database ids through the API). Numeric identifiers have no inherent meaning and due to that, can be guaranteed to be immutable, whereas with a string id the user might want to rename the resource, thus changing the resource URI.

这里是否有REST最佳实践,或者最佳方法是否因系统而异?如果是后者,则每种方法还有其他优点和缺点吗?

Is there a REST best practice here or does the best approach vary to system to system? If the latter, are there any additional pros and cons associated with each method?

推荐答案

严格来说,您知道两种方法之间没有优势.是的,字符串标识可能使人们更容易记住,但是除此之外,REST并不强制使用漂亮的" URL(或ID),因为大多数时间URL都是由超链接之后的程序访问的.

As you know, strictly speaking, there is no advantage between both approaches. Yes, string identifies may be easier for people to remember, but apart from that, REST does not enforce "pretty" URLs (or IDs), because most of the time URLs are accessed by programs following the hyperlinks.

因此,人类友好的URL仅应用于引导人类可能会记住的资源.此外,ID猜测也不应该成为问题,因为:

Thus, human friendly URLs should only be used for bootstrapping resources that may be remembered by humans. Also, ID guessing should not be a problem because either:

  1. 您必须基于任何身份验证方法来限制对URL的访问,或者:
  2. 您必须使用非公开"的随机/不可用网址.

那要用哪一个呢?在大多数情况下,这并不重要,因为不会直接访问ID.如果您必须确保人们出于某种原因记得他们的URL,请尝试使它们对人类友好,但请尝试避免更改资源名称,并应用其他身份验证方法,以使即使猜测的URL也无法访问未经授权的位置.

So which one to use? Most of the time, it does not matter, as IDs are not accessed directly. If you have to ensure people remember their URLs for some reason, try to do them human-friendly, but try to avoid resource-name change and apply some other means of authentication so that even guessed URLs don't get access to unauthorized places.

这篇关于REST数字或字符串资源标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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