Rails RestClient POST Request with 400 Bad Request Error

Looking at the docs, there are no good examples of how to make a POST request. I need to make a POST request with a parameter auth_tokenand get the answer back:

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

400 error with bad request:

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 of how to make a POST request using RestClient?

EDIT:

This is how I make a 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
+4
source share
2 answers

Try using the 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
+1
source

If you just want to replicate a curl request:

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

Both Curl and RestClient, by default, use the same content type (application / x-www-form-urlencoded) when sending data to this format.

0

Source: https://habr.com/ru/post/1627135/


All Articles