How to send data in a post request with RestClient - ruby-on-rails

I'm trying to mimic a curl request using the RestClient Ruby gem, and so far, I've been having a lot of trouble trying to send in a payload. My curl request looks something like this
curl URL -X POST -u API_KEY -d '{"param_1": "1"}'
I've been trying to replicate this with RestClient using something like this:
RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: {"param_1" => "1"})
Alas, I keep getting 400 - Bad Requests errors when doing this. Am I sending data over the wrong way? Should I be using something other than payload?

Change:
payload: {"param_1" => "1"})
To:
payload: '{"param_1": "1"})'
Also, specify the headers.
So, it becomes:
RestClient::Request.execute(method: :post,
url: 'your_url',
user: 'API_KEY',
payload: '{"param_1": "1"}',
headers: {"Content-Type" => "application/json"}
)

Just Change:
payload: {"param_1" => "1"}
To:
payload: {"param_1" => "1"}.to_json
So, then it becomes:
RestClient::Request.execute(method: :post,
url: 'your_url',
user: 'API_KEY',
payload: {"param_1" => "1"}.to_json,
headers: {"Content-Type" => "application/json"}
)

Turns out I had to add an argument to specify that my data was in a JSON format. The correct answer was something like this:
RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: '{"param_1": "1"}', headers: {"Content-Type" => "application/json"})

Related

Ruby Rest client POST, how to send headers

Ruby rest client is not able to send headers, my java service is not able to read headers when I trigger post request from ruby as below. My Service layers throws error Header companyID is missing. When run the same http request in Postman it works.
response = RestClient::Request.new({
method: :post,
url: 'https://example.com/submitForm',
headers:{content_type: 'application/x-www-form-urlencoded',
companyID:'Company1',
Authorization:'Basic HELLO1234'},
payload: { data: str_res}
}).execute do |response, request, result|
case response.code
when 400
[ :error, JSON.parse(response.to_str) ]
when 200
[ :success, JSON.parse(response.to_str) ]
puts request.headers
else
fail "Invalid response #{response.to_str} received."
end
end
Here is postman code that works. Need similar in Ruby Rest, pls advise.
POST /submitForm HTTP/1.1
Host: example.com
companyID: Company1
Authorization: Basic HELLO1234
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 528cafa1-2b5d-13a1-f227-bfe0171a9437
data=My Own data
Below worked. Looks like headers should be in same line.
payloadString = "data=My Own data"
response = RestClient::Request.new({
method: :post,
url: 'https://example.com/submitForm',
payload: payloadString,
headers: {content_type: 'application/x-www-form-urlencoded', companyID:'Company1', Authorization:'Basic HELLO1234'}
}).execute do |response, request, result|
case response.code
when 400
[ :error, JSON.parse(response.to_str) ]
when 200
[ :success, JSON.parse(response.to_str) ]
else
fail "Invalid response #{response.to_str} received."
end
end
Try using the RestClient post method:
result = RestClient.post(
'https://example.com/submitForm',
payload,
{
content_type: 'application/x-www-form-urlencoded',
companyID: 'Company1',
Authorization: 'Basic HELLO1234'
}
)
Payload in this instance is a string, so you'll need to figure out the appropriate structure for application/x-www-form-urlencoded. For example:
payload.to_json => '{"data": "str_res"}'

Rails, RestClient pass binary font file

I'm trying to use restclient to do this CURL post
curl -v -i -X POST -H 'X-Api-Secret: ' -F font=#myraid.ttf APIURL
This is what I have so far
response = RestClient::Request.execute(
:method => :post,
:url => api_url,
:headers => {:content_type => 'multipart/form-data', :accept => 'application/json', :X_Api_Secret => "xxxxxxxxx"}
)
which works perfectly until I try to pass a file like this
response =RestClient::Request.execute(
:method => :post,
:url => api_url,
:headers => {:content_type => 'multipart/form-data', :accept => 'application/json', :X_Api_Secret => "xxxxxxxxxx"},
:upload => {
:file => File.new(params[:custom_font][:font].path, 'rb')
}
)
It then seems to ignore my headers and I get a 403 error, I've also tried a regular rest-client post request like
response = RestClient.post api_url, { :X_Api_Secret => "xxxxxx"}
But again it breaks when I try to introduce the data file.
Any help, pointers or advice would be greatly appreciated.
Ok after a couple of days of head banging, I ended up using unirest instead, after updating to the latest version it worked straight away.
response = Unirest.post api_key,
headers:{
"X-Api-Secret" => "xxxxx"
},
parameters:{
"data" => "ccc"
}

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
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
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.
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

HTTParty not sending data to API

I am trying to call a Restful API (basically a third party application). Here is my code:
resp = HTTParty.post("http://example.com/test/api/url",
{
:query => {"id"=> 3, "example_payload"=> "test payload", "details"=> {}},
:headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'client_key' => "xxx-xxx-xxxxx" }
})
This is returning a response with status "200 ok". But I am not able to find the changes in my third party application.
I tried with "Rest-client" and "Net-http" as well. Both of them are also not working.
Thanks for helping in advance.
I assume that by
"not able to find the changes in my third party application"
, you mean that your not able to hit that third party url.
Solution:
You don't need to wrap the query and headers into a hash. Simply pass them as parameters like:
HTTParty.post(
"http://example.com/test/api/url",
query: {"id"=> 3, "example_payload"=> "test payload", "details"=> {}},
headers: { 'Content-Type' => 'application/json',
'Accept' => 'application/json',
'client_key' => "xxx-xxx-xxxxx"
}
)
This works for me.

Rails RestClient pass token in header fails

I do this curl in Terminal which works excellent:
$ curl https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000 -H "Authorization: Token xxxxxxxxxxxxxxxxxxxxxx"
Output is json.
Now I want to access the json string via my rails app. I have tried RestClient to do this, but somehow I always get a 401 unauthorized error. I believe the token gets not send correctly via header. I have tried the following:
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', {token: 'xxxxxxxxxxxxxxxxxxxxxx'}
and
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', :params => {:token => 'xxxxxxxxxxxxxxxxxxxxxx'}
with no success. Maybe I use a wrong syntax for sending the token in the header?
Doku is here http://rubydoc.info/github/rest-client/rest-client - I could not find any mistakes.
# GET request with modified headers
RestClient.get 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# POST request with modified headers
RestClient.post 'http://example.com/resource', {:foo => 'bar', :baz => 'qux'}, {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# DELETE request with modified headers
RestClient.delete 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
Source: https://github.com/rest-client/rest-client#headers

Resources