How to convert curl to Ruby Net::HTTP with -X GET -G options? - ruby

I was using https://jhawthorn.github.io/curl-to-ruby/ to convert curl commands to Net::HTTP code. However the following cannot be converted using the jhawthorn resource:
curl -H "Content-type: application/json" -H "Authorization: Token token=$PAGERDUTY_ACCESS_KEY" -X GET -G --data-urlencode "since=2017-01-16" --data-urlencode "until=2017-01-17" "https://company.pagerduty.com/api/v1/schedules"
I have described my exact problem in this github issue: https://github.com/jhawthorn/curl-to-ruby/issues/8
This is my current function that uses the Net::HTTP gem:
#!/usr/bin/env ruby
require 'json'
require 'net/http'
require 'uri'
def get_pagerduty_hash(ending='')
uri = URI.parse("https://company.pagerduty.com/api/v1/schedules#{ending}")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Token token=#{ENV['PAGERDUTY_ACCESS_KEY']}"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
return JSON.parse(response.body).to_hash
end
How can I change this to correctly use the date part of the original curl command:
-X GET -G --data-urlencode "since=2017-01-16" --data-urlencode "until=2017-01-17"

You have to use the URI.encode_www_form function:
#!/usr/bin/env ruby
require 'json'
require 'net/http'
require 'uri'
def get_pagerduty_hash(ending='')
uri = URI.parse("https://company.pagerduty.com/api/v1/schedules#{ending}")
params = { :since => '2017-01-16', :until => '2017-01-17' }
uri.query = URI.encode_www_form(params)
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Token token=#{ENV['PAGERDUTY_ACCESS_KEY']}"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
return JSON.parse(response.body).to_hash
end

urlencode means that the data is encoded in the URL
url = URI.parse('http://example.com')
url.query = "since=2017-01-16&until=2017-01-17"
puts url
# => http://example.com?since=2017-01-16&until=2017-01-17

Related

How to use httparty instead of net/http or curl

