简体   繁体   中英

Web API Design: Form POST'ing key-value pairs: JSON or checkbox style?

Design question for RESTful APIs: one of the input parameters to my API (that is, the data sent from the client to my API) is a dictionary (hash / key-value pairs). What's the best way to encode this so that the API can be easily invoked from web pages as well as scripts/programming languages?

My first thought was to json encode the object, something like this:

var data = {a:'one', b:'two'};
form_paramter_x = JSON.stringify(data);

and decode on the server:

data = simplejson.loads( request.POST['form_paramter_x'] )

The alternative would be to encode as key-value pairs html-form-checkbox style:

form_param_x=a:one&form_param_x=b:two

The latter alternative would require ad-hoc parsing of the key and value (the "a:one" part), and generally seems less clean, but also seems closer to a basic HTML form, which is probably a good thing.

Which of these is cleaner? Or is there another better alternative?

If you're designing your API for other parties to use, I'd consider what is going to be easiest for them to encode for. JSON is widely supported these days, so that isn't a deal breaker. In the end, I'd go w/ whichever is easier for your clients to code. Emotionally, I'm leaning towards the JSON encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM