Header parameter missing when making POST request using Rest-Client Ruby Gem - ruby

Hi I am successfully able to post from Post man , but unable to do so from Ruby Rest client.
Post details
Post Man Request
POST /endpoint HTTP/1.1
Host: host:11400
Accept: application/json
HTTP_USER: userid
fname: fname
lname: lname
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 589a5345-e384-bd71-d690-60987165487b
{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}
the rest code I ve tried multiple ways including below
method tried
p RestClient.post 'http://url_details',
Accept: 'application/json',
'HTTP_USER'.to_sym => 'userid',
fname: 'name',
lname: '',
'Content-Type'.to_sym => 'application/json',
payload: JSON.parse('{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}')
method tried
p RestClient.post 'http://url_details/job', http_user: 'userid', content_type: :json, accept: :json
method tried
p #uber_ride = (RestClient::Request.execute(
:method => :post,
:url => 'http://url_details/job',
'HTTP_USER' => 'userid',
:headers => {:content_type => 'application/json', :accept => 'application/json', :HTTP_USER => 'userid', :fname => 'name', :lname => 'lname'}
))
method tried
p '++++++++++++++++++++++++++++++++'
p RestClient.post($Current_Api_Endpoint,
$Current_Payload,
:http_user =>'userid',
headers:
{:accept => 'application/json',
:content_type => 'application/json',
:http_user =>'userid',
:fname => 'name',
:lname => 'lname'}
)
p '++++++++++++++++++++++++++++++++'
method tried
p env1 = ENV['http_proxy']
# p a = {:method => :post, :url => 'http://url_details/job', :headers => { :accept => 'application/json', :content_type => 'application/json', :http_user => 'userid', :fname => 'name', :lname => 'lname' }, :payload => { :rtdt => "06/10/2016",:jobs => [{:pid => 53} , {:pid => 54}]} }
p a = {
method: 'post',
url: 'http://url_details/job',
proxy: ENV['http_proxy'],
headers: {accept: 'application/json', content_type: 'application/json', http_user: 'userid', fname: 'name', lname: 'lname'},
payload: { rtdt: '06/10/2016', jobs: {pid: 53}}
}
I am getting error
HTTP Status 500 - HTTP_USER header not found in request
torg.springframework.security.web.authentication
I Found out the issue since then. All headers are able to be sent, except this one - This one in CAPS. rest of them in small characters. How to solve it

Ruby's Net::HTTP implementation does not transmit ALL_CAPS_UNDERSCORED header names. RestClient relies on Net::HTTP. So, for example, the HTTP_USER header is actually transformed into Http_user when transmitted.
Alertnative: curb
Curl, however, does not have this limitation. It transmits header names verbatim. Therefore instead of using RestClient, you could use the curb gem, which is a wrapper around libcurl. This seems to work:
require "curb"
Curl::Easy.http_post("http://URL_REDACTED") do |http|
http.headers["Accept"] = "application/json"
http.headers["Content-Type"] = "application/json"
http.headers["HTTP_USER"] = "userid"
http.post_body = '{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}'
end
Alternative: excon
The excon gem is another possibility. It implements HTTP in pure Ruby, without relying on Net::HTTP. It does its own header processing and allows ALL_CAPS headers. So this should work:
require "excon"
Excon.post(
"http://URL_REDACTED",
:headers => {
"Accept" => "application/json",
"Content-Type" => "application/json",
"HTTP_USER" => "userid"
},
:body => '{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}'
)
Anyway, I would argue that the server you are trying to connect to is ultimately at fault here, because headers are supposed to be evaluated as case-insensitive: Are HTTP headers case-sensitive?. If the server requires a header be in all uppercase, that is a bug.

