Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following problem. A web service is sending a JSON POST request to my app and I want to parse it.

I thought I just can access the params with

@var = params[:name_of_the_JSON_fields]

but it doesn't work. I see in my Heroku logs, that the request is done and that the parameters are there, but I just can't store them.

Does anyone have an idea?

like image 483
thomas8877 Avatar asked Dec 05 '10 17:12

thomas8877


3 Answers

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.

like image 199
Jesse Wolgamott Avatar answered Nov 13 '22 18:11

Jesse Wolgamott


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()
like image 25
Matte3o Avatar answered Nov 13 '22 18:11

Matte3o


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)
like image 13
mltsy Avatar answered Nov 13 '22 18:11

mltsy