Multiple key / value pairs in HTTP POST, where the key has the same name

I am working on an API that accepts data from remote clients, some of which, where the HTTP POST key works almost like an array. In English, this means that I have a resource on my server called "class". A class in this sense is the type in which the student sits and the teacher learns. When a user sends an HTTP POST to create a new class for their application, many key value pairs look like this:

student name: Bob Smith
student_name: Jane Smith
student_name: Chris Smith

What is the best way to handle this on the client side (say, the client is cURL or ActiveResource, regardless of ..) and what is a decent way to handle this on the server side if my server is a Ruby on Rails application? We need a way to allow the use of multiple keys with the same name and without any namespace conflicts or data loss.

My requirement should be for POST data to represent urlencoded key / value pairs.

+7
rest ruby ruby-on-rails activeresource
source share
2 answers

There are two ways to deal with this, and it will depend on your client architecture, how you do it, since HTTP standards do not make the situation cut and dry.

Traditionally, HTTP requests simply use the same key for duplicate values ​​and leave it to the client architecture to understand what is happening. For example, you might have a mail request with the following values:

student_name=Bob+Smith&student_name=Jane+Smith&student_name=Chris+Smith 

When the receiving architecture received this string, it would have to understand that there are several student_name keys and act accordingly. It is usually implemented so that if you have one key, a scalar value is created, and if you have a multiplicity of the same key, the values ​​are placed in an array.

Modern client-side architectures such as PHP and Rails use a different syntax. Any key that you want to read as an array is added in square brackets, for example:

 student_name[]=Bob+Smith&student_name[]=Jane+Smith&student_name[]=Chris+Smith 

The receiving architecture will create an array structure named hostname without parentheses. The square bracket syntax solves the problem of the inability to send an array with only one value, which cannot be processed using the "traditional" method.

Since you are using Rails, square bracket syntax is the way to go. If you think you can switch server architectures or want to distribute your code, you can explore more agnostic methods, such as JSON encoding of the sent string, which adds overhead, but it can be useful if this is a situation that you expect to have to handle.

There is a great post in the context of jQuery Ajax Options here .

+20
source

Send your data in XML or JSON format and analyze everything you need.

0
source

All Articles