How to design REST URI for multiple Key-Value params of HTTP GET
Here is one idea to pass a parameter:
/products?productDetail=[{"key":"key0","value":"key1"},{"key":"key2","value":"key2"},{"key":"key3","value":"key3"}]
where
[{"key":"key0","value":"key1"},{"key":"key2","value":"key2"},{"key":"key3","value":"key3"}]
is a JSON representation of the List<kv>
class
class kv {
String key;
String value;
public kv(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
so you can easily convert query parameter productDetail
in to List<kv>
using
new Gson().fromJson(productDetail,kv.class);
than you can easily iterate all elements.
Another suggestion is, if you don't know how many products are queried then use a POST
request for this.
I would expand upon your second suggestion a little by adding explicit names for the parts of your product, and using semicolons in place of commas to separate product attributes, since the order does not matter*.
/products?id=1;qty=44&qty=55;id=2
Note how id
and qty
are switched around for the second product, because the order of attributes does not matter.
* There is a convention to use commas when the order is important, and semicolons when the order is not important.