Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails controller accept json POST request

How can I set up my rails project to accept a json HTTP POST request? I'm a beginner to rails and have tried different things but cant capture any data. So far this is my controller method.

def flowplayer_callback
    pars = params[:video]
end

I have this in my routes.rb file:

post "flowplayer_callback" => "videos#flowplayer_callback", :via => [ :post]

Incoming json will look similar to this:

{"video": { "id": 85067, "seconds": 48, "failed": 0, "encodings": [{ "id": 263445, "duration": 23 }, { "id": 263446, "duration": 23 }] }

Edit: My issue was with devise gem trying to authenticate user in the before action.

like image 827
tet5uo Avatar asked Nov 28 '15 17:11

tet5uo


2 Answers

If the Content-Type header of your request is set to application/json, Rails will automatically load your parameters into the params hash. Read a bit more about this here:

http://edgeguides.rubyonrails.org/action_controller_overview.html#json-parameters

Additionally, unless you've disabled it, you'll have Strong Parameters blocking anything you haven't permitted.

You should permit the things you're willing to accept in your controller action (or set up a private method if you need to permit them in more than one place, such as create and update methods):

def flowplayer_callback
  pars = params.require(:video).permit(:id, :seconds, encodings: [:id, :duration])
end

I'm not sure what's going on with your :failed section of data as your hash is somewhat broken. But, you should get the idea for what you need to do.

Read more about Strong Parameters here - http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

like image 175
Jon Avatar answered Oct 08 '22 07:10

Jon


It could be that you need to set the correct headers before making your post request, in order for rails controller to accept a json response.

Content-Type: application/json
Accept: application/json

This SO response has some more details https://stackoverflow.com/a/4914925

like image 35
OscuroAA Avatar answered Oct 08 '22 09:10

OscuroAA