REST numeric or string resource identifiers?

I am doing some research to help me develop a REST API, and this is one of the topics that I have not seen anywhere in more detail.

If I have a user in the system, is it better to identify the user with a numerical identifier

/ users / 1

Or using a string identifier?

/ users / rsmith

I see hypothetical potential pros and cons of each approach, string identifiers are more readable for a person, less accessible for searching (cannot be increased to search for real users) and do not require storing another numerical identifier in the database (I would not want to expose database identifiers through the API). Numeric identifiers do not have an inherent meaning and, therefore, can be guaranteed unchanged, while with a string identifier a user may want to rename a resource, thereby changing the resource URI.

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

+4
source share
2 answers

As you know, strictly speaking, there is no advantage between both approaches. Yes, string identifiers may be easier to remember, but apart from this, REST does not use โ€œprettyโ€ URLs (or identifiers), since most URLs refer to programs that follow hyperlinks.

Therefore, human-friendly URLs should only be used to download resources that people can remember. Also, guessing the ID should not be a problem, because either:

  • You must restrict access to URLs based on any authentication method or:
  • You must use randomized / unrecognized URLs that are not "public".

So which one to use? In most cases, this does not matter, since identifiers are not directly accessible. If for some reason you need to remember your URLs, try to make them convenient for people, but try to avoid changing the name of the resource and use other authentication methods so that even guessed URLs do not gain access to unauthorized places.

+2
source

The only advantage of this: / users / RSmith is that it is more human friendly. From a RESTfull point of view, this does not matter, because both are valid resource identifiers. Everything else depends on your system requirements.

+1
source

Source: https://habr.com/ru/post/1416225/


All Articles