How to parse json of an incoming POST request in Rails? How to parse json of an incoming POST request in Rails? ruby-on-rails ruby-on-rails

How to parse json of an incoming POST request in Rails?


When you post JSON (or XML), rails will handle all of the parsing for you, but you need to include the correct headers.

Have your app include:

Content-type: application/json

And all will be cool.


This answer may not be particular to this exact question, but I had a similar issue when setting up AWS SNS push notifications. I was unable to parse or even view the initial subscription request. Hopefully this helps someone else with a similar problem.

I found that you don't need to parse if you have a simple API setup with default format set to json, similar to below (in config/routes.rb):

 namespace :api, defaults: {format: :json}  do    namespace :v1 do      post "/controller_name" => 'controller_name#create'      get "/controller_name" => 'controller_name#index'    end  end

The important thing I discovered is that the incoming post request comes is accessible by the variable request. In order to convert this into readable JSON format, you can call the following:

request.body.read()


In most cases with the symptom desribed, the true root of the problem is the source of the incoming request: if it is sending JSON to your app, it should be sending a Content-Type header of application/json.

If you're able to modify the app sending the request, adjust that header, and Rails will parse the body as JSON, and everything will work as expected, with the parsed JSON fields appearing in your params hash.

When that is not possible (for instance when you don't control the source of the request - as in the case of receiving an Amazon SNS notification), Rails will not automatically parse the body as JSON for you, so the best you can to is read and parse it yourself, as in:

json_params = JSON.parse(request.raw_post)