Reading data from request body

Hi Everyone,

In one of my controller actions, I am using

data_sent = ActiveSupport::JSON.decode(request.body.read)

to get the JSON object sent to this controller via request that has the object/payload inside the body. I am using curl to send/test this, as follows:

curl -X POST --header “Content-Type: application/json” --header “Accept: application/json” - -d “{“foo”: “bar”}” “http://localhost:3000/foo

The result is that I get in data_sent a Hash like this: {foo: “bar”}, which seems to be correct.

The question here is whether the way I get the data on controller is the recommended way to do it, or whether there is other more Rails/better way to do it.

Thanks in advance

Panayotis

The data is also available in params:

    params[:foo] == "bar"

The (potential) problem is that params will also contain additional fields
added by ActionDispatch: params[:controller] and params[:action], so it
won't be *only* the parsed request body.

Hmmmmm. Yes, It works indeed as you say.Thanks for that. To tell you truth, I tried that from the beginning, but it didn’t work for me. But probably was
error on the client side not sending the correct request, rather than on the server side.

Thanks a lot.

Best

Panayotis

In the future when you have a problem like that, first thing to do is log params.inspect and take a look. Maybe you'll see how the params are, and understand that you had a mistake in the way you were accessing them. If not, then log the request body, and see how RoR parses a request body into params, and understand that maybe you were expecting the wrong thing there, or if not, that the request body is not correct.

When you work with complex forms, it's not at all uncommon to not find data where you expect it in the params when you're first developing. So getting comfortable with debugging those issues is a good thing :wink: