-1

After going through several posts on StackOverflow, I still do not quite understand whether using query parameter in URL is regarded as RESTFUL or not. For example, given an address http://www.example.com/product.php?productID=123. Is it a RESTFUL design? My intuition says it is because it is equivalent to sending a HTTP GET request to the server to fetch the corresponding data from the database.

If it is a RESTFUL design, my second question is that we can only achieve HTTP GET if we only use this "query argument" style? For instance, We can never do a HTTP POST request by using URL with the query argument ?productID=123, right? Thanks.

jackycflau
  • 1,101
  • 1
  • 13
  • 33

2 Answers2

0

a) You can use query parameters. You can use path segments. Or you can use both. Your choice.

b) And yes, you can POST to URIs with query parameters.

Julian Reschke
  • 40,156
  • 8
  • 95
  • 98
0

Path params and query params should be used in different scenarios:

Path params:

You should use it when you are trying to access a resource by ID. For instance

example/products/123456

Above you are getting the product with id 123456.

If you have a subresource, for instance:

example/products/123456/comments/1324

Above you are getting the comment with id 1324 into product with id 123456.

Query params:

You should use it when you are trying to query a resource using filters different to ID. For instance:

example/products?kind=food

Above you are getting all the products that they are of kind food.

If you have more filters like:

example/products?kind=food&priceLessThan=1200

Above you are getting all the products that they are of kind food and price is less than 1200. You should take into account that the query params are not necessary matching the fields into product resource, in this case, price is the field into product, not priceLessThan, this name is only logic to filter the resource.

Besides, you can sort and pagining like this:

example/products?kind=food&priceLessThan=1200&sortBy=name&page=10

As you can see, query params are more flexible, therefore, we should use those for filtering.

POST with Query Params:

You can use it, but, it should be strange. POST method is used to create new resources and into the Request Body you can put all the information you need to create it like a JSON or XML.

I you need some metadata when you create a resource, I suggest using a Request Header.