5

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.

1
  • You can remove :via => [:post]. Other than that, it looks good. What's NOT working about it? Have you tried printing the params on the page? What do the logs look like? Commented Nov 28, 2015 at 17:27

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for pointing the documentation link, I didn't know rails automatically parsed JSON into the same params I'm already used to.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.