Obfuscate auto increment resource id for REST API

I’m working on building a REST API on Rails. One thing I don’t want to expose my auto increment id of resource on public API because I don’t want them to guess or know the number of resources that created on my system, and another reason which is a new app as well, so the id starts 1, 2, 3.

http://api.example.com/v1/users/1   ->   http://api.example.com/v1/users/1254125412

I’m not sure, is there any algorithm to turn “1” into unique random integer? I could go with UUID, but I prefer to use integer which is smaller indexes and faster as well.

You could hash the user with something like SHA.

1 Like

For now, I feel switching into SHA or UUI is not benefit much in my project because if I add another column to use either one of them, I have to go back to change a lot of places, so that we stop referencing id column in response and url path. But if I change id column to use UUID or SHA, I have to work hard on data migration and foreign keys and also I have to solve some third party gems that have migrations that expect relationship with my tables using integer primary key.

What I want to have is turning sequence integer id column to random unique integer column. I found something I am going to try it: Pseudo encrypt - PostgreSQL wiki. Basically, I reset my default value of id column to call this function with the value that is from sequence next_value of that table.

I know you’re reluctant to use it due to the performance loss, UUID is at least natively supported in PG and Rails 4. Given how important this piece of your system (I assume from limited knowledge) is, I think UUID is the way to go.

If you want to use the SHA, you could use a (dreaded) callback to re-hash to user data on every save. That’s one of the few scenarios where an AR callback has a nice use case.