REST numeric or string resource identifiers?

ぐ巨炮叔叔 提交于 2019-12-19 18:27:10

问题


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

Or using a string identifier?

/users/RSmith

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.

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?


回答1:


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.

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. You have to restrict access to URLs based on any authentication method, or:
  2. You have to use randomized/unguessable URLs that are not "public".

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.




回答2:


Only advantage of this: /users/RSmith is that it's more human friendly. From RESTfull perspective it doesn't matter because both are valid resource identifiers. Everything else depends on your system requrements.



来源:https://stackoverflow.com/questions/10903636/rest-numeric-or-string-resource-identifiers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!