I thought one main characteristic and reason for using REST web services was to use path parameters rather than query parameters. But many publicly available REST web services use query parameters.
Am I wrong in thinking that query parameters are not supposed to be used in REST web services? Is there a recommendation or rule about not using query parameters in REST web services?
The query string can still be used in REST web services just not in the same way as normal.
You have to think of the URL as the key to a resource. The URL is an unique identifier for the resource. For example
http://example.com/products/123 -- where 123 is the id of the products.
Accessing to /products
would return a full list of products. Adding the id would return a specific product.
What if you want to order product in a specific way? Some would say
http://example.com/products/united-states
Well, now there is some ambiguity at the first look. Is united-states an id? Well that ambiguity can be solved by saying an id is represented as \d+
. Correct.
Ok so our first parameters which is made of words is a country.
Now lets say we want to add more filters, lets try and add more slashes.
http://example.com/products/united-states/home/asc
But I don't want united states products only! But still want home products.
http://example.com/products/home/asc
Wait... is home a country? I'm not sure now, it's kind of ambiguous... And what if I want to add another filter tomorrow? What will I do... add more slashes?
The URL becomes cluttered and full of ambiguous parameters that were optional at first and that become obligatory because of ambiguity.
The correct way, to me, would be to use the query string for thing specific about the query. Because, I can sort the query in any way I want, it is still the same query. I query products.
So the form should be like
http://example.com/products -- all products
http://example.com/products/{id} -- specific one
http://example.com/products/?country=united-sites -- filtered
This way you can add new filters anytime you want and keep URLs that are clear and won't ever break even though you change the filters.
If you want more information I really, really advise you to look at this conference by David Zülke, a guy working for the Symfony framework. He talks about a lot of things of REST web-services, but he also talk specifically about URLs, and how to build them (Mainly from 16 to 30 minutes).
You can also look at apigee website. They have a lot of videos (and books) about REST. More specifically this video, which is really on topic here.