7

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".

Opal
  • 81,889
  • 28
  • 189
  • 210

4 Answers4

9

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.

Opal
  • 81,889
  • 28
  • 189
  • 210
  • Thanks, we went with your suggestion of selecting on id and allowing filtering by name. – Brian P. Hamachek Jul 20 '15 at 15:25
  • 1
    You should always prefer a synthetic key. If you used the name as a unique ID, you are imposing constraints on future revisions to your API - you would never be able to make them non-unique, and you'd need to start returning 301s, which might be a performance hit for clients. – Eric Stein Jul 20 '15 at 15:46
  • That's a very reasonable advice. – Opal Jul 20 '15 at 15:47
  • Is it safe to make the id visible to the frontend? – Mon Mar 17 '20 at 06:03
  • Well, it depends. Basically you need to expose some identity descriptor to the frontend to allow it to reliably interact with your server. But it doesn't need to be a DB ID. you may generate w hash that will be describing uniquely the resource you return. – Opal Mar 17 '20 at 09:11
2

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.

morsor
  • 1,263
  • 14
  • 29
1

/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. ;)

Ben Fried
  • 2,168
  • 1
  • 14
  • 13
1

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.

Neel Salpe
  • 1,287
  • 3
  • 15
  • 26