resthttpuriapi-design

How to access a Subresource in a REST API without using the unique identifier?


I need to access a sub-resource of a resource without using the real unique identifier of that resource.

As far as I understood, you use Path-Variables for unique identifiers and Request-Params for filtering.

If I would use the unique identifier, the URI could look as follows:

/cars/47/engine/name

However if I want to obtain the name of the engine of a car by the color of the car, I am not sure how to do is. Since color would be a filter, the query would have to look something like this:

/cars?color=red/engine/name

But this looks kind of odd to me or is this actually the conventional way of doing it?

And furthermore, how would I use multiple properties of a resource as the unique identifier? Imagine I have an application where I could identify a person by it's firstname, sirname and the country that person was born in. Would I chain them together like that:

/persons/JoeWatsonSpain

Or wouldn't I be able to use it as a real unique identifier and do filter logic instead?

/persons?firstname=Joe&sirname=watson&country=spain

Solution

  • "But this looks kind of odd to me (/cars?color=red/engine/name) or is this actually the conventional way of doing it?"

    No. This API design is incorrect. According to RFC3986:

    The query component is indicated by the first question mark ("?") character and terminated by a number sign ("#") character or by the end of the URI.

    Thus, you can't use query (or previous term in RFC1738, "searchpart") and end it with /.

    The more appropriate way would be like:

    /cars/engine/name?carColor=red
    

    "How would I use multiple properties of a resource as the unique identifier?"

    There are 2 options (maybe more):

    1. "Chain them together", with your own separate rule. Such as: /persons/Joe_SP_Watson_SP_Spain
    2. Use query as you mentioned. Such as /persons?firstname=Joe&sirname=watson&country=spain

    Personally, I prefer the second solution, which is easier to understand and easier to maintain.