Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a REST API select on a ID or a name field? [closed]

Tags:

rest

web

api

I'm designing a REST API and trying to decide which is the more correct way of returning a single resource:

/resource/{id}

or

/resource/{name}

The ID would be immutable, so I'm thinking that it would be better to select by it, but name would be more friendly looking. What is the best practice? I've seen both used before "in the wild".

like image 414
Brian P. Hamachek Avatar asked Jul 19 '15 21:07

Brian P. Hamachek


4 Answers

Basically REST is built on top of unique IDs, thus:

GET    /resources/{id}/

should be used. However, there's nothing that prevents you from making name field unique (now it behaves as plain old ID) and build REST on top of this unique ID.

If this is not what you need and name cannot be made unique, then another option is to implement filtering via name:

GET    /resources?name=<SOME_NAME>

It also should be resources (plural) since it indicates that there's a collection under the hood.

like image 167
Opal Avatar answered Nov 19 '22 19:11

Opal


Whether using name instead is practical comes down to your business case.

Will 'name' always be unique? Or will the application deal with there being more than one occurrence?

Are 'pretty' URLs important? In most applications I've worked on, querying uses unique IDs which are never exposed to the end-user, as they have no business meaning whatsoever. They are in effect surrogate primary keys.

like image 34
morsor Avatar answered Nov 19 '22 19:11

morsor


/resource/{id} is more technically correct, but if it were me, I'd allow both. Assuming names can't contain ONLY numbers, and ids can ONLY be numbers, you could easily detect which was supplied and allow for either to be used. ;)

like image 29
Ben Fried Avatar answered Nov 19 '22 19:11

Ben Fried


This is good question .. it depends on business case example if api is used through cli like docker then you might want to use user friendly ids like name But as soon as it become part of URL it has limitations like ASCII (to avoid url encoding or loss of readability ) char only and some defined length like 128 chars etc.

like image 27
Neel Salpe Avatar answered Nov 19 '22 18:11

Neel Salpe