How to design REST URI for multiple Key-Value params of HTTP GET

joshi737 picture joshi737 · Dec 9, 2012 · Viewed 14.4k times · Source

I am designing a RESTful API.

One service should offer query functionality for multiple key-value pairs. For example, the client can query with one HTTP GET request for different products and the associated quantity.

The client wants to query product 1 with the amount 44 AND product 2 with the amount 55. I actually don't want my URI to look like this:

/produkt?productId1=1&productquantity1=44&productId2=2&productquantity2=55

because I don't know how many products are queried.

Or like this:

/produkt?product=1,44&product=2,55

because how can the client know that before the comma there is the productId and after the comma the quantity.

Does anyone have other solutions? Or is it not RESTful to offer the possibility to query multiple products with one request? Is it better to offer the possibility to query just one product with the associated quantity and if the client wants to query more products, they should send more requests?

Answer

Yogesh Prajapati picture Yogesh Prajapati · Dec 9, 2012

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.