RESTful API without ID in the URL

Alex picture Alex · Dec 30, 2013 · Viewed 12.4k times · Source

I have been discussing the best way of doing this with one of my colleagues

Here's an example scenario:

I'm trying to GET all orders for a Customer with ID of 1234.

Consider the following endpoint:

/customer/orders

With a GET request, with the following header:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

With the Authorization header, our auth mechanism identifies this request as for a Customer with ID 1234 and our service returns the required orders.

He is trying to persuade me this is right, because one logged in Customer, would only ever request their orders (in this case, the orders belonging to customer 1234) - so passing the ID in the URL is unnecessary. However.... To me, that isn't RESTful (I may be wrong)

In my opinion, it should be like this:.

/customer/1234/orders

With the header (As an example)

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

With the Authorization header, we verify the user has permission to retrieve those orders... If so, return them, else, return a 401

My question is, which is the preferred method?

I can certainly see benefits of the first way, but in the interest of keeping our api RESTful, my heart says to go with the second way...

Answer

Darrel Miller picture Darrel Miller · Dec 31, 2013

Identification of resources is a key REST constraint. Your orders and my orders are not the same resource, therefore they SHOULD (not MUST) have a different identifier.

The practical reason that you SHOULD give them a unique identifier (i.e. /customers/1234/orders) is because it will be much easier to support HTTP caching. HTTP caching intermediaries primarily use the URI as a cache key. It is possible to use other headers (like auth) as part of the cache key by using the vary header, however,the support for such mechanisms is much less reliable/widespread.

Even if today you have no plans to use HTTP caching, it is better to play safe and ensure your URIs are designed to allow this capability if you need it in the future.

When doing client side URI construction, there are some benefits to not having to include the customer ID in the URI. However, RESTful systems are supposed to provide the URIs for clients to follow by embedding those URIs in returned representations. There is no need for clients to build these URIs and therefore there is ZERO additional work for clients to use URIs with the id as using the URI without the Id. If you are prepared to swallow the hypermedia pill, then there is no advantage to not including the ID.