Reputation: 774
I am sending HTTP POST request:
data = { id: 1, name: 'ABC' }
uri = URI.parse('http://localhost:3000/events')
http = Net::HTTP.new(uri.host, uri.port)
http.post(uri, data.to_json)
My routes file:
Rails.application.routes.draw do
post '/events' => 'receiver#create'
end
Whereas create methods looks like:
def create
package = {
id: ,
name:
}
end
How can I get access to data values passing via request? My goal is to assign it to new hash within create method
Upvotes: 5
Views: 7035
Reputation: 6545
You should set Content-Type header in your request as well:
http.post(uri, data.to_json, {"Content-Type" => "application/json", "Accept" => "application/json"})
Then you can use params[:id]
and params[:data]
in your controller.
def create
@package = {id: params.require(:id), data: params.require(:data)}
head :no_content
end
head :no_content
will render empty reply (so you can create view later). And params.require
will ensure that your parameters is provided (otherwise controller will return 400 Bad Request response) – so you won't receive some strange undefined method ... of nil
errors later in case you missed params in your request.
Upvotes: 3