Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails RestClient POST request failing with "400 Bad Request"

Looking at the docs there aren't any good examples of how to make a POST request. I need to make a POST request with a auth_token parameter and get a response back:

response = RestClient::Request.execute(method: :post,
                        url: 'http://api.example.com/starthere',
                        payload: '{"auth_token" : "my_token"}',
                        headers: {"Content-Type" => "text/plain"}
                       )

400 bad request error:

RestClient::BadRequest: 400 Bad Request
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:74:in `return!'
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/restclient/request.rb:495:in `process_result'
    from /Users/me/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rest-client-1.8.0/lib/me/request.rb:421:in `block in transmit'

Any good examples how to make a POST request using RestClient?

EDIT:

This is how I make the request in the model:

  def start
    response = RestClient::Request.execute(method: :post,
                        url: 'http://api.example.com/starthere',
                        payload: '{"auth_token" : "my_token"}',
                        headers: {"Content-Type" => "text/plain"}
                       )
    puts response

  end
like image 491
Tom Avatar asked Feb 03 '16 11:02

Tom


1 Answers

Try using a hash like this:

def start
   url= 'http://api.example.com/starthere'
   params = {auth_token: 'my_token'}.to_json
   response = RestClient.post url, params
   puts response
end
like image 65
zlwaterfield Avatar answered Oct 05 '22 23:10

zlwaterfield