Besi
Besi

Reputation: 22949

POST Params aren't passed to controller on API Request

When I post to my resource via CURL in my Rails 3 application then the parameters aren't passed all the way to the controller.

So when I post {"favorite_user": {"username": "someuser"}} I end up with the following params:

{"format"=>:json, "action"=>"create", "controller"=>"v1/favorite_users"}

This is my POST Request:

POST /api/favorite_users HTTP/1.1
User-Agent: curl/7.30.0
Host: myapp.com
Content-Type: application/myapp.com; version=1
Accept: application/myapp.com; version=1
Content-Length: 48

{"favorite_user": {"username": "someuser"}}

My routes.rb:

scope 'api', as: 'api' do
  api_version(module: 'V1',
              header: {name: 'Accept', value: 'application/myapp.com; version=1'},
              defaults: {format: :json}) do
    resources :favorite_users, only: [:index, :show, :create]
  end
end

rake routes yields this:

api_favorite_users GET    /api/favorite_users(.:format)                                        V1/favorite_users#index {:format=>:json}
                   POST   /api/favorite_users(.:format)                                        V1/favorite_users#create {:format=>:json}
 api_favorite_user GET    /api/favorite_users/:id(.:format)                                    V1/favorite_users#show {:format=>:json}

My controller:

class V1::FavoriteUsersController < V1::BaseController

  # ...

  def create
    render text: params.to_s
  end

end

Upvotes: 1

Views: 186

Answers (1)

neill
neill

Reputation: 90

Assuming that you are using the Versionist gem for versioning your API, you need to change the Content-Type header to something that Rails will understand. Your data is JSON, so the header should be Content-Type: application/json. Versionist doesn't tell Rails how to interpret and decode incoming request bodies with the custom Content-Type, it only looks at the Accept header value for a matching type.

Upvotes: 1

Related Questions