I have a curl request which works
curl -X GET -k 'https://APIADDRESSHERE' -u 'USERNAME:PASSWORD' -H 'Content-Type: application/json'
I can also get this working in ruby:
require 'net/http'
require 'uri'
require 'openssl'
uri = URI.parse("https://APIADDRESSHERE")
request = Net::HTTP::Get.new(uri)
request.basic_auth("USERNAME", "PASSWORD")
request.content_type = "application/json"
req_options = {
use_ssl: uri.scheme == "https",
verify_mode: OpenSSL::SSL::VERIFY_NONE,
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
However when I try this with httparty I keep getting a 401 error saying:
An Authentication object was not found in the SecurityContext This request requires HTTP authentication.
I have tried a lot of variations of the following but I'm stuck.
response = HTTParty.get('https://APIURLHERE', {"headers": { "Authorization:" => "BASE64ENCODEDUSERNAMEANDPASSWORD", "Content-Type" => "application/json" }})
Have you tried the following?
response = HTTParty.get('https://APIURLHERE', headers: { "Authorization:" => "BASE64ENCODEDUSERNAMEANDPASSWORD", "Content-Type" => "application/json" })
Ok I made a simple mistake somewhere along the way because the original solution from the similar post worked... Dont know how it didnt work 50 times last time I was working on this but it was clearly an error on my part somewhere.

How to turn curl request with user and password into ruby NET::HTTP for https site?

I have a ruby script that I'm using to get info from a web page and update the page. I am getting some json info from the web page with:
`curl -s -u #{username}:#{password} #{HTTPS_PAGE_URL}`
And then I am updating the page with:
`curl -s -u #{username}:#{password} -X PUT -H 'Content-Type: application/json' -d'#{new_page_json_info}' #{HTTPS_PAGE_URL}`
I want to use Net::HTTP to do this instead. How can I do this?
For reference here is the confluence doc that I used to create the curl command in the first place: https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples
can try doing something like:
uri = URI.parse("http://google.com/")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("username", "password")
Thank you http://jhawthorn.github.io/curl-to-ruby
That solved it. All you have to do is give that website your curl command and it will convert it into a ruby script.
For the first curl (this gets the json info from a page and sends it to stdout):
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
uri = URI.parse("https://my.page.io/rest/api/content/")
request = Net::HTTP::Get.new(uri)
request.basic_auth("username", "password")
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
# response.code
puts JSON.parse(response.body).to_hash
For the second (this updates the json info on a page):
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://my.page.io/rest/api/content/")
request = Net::HTTP::Put.new(uri)
request.basic_auth("username", "password")
request.content_type = "application/json"
request.body = "{Test:blah}"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end

Curl get request in Ruby

Would be very grateful if someone could help me convert this curl request into ruby?I have Been trying for a while and can't get the syntax correct.
curl -v -H "Content-Type: application/json" -H "X-Knack-Application-Id:000000" -H "X-Knack-REST-API-Key:000000" https://api.knackhq.com/v1/objects/object_6/records
tried:
uri = URI('https://api.knackhq.com/v1/objects/object_1/records')
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Post.new uri
# API details of Knack
request["X-Knack-Application-Id"] = '56e72cd003219158'
request["X-Knack-REST-API-Key"] = 'd9c343d2-2a4b-291e0712a63a'
end
There are at least two issues.
First, in the cURL command you don't specify a method, hence by default it is a GET, but you use POST in Ruby.
Secondly, you are missing the part where you execute the HTTP request
http.request(request)
Here's the code:
uri = URI('https://api.knackhq.com/v1/objects/object_1/records')
req = Net::HTTP::Get.new(uri)
req["X-Knack-Application-Id"] = '56e72cd003219158'
req["X-Knack-REST-API-Key"] = 'd9c343d2-2a4b-291e0712a63a'
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
http.request(req)
end
More examples are available in the Net::HTTP documentation.
Did you try some gems? I often use RestClient for api reqests, here is my example:
RestClient.post("https://api.knackhq.com/v1/objects/object_6/records", {}, {"X-Knack-REST-API-Key" => "000000", "X-Knack-Application-Id"=>"000000"})
More information about: https://github.com/rest-client/rest-client

Ruby https POST with headers and auth error

I'm trying to sent a post request that like so based on curl:
curl -XPOST -H content-type:application/json -d "{\"date\":\"2012-07-02\",\"aaaa\":\"bbbbb\", \"cccc\" : \"\[\"dddd\",\"eeee\",\"fffff\"\]\"}" URI -u USERNAME:PASSWORD
In Ruby:
#toSend = {
"date" => "2012-07-02",
"aaaa" => "bbbbb",
"cccc" => ["dddd","eeee","fffff"]
}.to_json
uri = URI.parse("https:/...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
req.body = "[ #{#toSend} ]"
req.basic_auth options[:username].to_s, options[:password].to_s
post = https.request(req)
For some reason the auth isn't getting attached what could be wrong with this?
I suspect your request to be run before you even add the auth parameters.
I would go this way:
require 'net/http'
require 'uri'
url = URI.parse('https://....')
req = Net::HTTP::Post.new(url.path)
req.basic_auth options[:username].to_s, options[:password].to_s
req.use_ssl = true
req.form_data({"date" => "2012-07-02", "aaaa" => "bbbbb", "cccc" => ["dddd","eeee","fffff"]})
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }

curl request in ruby

How would I make the following curl request in ruby?
curl -k -X GET -H "Content-Type: application/xml" -H "Accept: application/xml" -H "X-OFFERSDB-API-KEY: demo" 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
I'm having difficulty with some of the headers.
require 'net/http'
url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
mykey = 'demo'
request = Net::HTTP.new(url)
request.request_head('/', 'X-OFFERSDB-API-KEY' => mykey)
puts request
I think you need to create a request object, instead of an HTTP object. Then set headers on it.
require 'net/http'
url = 'http://testapi.offersdb.com/distribution/beta/offers?radius=10&postal_code=30305'
mykey = 'demo'
uri = URI(url)
request = Net::HTTP::Get.new(uri.path)
request['Content-Type'] = 'application/xml'
request['Accept'] = 'application/xml'
request['X-OFFERSDB-API-KEY'] = mykey
response = Net::HTTP.new(uri.host,uri.port) do |http|
http.request(request)
end
puts response
Source: http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTPHeader.html

Resources