Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON Payload in Rails When Using Custom MIME Type

A Rails application with a RESTful interface needs to accept POST data using a custom MIME type based on 'application/json'. Let's call that MIME type 'application/vnd.com.example.Foo+json'.

Registering the custom MIME type in Rails using Mime::Type.register works fine in that the application recognizes the MIME type given in the "Accept:" header and renders a JSON view through respond_to.

The problem is with controller methods such as update and create that need to convert custom JSON formatted data into a params hash. If I set the "Content Type:" header to application/json, the data gets parsed into the params hash.

But if I set the "Content Type:" header to 'applcation/vnd.com.example.Foo+json', then the payload does not get parsed.

So it seems like MIME::Type.register is used for driving the respond_to block, but not in deciding how to parse payloads for create and update methods.

Any ideas?

like image 770
Rich Apodaca Avatar asked Jul 31 '09 21:07

Rich Apodaca


1 Answers

For those who may be interested, I found the answer to my own question.

Use something like this in mime_types.rb (or possibly elsewhere in your your initialization sequence):

ActionController::Base.param_parsers[Mime::Type.lookup('application/vnd.com.example.foo+json')]=lambda do |body|
  JSON.parse body
end

One catch: don't use capitalization in the MIME type above (i.e., 'application/vnd.com.example.Foo+json'). Rails converts the MIME type into all lower case, so no match will be found it it's set to upper case.

like image 131
Rich Apodaca Avatar answered Oct 05 '22 22:10

Rich Apodaca