Accepting JSON in requests

Allright, we've been going back and forth on
http://dev.rubyonrails.org/ticket/9935, and I'd like to get some more
comments, primarily from folks using or implementing JSON rest APIs.
I personally haven't, because I tend to get a lot of pushback from
other JSON fans regarding things like this, date formats, etc.

The goal with the Rails param parsers is to allow the same controller
code to work with multiple formats (html forms, xml, json, yaml, etc).
Also, going with REST best practices would be nice too. This
question is what kept me from implementing this months ago, actually.

Looking at the back-and-forth, I have to see I don't see why the
bother for all the complexities.

The Rails way indicates that we go for the simpler solution. In this
case I'd have to say requiring the JSON item posted in to be an
object, not an array, at the outermost level, is clearly the simplest
option.

It allows the JSON to be parsed into the params hash in just the same
way as XML and HTML forms.

JSON is a flexible format with lots of exciting work being done around
it these days, but just as Rails is opinionated about the XML it will
automagically turn into a params hash, it should be picky about the
JSON it will automagically convert, especially if being picky allows
for a much simpler developer API.

None of this should stop someone from getting at the raw post body and
deserializing it themselves if they are inclined. If we can make it
easy for developers access the raw JSON, it should be provided in a
parallel fashion as accessing the raw XML or forms data.

Chris

The last patch submitted against the ticket allows you to do this:

def show

respond_to do |format|
format.xml { render :xml=>@item }

format.json { render :json=>@item }

end

end

def update

@item.update_attributes! params[:item]

end

It works for both XML and JSON (also HTML forms, not shown here), and you can feed update the same result you got from the previous
show, retaining the PUT-what-you-GET.

Assaf

The last patch submitted against the ticket allows you to do this:

It just doesn't feel right to me to depend on your controller name for
this.

Let's try this as a plugin for now and give it a chance to live in the
wild. If this works out for folks writing JSON APIs, we can look at
including it in a future version. I'd hate to push it off, but this
was brought up so late in the cycle so there's not much time to try it
out.

Bringing this back, I turned the patch into a plugin that you can try out:

http://labnotes.org/svn/public/ruby/rails_plugins/json_request

A bit more on what it does and make sure it uses the right parameter name:
http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/

Assaf