POST a list of items using REST

前端 未结 2 790
孤独总比滥情好
孤独总比滥情好 2021-01-12 05:10

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

2条回答
  •  终归单人心
    2021-01-12 05:32

    Rails serializes forms on a format not unlike what you suggest. If you have a nested model it encodes it like this:

    name=theo&company[name]=acme
    

    (the equivalent JSON would be {"name": "theo", "company": {"name": "acme"}})

    I can't say that I've seen a Rails application sending arrays, but there's no reason why it wouldn't work (worst case you would end up with a hash with string keys).

    PHP has another convention, if you want to send an array you do

    names[]=alice&names[]=bob&names[]=steve
    

    But I don't know how you do nested objects that way.

    The HTTP spec, or if it's the URI spec, not sure which atm, actually specifies that if you pass the same argument multiple times you get array of values (instead of the last-wins behaviour of most application frameworks). You can see this in the API docs for Jetty, for example: http://api.dpml.net/org/mortbay/jetty/6.1.5/org/mortbay/jetty/Request.html#getParameterValues(java.lang.String)

    However, most of this applies to GET requests, not necessarily POST (but perhaps application/x-url-encoded should adhere to the same standards as GET).

    In short, I don't think there is a standard for doing this, POST bodies are a bit of a wild west territory. I think, however, that either you should go with JSON, because it's made to describe structures, and application/x-url-encoded is not, or you should try to represent the structure of your data better, something like:

    users[0][name]=foo&users[0][age]=20&users[1][name]=bar&users[1][age]=10
    

    That has some kind of chance of actually being interpretable by a Rails app out of the box, for example.

提交回复
热议问题