Simple API wrapper with HTTParty - ruby-on-rails

I' am trying to create a simple wrapper for skyscanner API. The problems is that when try to get the sessionKey, what I get is <HTTParty::Response:0x10 parsed_response=nil, #response=#<Net::HTTPUnsupportedMediaType 415 Unsupported Media Type readbody=true>. I am not sure what is that I am doing wrong. I am new to rails and I will appreciate any direction on how to solve this problem?. Thanks
require 'httparty'
class Skyscanner
include HTTParty
format :json
base_uri "http://partners.api.skyscanner.net/apiservices/pricing"
def self.find(originplace, destinationplace)
#options = { query:
{
:apiKey => "API_KEY",
:country => "US",
:currency => "USD",
:locale => "en-us",
:adults => 1,
:children => 0,
:infants => 0,
:originplace => originplacea,
:destinationplace => destinationplace,
:outbounddate => "2017-02-20",
:inbounddate => "2017-02-27",
:locationschema => "iata",
:cabinclass => "Economy"
}
}
#headers = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'}
#sessionkey_request = HTTParty.post("http://partners.api.skyscanner.net/apiservices/pricing/v1.0/",:body => #options,:headers => #headers)
puts #sessionkey_request.inspect
#get_sessionkey = #sessionkey_request.headers['location']
#sessionkey = #get_sessionkey.to_s().split('/').last
puts #sessionkey.inspect
end
end
If anyone have a better way of approaching this wrapper, please advice me on how to. Thanks

Related

How to define a global variable that can be accessed in Delayed Job in rails?

This is my config/initializers/bunny.rb file:
if Setting.RABBITMQ_ENABLED[Rails.env]
conn = Bunny.new Setting.MERCURY_URL[Rails.env]
conn.start
bunny_settings = Setting.BUNNY_SETTINGS
## Channel && Topic for sending SMS-es.
sms_ch = conn.create_channel
::SmsHandle = sms_ch.topic(bunny_settings["sms_topic_name"], :durable => true, :auto_delete => true)
## Channel && Topic for sending seller requests
seller_ch = conn.create_channel
exchange = seller_ch.topic(bunny_settings["seller_topic_name"], :durable => true, :auto_delete => true)
seller_ch.queue(bunny_settings["seller_queue_name"], :durable => true, :auto_delete => true, :arguments => {}, :exclusive => false).bind(exchange, :routing_key => bunny_settings["seller_routing_key"]).subscribe do |delivery_info, properties, payload|
payload_json = JSON.parse payload
BunnyConsumer.consume_seller_request(delivery_info, properties, payload_json)
end
end
As you can see, I declared SmsHandle as a global variable to use it anywhere.
Worker code:
def send_sms(message_handle, caller_params)
if Setting.RABBITMQ_ENABLED[Rails.env]
pay_load = {:usertype => "custom", :triggers => [message_handle], :type => "notification", :caller_params => caller_params}.to_json
SmsHandle.publish(pay_load, :routing_key => "route_key" + rand(0..9).to_s, :content_type => "application/json", :type => "transport")
self.notification_events.create!(handle_name: message_handle, notification_type: SellerLead::NotificationType::SMS, payload: caller_params.to_json)
end
end
But, the problem for me here is that I unable to use it in any method that'll be called in a delayed_job.
So, how can I enable the delayed_job to use this particular variable.
Should I declare variable like this in the config/initializer/delayed_job.rb? Even this doesn't seem to working. Can someone point to the right way of doing this?

Send array in JSON POST request with HTTParty

