I’m looking for a convention on how to serialize my data when I have a (long) list of items that I want to POST to the server.
For example, if I have a resource /users and I wanted to POST a new one to it, I’d http-encode the fields for the new user and put it in the request body like this: name=foo&age=20
But if I have a list of users, like this [{ name: 'foo', age: 20 }, { name: 'bar', age: 10 }], is there a conventional way of POSTing this?
I’m thinking name[0]=foo&age[0]=20&name[1]=bar&age[1]=10 but I can’t find anything to back it up. What do web servers usually accept/expect?
Quick question which may change my answer: Are you POSTing directly from an HTML form or are you expecting something more sophisticated (e.g. javascript processsing, or not even a web-based client)
If you have a sophisticated enough client, you could just construct a JSON string and POST with a content type of
application/json. Then whatever resource is processing the POST could use any number of json libraries to read the posted string and process as is.Further Rambling:
What framework/languages are you using to construct your REST service? Do they have built-in functionality/conventions to help you?
For example if you’re using JAX-RS to build your service, there is a built in annotation @FormParam which can be used to process posted forms… for example: if you posted the following with a content type of
application/x-www-form-urlencoded:name=foo&age=20&name=bar&age=10You could retrieve parallel lists on the service side via:
But you would then have to deal with the question of what if one list is shorter/longer than the other, how do you resolve that? What happens if a new field is required or optional to create a list of users? (But as I mentioned initially, a JSON array of JSON objects would solve that issue… there are a number of libraries out there that support automagic JSON deserialization in JAX-RS or there is also the option of creating your own MessageBodyReader.
(Disclaimer on the next section: I don’t know rails, my experience is more in the Java services world… I’m basing this on this guide). It looks like Rails has a convention of
name[]=foo&name[]=barto process posted data into arrays automagically, and a similar convention to populate structure likeuser[name]=foo&user[age]=20… Perhaps if you are on rails there is some way to use/abuse both of these features to get the desired result?Other REST frameworks and languages may have their own conventions and functionality 🙂