curl request in ruby - 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

Related

Convert Hash to specific string format in ruby

I would like to convert a hash: {"key1"=>"value1", "key2"=>"value2"} into a string which looks like this: '[{"key1" : "value1","key2" : "value2"}]'
Background: I'm making an API call from my rails Controller.
The curl equivalent of this request is curl -X POST -H 'Content-Type: application/json' -i 'valid_uri' --data '[{"key1" : "value1","key2" : "value2"}]'
So, to convert this in ruby, I tried the following:
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse(VALID_URI)
header = {'Content-Type' => 'application/json'}
data = {"key1"=>"value1", "key2"=>"value2"}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = Array.wrap(data1.to_s.gsub('=>',':')).to_s
response = http.request(request)
However, the format of request.body doesn't match the format of data in curl request which results in Net::HTTPBadRequest 400 Bad Request
Can someone please explain how can I achieve this? TIA
just use the json module:
require "json"
h=[{"key1"=>"value1", "key2"=>"value2"}]
string=h.to_json # => [{"key1":"value1","key2":"value2"}]

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

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

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

Add `Authorization Bearer` hash to Net::HTTP post request (Ruby)

How can I add Authorization Bearer to a POST request with Net::HTTP?
I can only find help for "basic authentication" in the documentation.
req.basic_auth 'user', 'pass'
Source: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication
I'm trying to replicate a curl that would look like:
> curl 'http://localhost:8080/places' -d '{"_json":[{"uuid":"0514b...",
> "name":"Athens"}]}' -X POST -H 'Content-Type: application/json' -H
> 'Authorization: Bearer eyJ0eXAiO...'
Currently I've gotten to:
require 'net/http'
require 'net/https'
require 'uri'
uri = URI('http://localhost:8080/places')
res = Net::HTTP.post_form(uri, '_json' => [{'uuid': '0514b...', 'name':'Athens'}])
But I'm having trouble figuring out how to add the Authentication: Bearer... part.
Does anyone have experience with this?
I dont think you can add custom headers with the post_form method. You can add it with post method. Try the code below:
uri = URI("http://localhost:8080/places")
params = [{'uuid': '0514b...', 'name':'Athens'}]
headers = {
'Authorization'=>'Bearer foobar',
'Content-Type' =>'application/json',
'Accept'=>'application/json'
}
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)

How can I run this curl command in Ruby?

curl --request PROPFIND --url "http://carddav.mail.aol.com/home/testuser#aol.com/Contacts/" --header "Content-Type: text/xml" --header "Depth: 1" --data '<A:propfind xmlns:A="DAV:"><A:prop><A:getetag /><D:address-data xmlns:D="urn:ietf:params:xml:ns:carddav"/></A:prop></A:propfind>' --header "Authorization: Bearer fjskdlfjds"
Is there a particular method in Net::HTTP that allows the propfind command?
Net::HTTP::Propfind
Here is an example:
uri = URI.parse('http://example.com')
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Propfind.new(uri.request_uri)
# Set your body (data)
request.body = "Here's the body."
# Set your headers: one header per line.
request["Content-Type"] = "application/json"
response = http.request(request)

Resources