Rails RestClient POST request failing with “400 Bad Request”

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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 

回答1:

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 


回答2:

If you just want to replicate the curl request:

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

Both Curl and RestClient defaults to the same content type (application/x-www-form-urlencoded) when posting data the this format.



回答3:

In case you land here having the same Issue, Just know that this is a common error that happens when your environment variables are not "set".
I put this in quotes because you might have set it but not available in the current terminal session! You can check if the ENV KEY is available with:

printenv <yourenvkey>

if you get nothing then it means you need to re-add it or just put it in your bash files

FYI: Putting my ENV variables in my ~/.bash_profile fixed it



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!