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".
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.
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.
/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. ;)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With