Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jamesjames's avatar

is it okay to make primary key visible to public ?

I am going to build rest API. I can see that many articles and tutorials are using primary key and displaying primary key to public.

like user_id, book_id, etc

Is it okay?

0 likes
5 replies
lostdreamer_nl's avatar

why not, they'll need a way to find the entity via your API right? ie:

Route::get('users', function() {
    return User::all();
});
Route::get('users/{user}', function(User $user) {
    return $user;
});

They'll need to know what they should use to go to /users/3 . If you're afraid of people going to URLs they're not supposed to by incrementing those ID's you can do 1 of 2 things:

  1. Use GUIDs for id's so they cannot be guessed
  2. Use permissions checks to see if a user is allowed to view a specific resource (you should always do this)

The same goes for URLs: how many sites do you see where ID's are passed around in URLs, for all to see.

jamesjames's avatar

@lostdreamer_nl thanks for your reply. I just wanted to ask before start because some people mention about security reasons.

amielantonio's avatar

I don't think that exposing your primary key is a good idea. I usually add a public key or a surrogate key as my identifier. It's better in the long run most specifically when a user would often want to have their own identifiers, or you are changing your keys at times.

lostdreamer_nl's avatar

".... or you are changing your keys at times."

A good API does not change it's keys... (nice if your customers are caching your data and you suddenly change your identifiers) Unless you want to force all users of your API to update their code as well.

Always fun to see a company make the switch from integer ID's to UIDs and breaking all their customer's databases that save the key as an integer.

Most APIs I know will use GUIDs as the primary key, and communicate that with all clients. The Identifier should always be public, whether it is your DB's primary key, or just your API's identifier key does not really matter as they should both be unique.

LiamHammett's avatar

There's not really any inherent security risks if you protect your data properly.

One thing is that if you're using incrementing integers as your public key, as is default, people will be able to query /users/1 then /users/2 and so on and find out what your maximum user ID is, therefore how many users your system has. This might be an issue if you don't want this kind of statistical data to be able to go to competitors.

One solution is to use a reversible hash of the primary key for your URLs. https://github.com/balping/laravel-hashslug

Please or to participate in this conversation.