REST numeric or string resource identifiers?

2019-02-22 16:02发布

问题:

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.