How to design REST URI for multiple Key-Value para

2019-04-23 11:31发布

问题:

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?

回答1:

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.



回答2:

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.