Rich Apodaca Rich Apodaca - 3 months ago 11x
JSON Question

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/'.

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/', 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?


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/')]=lambda do |body|
  JSON.parse body

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