The RestClient README examples indicate that the correct usage is:
RestClient.post(url, payload, headers)
So all you have to do is:
RestClient.post(
"http://URL_REDACTED",
'{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}',
content_type: :json,
accept: :json,
"HTTP_USER" => "userid"
)
I tested against http://requestb.in and got the expected headers and body:
HEADERS
Total-Route-Time: 0
Connection: close
Via: 1.1 vegur
Connect-Time: 0
Http-User: userid
Content-Type: application/json
Content-Length: 55
User-Agent: rest-client/2.0.0 (darwin15.4.0 x86_64) ruby/2.3.1p112
X-Request-Id: c7cd819f-8901-41b9-8cbb-3b6d1895cd67
Accept-Encoding: gzip
Host: requestb.in
Accept: application/json
RAW BODY
{ "rtdt":"09/08/2016","jobs":[{"pid":53} , {"pid":54}]}

Related

Users_not_found in HTTParty request to SlackAPI when curl works

I'm trying to use GET request using httparty gem to have info about specific user from SlackAPI. From curl it works well
curl --data "token=SLACK_TOKEN&email=user#example.com" https://slack.com/api/users.lookupByEmail
But my code below seems to be broken because I received an error {"ok":false,"error":"users_not_found"}
module Slack
class GetUserId
def call
response = HTTParty.get("https://slack.com/api/users.lookupByEmail", payload: payload, headers: headers)
end
def headers
{
'Content-Type' => 'application/json',
'Authorization' => 'Bearer SLACK_TOKEN'
}
end
def payload
{
email: "user#example.com"
}.to_json
end
end
end
If you check their documentation, it seems that API do not accept JSON-form but rather "application/x-www-form-urlencoded.
So something like:
headers: {
'Authorization' => 'Bearer SLACK_TOKEN,
"Content-Type" => "application/x-www-form-urlencoded"
},
body: {
"token=SLACK_TOKEN”,
”email=user#example.com"
...
Reference: https://api.slack.com/methods/users.lookupByEmail

Uploading to Google Drive API using Ruby RestClient

I'm trying to upload a small image file to Google Drive using RestClient. I already have an access token (being requested in earlier code) but I am not sure how to form the payload.
The API docs state the request should look like this:
POST /upload/drive/v3/files?uploadType=media HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Content-Length: number_of_bytes_in_file
Authorization: Bearer your_auth_token
JPEG data
I have tried the following but it results in an error:
require 'rest-client'
file = File.open("./uploaded-by-api.jpg")
response = RestClient::Request.execute(method: :post, url: 'https://www.googleapis.com/upload/drive/v3/files', payload: { uploadType: "media", file: file, }, headers: { Authorization: "Bearer #{access_token}", "Content-Type" => "image/jpeg", "Content-Length" => "1000" })
I'm pretty sure there is a mistake in the way I'm including the actual file data but I can't find any examples of this with RestClient.
Ok solved it with the following:
response = RestClient.post(
'https://www.googleapis.com/upload/drive/v3/files',
{ 'uploadType' => "media", 'upload' => file },
"Authorization" => "Bearer #{access_token}",
"Content-Type" => "image/jpeg",
"Content-Length" => "1000"
)

send post request with xml response using ruby 1.8.7

I'm trying to customize the interface provider qiwi
this is my code:
http = Net::HTTP.new('w.qiwi.com', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
body = {
:bill_id => "BILL-#{payment.id}",
:user => 'tel:' + params[:qiwi][:phone],
:amount => payment.amount,
:ccy => 'RUB',
:comment => "",
:prv_name => 'Company'
}.to_param
key = "Basic " + Base64.encode64s("secret_key")
http.send_request('POST', "/qiwi-notify.php HTTP/1.1", body, {'Accept' => application/xml', 'Authorization' => key})
I need to do the following:
POST /qiwi-notify.php HTTP/1.1
Accept: application/xml
Content-type: application/x-www-form-urlencoded
Authorization: Basic MjA0Mjp0ZXN0Cg==
bill_id=BILL-
1&status=paid&error=0&amount=1.00&user=tel%3A%2B79031811737&prv_nam
e=TEST&ccy=RUB&comment=test&command=bill
Response should XML-doc:
HTTP/1.1 200 OK
Content-Type: text/xml
<?xml version="1.0"?> <result><result_code>0</result_code></result>
how can I implement a request privednny below, my code does not work
Thanks
You didn't explicitly state what your problem is, but looking at the code there are a few problems before it can be even interpreted.
:bill_id => "BILL-#{payment.id}"
needs a , at the end.
http.send_request('POST', "/qiwi-notify.php HTTP/1.1", body, {'Accept' => application/xml', 'Authorization' => key})
is lacking an apostrophe before application/xml'.
With those fixes in place, the code ends up looking like
http = Net::HTTP.new('w.qiwi.com', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
body = {
:bill_id => "BILL-#{payment.id}",
:user => 'tel:' + params[:qiwi][:phone],
:amount => payment.amount,
:ccy => 'RUB',
:comment => "",
:prv_name => 'Company'
}.to_param
key = "Basic " + Base64.encode64s("secret_key")
http.send_request('POST', "/qiwi-notify.php HTTP/1.1", body, {'Accept' => 'application/xml', 'Authorization' => key})

Webmock not registering my request stubs correctly

I am registering a request stub as follows:
url = "http://www.example.com/1"
stub_request(:get, url).
with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n",
headers: {
'Accept' => 'application/xml',
'Content-type' => 'application/xml',
'User-Agent' => 'Ruby',
'X-Trackertoken' => '12345'
}).
to_return(status: 200, body: '', headers: {})
for some reason when I run bundle exec rspec spec, my specs fails saying that the request isn't registered yet. The registered stub is this,
stub_request(:get, "http://www.example.com/1").
with(body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n",
headers: {
'Accept' => 'application/xml',
'Content-type' => 'application/xml',
'User-Agent' => 'Ruby',
'X-Trackertoken' => '12345'
})
note that the to_return part is missing
I tried replacing the body header with an empty string, the request stub is registered correctly but then my specs will still fail because they are expecting some value from the body other than the empty string. Thus, it is really important that I assign a value to body.
In my spec I am calling this method:
def find(id)
require 'net/http'
http = Net::HTTP.new('www.example.com')
headers = {
"X-TrackerToken" => "12345",
"Accept" => "application/xml",
"Content-type" => "application/xml",
"User-Agent" => "Ruby"
}
parse(http.request(Net::HTTP::Get.new("/#{id}", headers)).body)
end
Any ideas on why this is happening?
Thanks.
The problem is that your stub is matching a GET request with a non-empty body of <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n, but when you make the request you're not including any body, so it doesn't find the stub.
I think you're confused about what body is what here. The body in the with method arguments is the body of the request you are making, not the body of the response. What you probably want is a stub like this:
url = "http://www.example.com/1"
stub_request(:get, url).
with(headers: {
'Accept' => 'application/xml',
'Content-type' => 'application/xml',
'User-Agent' => 'Ruby',
'X-Trackertoken' => '12345'
}).
to_return(status: 200,
body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project>\n <id>1</id>\n</project>\n",
headers: {})

Setting Request Headers in Ruby

I have the rest client gem and I am defining a request like this:
url = 'http://someurl'
request = {"data" => data}.to_json
response = RestClient.post(url,request,:content_type => :json, :accept => :json)
However I need to set the HTTP header to something. For example an API key. Which could be done in curl as:
curl -XHEAD -H x-auth-user: myusername -H x-auth-key: mykey "url"
Whats the best way to do this in ruby? Using this gem? Or can I do it manually to have more control.
The third parameter is the headers hash.
You can do what you want by:
response = RestClient.post(
url,
request,
:content_type => :json, :accept => :json, :'x-auth-key' => "mykey")
You can also do this
RestClient::Request.execute(
:method => :get or :post,
:url => your_url,
:headers => {key => value}
)
I had the same problem with Rest-Client (1.7.2) I need to put both params and HTTP headers.
I solved with this syntax:
params = {id: id, device: device, status: status}
headers = {myheader: "giorgio"}
RestClient.put url, params, headers
I hate RestClient :-)
If PUT isn't allowed we can pass it in the header of POST. Headers in bold. This worked for me:
act_resp = RestClient.post url, req_param, **:content_type => :json, :method => :put**

Resources