I'm trying to work with a 3rd party API that requires an array to be sent within a POST request body. I've already gotten the hang of sending JSON; I've read you just need to set some headers and call to_json on the POST body. However, I'm not sure how to embed an array within that POST body. I've tried the following:
HTTParty.post(url,
:body => {
:things => [{:id => 1}, {:id => 2}, {:id => 3}],
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
)
but this is giving me a server error, leading me to believe the array isn't being formatted correctly. Could someone please advise on how to send an array within a JSON POST request? Thanks!
EDIT:
The error I get back is the following:
#<HTTParty::Response:0x10 parsed_response=nil,
#response=#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>,
#headers={"error_message"=>["Can not deserialize instance of java.lang.Long out of
START_OBJECT token at [Source: org.apache.catalina.connector.CoyoteInputStream#30edd11c;
line: 1, column: 15] (through reference chain: REDACTED[\"things\"])"],
"error_code"=>["0"], "content-length"=>["0"],
"date"=>["Wed, 13 Aug 2014 22:53:49 GMT"], "connection"=>["close"]}>
The JSON should be in the format:
{ "things" : [ {"id": "..."}, {"id: "..."}, ... ] }
The simplest way to embed an array within a POST body using HTTParty in Ruby on Rails is to pass the request to an instance variable (any name of your choice can suffice for the instance variable).
So we will have
#mypost = HTTParty.post(url,
:body => {
:things => {
:id => 1,
:id => 2,
:id => 3
},
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'xxxxxxxxxx'
'Accept' => 'application/json'
})
Here is an example of an HTTParty Post Request
#myrequest = HTTParty.post(' https://www.pingme.com/wp-json/wplms/v1/user/register',
:body => {
:books => {
:name => "#{#book.name}",
:author => "#{#book.author}",
:description => "#{#book.description}",
:category_id => "#{#book.category_id}",
:sub_category_id => "#{#book.sub_category_id}"
},
}.to_json,
:headers => { 'Content-Type' => 'application/json',
'Authorization' => '77d22458349303990334xxxxxxxxxx',
'Accept' => 'application/json'})
That's all
I hope this helps.
I had a similar requirement for a SurveyMonkey API, the below will create a params_hash with nested array of hashes
create the fields array of hashes
fields = []
i =0
while i < 10 do
fields << {":id#{i}" => "some value #{i}"}
i += 1
end
method with optional splat field variable
def get_response(survey_id, respondent_ids, *fields )
params_hash = {}
params_hash[:survey_id] = "#{survey_id}"
params_hash[:respondent_ids] = respondent_ids
params_hash[:fields] = fields
#result = HTTParty.post("http://"some.address.here",
#:debug_output => $stdout,
:headers => {'Authorization' => "bearer #{#access_token.to_s}", 'Content-type' => 'application/json'},
:body => params_hash.to_json,
)
end

undefined method `values_at' for nil:NilClass when I use WashOut gem

I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.

How to use Rhodes without Rhosync or RhoConnect?

I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.

json format from rails to sproutcore

For those of you using Rails as a backend to their Sproutcore clients,
which one is the best way to format the data into json?
From the Sproutcore guides there was this approach:
def as_json(options = {})
event_hash = {
"guid" => self.id,
"id" => self.id,
"designation" => self.designation,
"category" => self.category,
"scheduled_for" => self.scheduled_for,
"location" => self.location,
"groups" => self.groups,
"resources" => self.resources
}
event_hash
end
But it fails, send an "Illegal statement error". Then, I changed to this other method:
def as_json(options = {})
# event_hash = options.merge(:include => [:groups, :resources], :methods => :guid)
event_hash = options.merge(:methods => :guid)
super(event_hash)
end
which seems to be working as far as the formatting is concerned, although I am suspecting it to causing some trouble regarding the representation in the dataHash of the store. Anyway, ha anyone been having similar issues with the first version of as_json? If not, is there anything I am doing wrong?
Appreciate any help
On the first method you need to call super:
def as_json(options = {})
event_hash = {
"guid" => self.id,
"id" => self.id,
"designation" => self.designation,
"category" => self.category,
"scheduled_for" => self.scheduled_for,
"location" => self.location,
"groups" => self.groups,
"resources" => self.resources
}
super(event_hash)
end
However you should get the options param and process to do this apropiately.

Resources