Should RESTful URIs expose database primary keys? Should RESTful URIs expose database primary keys? database database

Should RESTful URIs expose database primary keys?


I would expect the id to be the primary key as that is how you would identify the record. If you want, and you have one, you could use a natural primary key e.g. someone's employee id rather than an identity which is a surrogate key.

If your issue is that is is an integer rather than it being the database primary key (and hence I suppose guessable) you could use a GUID instead. They can be generated on either the client, or server side either in the application or in the DB.

They would help with database merges etc. and they are guaranteed unique.


If you design your RESTful API correctly, the choice of numbering scheme for IDs becomes opaque and irrelevant to your API's consumers.

Applications coded against your API will navigate around it using hyperlinks within your representations, as long as they don't attempt URI construction. Applying the principles of HATEOAS allows you to use database keys as your resource IDs without worry.


Generally, it doesn't matter.

But you should always be returning an href as your unique identifier to the consumer, not just an ID. If you just return an ID, that means they have to know where the resource lives and combine that information with the ID to make a unique request for the resource. Returning the href for them eliminates coupling.