I'm trying to query the Artifactory's AQL API using ruby code, I already checked that this code works on bash using curl:
curl -u admin:password -i -H "Accept: application/json" -X POST http://server.example.com:8081/artifactory/api/search/aql -T aql.aql
Where aql.aql contents are as follows:
items.find
(
{
"repo":{"$eq":"test-ASO"}
}
)
.include("name","property.*")
Now I'm trying to do the same using Ruby with this code:
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'open-uri'
require 'uri'
require 'net/http'
payload ='items.find
(
{
"repo":{"$eq":"test-ASO"}
}
).include("name","property.*")'
uri = URI.parse("http://server.example.com:8081/artifactory/api/search/aql")
http = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req.basic_auth 'user', 'password'
req.set_form_data(payload)
res = http.request(req)
puts res.body
But all that I get is:
{
"errors" : [ {
"status" : 400,
"message" : "Bad Request"
} ]
}
My guess is that the payload of the query has to be a file, as I did before with curl (-T parameter) but I don't think that using files for queries is a very elegant way to achieve this.
EDIT
Finally I achieved this by declaring the req.body variable with the proper content:
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'open-uri'
require 'uri'
require 'net/http'
payload = 'items.find().include("name","property.*")'
uri = URI.parse("http://server.example.com:8081/artifactory/api/search/aql")
http = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req["Content-Type"] = "text/plain"
req.basic_auth 'admin', 'password'
req.body = payload
res = http.request(req)
puts res.body
Related
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"}]
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
I'm struggling with getting results from the team city api in JSON
require 'open-uri'
url = ".../app/rest/buildQueue/"
c = Curl::Easy.new(url) do |curl|
curl.headers["Content-type"] = "application/json"
curl.http_auth_types = :basic
curl.username = 'user'
curl.password = 'password'
end
c.perform
puts c.body_str
I get a bunch of xml text
You need to use the Accept header to control the response type:
e.g (command line)
curl --url http://xxx/app/rest/buildQueue/ -H Accept:"application/json"
Documentation Reference
also you can use "net/http"
require 'net/http'
require 'uri'
url = URI('http://localhost:8111/httpAuth/app/rest/agents')
req = Net::HTTP::Get.new(url)
req['Accept'] = 'application/json'
req.basic_auth 'admin', 'admin'
res = Net::HTTP.start(url.hostname, url.port) {|http|
http.request(req)
}
puts res.body
require 'net/http'
require 'uri'
postData = Net::HTTP.post_form(URI.parse('http://localhost/restapi/index.php/api/posts'),
{'id'=>9,'firstname'=>"test","lastname"=>"test"})
puts postData.body
How can I send data in JSON form?
#toSend = {"id" =>5,"firstname" => "anurag","lastname" => "arya"}
I also tried this but it did not work:
#toSend.to_json
Example:
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
url = "http://localhost/restapi/index.php/api/posts"
uri = URI.parse(url)
data = {"id"=>11,
"firstname"=>"PWD","lastname"=>"last"}
headers = {'Content-Type' =>'application/json',
'Accept-Encoding'=> "gzip,deflate",
'Accept' => "application/json"}
http = Net::HTTP.new(uri.host,uri.port) # Creates a http object
#http.use_ssl = true # When using https
#http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.post(uri.path,data.to_json,headers)
puts response.code
puts response.body
postData=Net::HTTP.post_form(URI.parse('http://localhost/oecprashant/yiiIndex.php/api/rubyREST'),
{'data'=>jsonData})
I'm pretty new in Ruby and Rails.
I want to send a HTTP POST request in my rails application, the request can be invoked by command line like:
curl -X POST -u "username:password" \
-H "Content-Type: application/json" \
--data '{"device_tokens": ["0C676037F5FE3194F11709B"], "aps": {"alert": "Hello!"}}' \
https://go.urbanairship.com/api/push/
The ruby code I wrote (actually it's glue code) is:
uri = URI('https://go.urbanairship.com/api/push')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Post.new(uri.request_uri, initheader = {'Content-Type' =>'application/json'})
request.basic_auth 'username', 'password'
request.body = ActiveSupport::JSON.encode({'device_tokens' => ["4872AAB82341AEE600C6E219AA93BB38B5144176037F2056D65FE3194F11709B"], "aps" => {"alert" => "Hello!"}})
response = http.request request # Net::HTTPResponse object
puts response.body
end
However, running the ruby code in Rails Console didn't give me expected result (the command line does). Can someone give me a hand? I've tried searching relevant posts and Ruby docs, however my knowledge in Ruby is not good enough to solve it.
require 'net/http'
require 'net/https'
https = Net::HTTP.new('go.urbanairship.com', 443)
https.use_ssl = true
path = '/api/push'
It's often tidier to create a little client class. I like HTTParty for that:
require 'httparty'
class UAS
include HTTParty
base_uri "https://go.urbanairship.com"
basic_auth 'username', 'password'
default_params :output => 'json'
#token = "4872AAB82341AEE600C6E219AA93BB38B5144176037F2056D65FE3194F11709B"
def self.alert(message)
post('/api/push/', {'device_tokens' => #token, 'aps' => {"alert" => message}})
end
end
Then you use it like so:
UAS.alert('Hello!')