Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resources ID in REST Api = primary key in database

Tags:

rest

mysql

I am creating a RESTful API.

My table of e.g. users has a primary key 1,2,3, ...

Now to name my resources in the API I want some more complex name. A hash of something which also will be a unique identifier but a little more difficult to guess.

Should I save this hash in an extra column in my user table or kick the 1,2,3, ... out of the primary key and use the unique hash as global id (database & API)

like image 263
almo Avatar asked Apr 16 '15 15:04

almo


2 Answers

Why the complexity?

REST API URLs are meant to be discoverable. Obfuscating the resource identifier is anything but discoverable. If you want to keep people from accessing certain data, then secure that data through authentication and authorization. If you're really creating a RESTful API, part of that is discoverability.

like image 100
George Stocker Avatar answered Sep 25 '22 07:09

George Stocker


So, from the API perspective, the only sane reason I can imagine for doing something like that is avoiding a strong coupling between the URIs and the PK. Like, for instance, you expect to change storage in the future and you don't want to be stuck with a sequential PK forever. If that's the case, I'd say to use a random UUID Version 4, store as a binary value in the database, and use the hex representation to construct the URI. That's what I did in this situation and it works fine.

Now, from the database perspective, I would recommend checking how your database deals with random values as primary key before adopting that. For instance, MySQL insert performance degrades terribly with random values in the clustered index, and it's better to have an unique index for the hash/uuid column, and an auto-increment column as PK.

Other than that, if all you want is to obfuscate the URI, I wouldn't change the database, and simply apply some reversible encoding to the integer value, to use it as part of the URI.

like image 25
Pedro Werneck Avatar answered Sep 24 '22 07:09

Pedro Werneck