Ruby - no implicit conversion of HTTParty::Response into String exotel api - ruby-on-rails

I'm unable to fetch response or send request to exotel sms api using the provided documentation on exotel rubygem http://www.rubydoc.info/gems/exotel/0.2
The documentations says to fetch response as follows:
sms = Exotel::Sms.details(sms_id)
But when I do that with an sms_id, ex. sms_id='12345678901234567890'
like
sms = Exotel::Sms.details("12345678901234567890")
it gives an error
TypeError: no implicit conversion of HTTParty::Response into String
I do have httparty gem installed. How to solve this?

The library is tested with 0.9.0 version of httparty that used to respond with Hash for http requests and the code is assuming it is string if not Hash and that is why it is failing
Here is the line causing the problem
exotel/response.rb
Quick fix would be to use 'httparty=0.9.0'
You may do it by using
gem "httparty","0.9.0"
Here is a working sample code, please update the account_sid and token with yours
gem "httparty","0.9.0"
require "exotel"
account_sid = "testexotel"
token = "9dcb4*******************e1dc2174fc47"
Exotel.configure do |c|
c.exotel_sid = account_sid
c.exotel_token = token
end
sms = Exotel::Sms.details("40a7*********258d411898b18b")
puts sms.status
puts sms.date_sent

Related

How to check for successful response from API in rails by just using status code?

I am consuming an API using a gem in Ruby on Rails. The gem makes the API call for me and returns the status code as an integer (for example 200, 201 e.t.c.) and the data response from the API.
def get_cars
status_code, data = MyGem::Cars.get_cars
if status_code in SUCCESSFUL_RESPONSE_CODES
# Perform data manipulation
else
raise "There was an error processing the request. Status code #{status_code}"
end
end
Now I have manually initialised SUCCESSFUL_RESPONSE_CODES as a list containing integers of successful codes I found here.
Is this list defined somewhere in Ruby/RoR to avoid manually defining it?
I would expect any widely supported gem to use standard HTTP response codes to determine if the HTTP response was a success. For example:
require 'open-uri' # Rails loads this by default.
res = open('http://example.com')
res.status
=> ["200","OK"]
status.include?'OK'
=>true
status.include?'200'
=> true
So long as you trust the gem code making your request to handle standard HTTP response codes, you should be ok. Here's another example using HTTParty gem
require 'HTTParty'
res = HTTParty.get('https://example.com')
res.success?
=> true

Undefined method `OAuth' when making HTTP request to Twitter api

I'm getting the following OAuth error when trying to make a request to the Twitter streaming api:
"#NoMethodError: undefined method `OAuth' for #TwitterMoment:0x007fa081d821f0"
def query
authorisation_header = OAuth oauth_consumer_key=ENV["oauth_consumer_key"], oauth_nonce=ENV["oauth_nonce"], oauth_signature=ENV["oauth_signature"], oauth_signature_method=ENV["oauth_signature_method"], oauth_timestamp=ENV["oauth_timestamp"], oauth_token=ENV["oauth_token"], oauth_version=ENV["oauth_version"]
response = HTTParty.get("https://stream.twitter.com/1.1/statuses/filter.json?locations=-#{#bounds}", headers: {"Authorization" => authorisation_header})
end
OAuth is included in my gemfile.
Any ideas would be very much appreciated! This is my first Stack Overflow question :)
You're using OAuth here as a function/method, but that method doesn't exist. There's no def OAuth(...) anywhere in the oauth gem, so it explodes and gives you that NoMethodError.
Judging from the Header example at the bottom of this question, I think you've confused the header string for Ruby code.
Instead, you either need to make the string yourself (a bit annoying to do safely), or use the OAuth gem's methods (API) to do so.
Here's an example from the OAuth github repo:
consumer = OAuth::Consumer.new(
options[:consumer_key],
options[:consumer_secret],
:site => "http://query.yahooapis.com"
)
access_token = OAuth::AccessToken.new(consumer)
response = access_token.request(
:get,
"/v1/yql?q=#{OAuth::Helper.escape(query)}&format=json"
)
rsp = JSON.parse(response.body)
pp rsp
This example may work for you (I'm not able to test it locally here, sorry):
def query
consumer = OAuth::Consumer.new(
ENV["oauth_consumer_key"],
ENV["oauth_consumer_token"],
site: "https://stream.twitter.com"
)
access_token = OAuth::AccessToken.new(consumer)
response = access_token.request(
:get,
"/1.1/statuses/filter.json?locations=-#{OAuth::Helper.escape(#bounds)}"
)
response = JSON.parse(response.body)
pp response # Just a bit of debug printing for the moment; remove this later.
response
end
An addendum:
Usually I might have directed you to use an existing Twitter client gem, such as https://github.com/sferik/twitter, but in this case it looks like they haven't implemented the Moments API yet.

Ruby - gem instagram parser error on response

Faraday Parsing Error 757
I'm new with Ruby and i'm trying to do a simple instragram integration using instagram gem.
I already configured tokens (access_token, client_secret, client_id) with Insagram.config()
Now i'm facing an error while trying to get recent media from instagram inside my controller.
The request:
#medias = Instagram.user_recent_media(196583629, {:count => 1})
The error:
Faraday::Error::ParsingError at /contests/385
757: unexpected token at '�'
Console:
faraday_middleware (0.9.1) lib/faraday_middleware/response/parse_json.rb:11:in `block in <class:ParseJson>'
I don't know if might be the response that i'm getting is broken etc..
Is there a way to check how and what's my response ?
Appreciate any help :)
Thanks.
I tried to replicate this, but the userid you gave is protected.
However, the following code works ok for me (using Snoop Doggs ID: 1574083)
require 'instagram'
Instagram.configure do |config|
config.client_id = ENV['INSTA_CLIENT']
config.client_secret = ENV['INSTA_SECRET']
end
#medias = Instagram.user_recent_media(1574083, {:count => 1})
puts #medias.first
However, unexpected token errors basically imply that the JSON given by the server is not valid json, normally because it's not JSON at all or it's invalid (leading " for example...)
If you do a manual curl of that userid, what do you get?
curl https://api.instagram.com/v1/users/196583629/media/recent/?client_id='clientidhere'

Ruby SOAP Client using SAVON not working whereas PHP SOAP client works

Hello there I am testing few web services and I am trying to write a client using SAVON with my WSDL. I have one available operation named log_process and I am trying to access that but getting errors. I have a similar script written in PHP and it is working fine. I have tried
require 'net/http'
require "uri"
require 'savon'
client = Savon.client(wsdl: "http://somedomain.com/projects/shared/abc.wsdl")
#a=client.operations
puts #a
ary={0 =>"art", 1 =>"bac", 2 =>"arr"}
#result = client.call(:log_process, message:{0 =>"asdf", 1 =>"qwer", 2 =>"arr"})
puts #result
and getting following error
raise_soap_and_http_errors!': (SOAP-ENV:Client) Bad Request (Savon::SOAPFault)
My php working solution looks like this
$result = $client->log_process(array(0=>$user_name,1=>$user_pwd,2=>$display_type));
any idea what will be the ruby equivalent to this or am I calling the operation in correct manner?
I know this is late, but I was having the exact same issue trying to set up a soap request using savon to a soap server I have worked with extensively using PHP Soap server. I found another post related to this, and it seem that adding the message_tag option fixed it.
This is because in my case the WSDL was expecting functionNameRequest in the xml, but savon as only sending funcionName by setting message_tag to functionNameRequest the >soap server was able to correctly map the function that was being requested.
This was the thread that helped me out https://github.com/savonrb/savon/issues/520 Relevant code quoted below:
Hi,
I'm just sharing this in case it's useful.
I'm using savon 2.3.0 and I guess the gem had some problems identifying parameters >automatically from my wsdl. I have no idea about SOAP and this is the first time I'm >actually using it.
I'm dealing with TradeTracker's WSDL
With the following code I got it working:
client = Savon.client do
wsdl "http://ws.tradetracker.com/soap/affiliate?wsdl"
namespace_identifier :ns1
end
credentials = {
customerID: 123123,
passphrase: "123123123"
}
response = client.call(:authenticate, message_tag: :authenticate, message: credentials)
Try:
#result = client.call(:log_process, message:["asdf", "asg", "arr"])
In the PHP code, you are sending only 1 parameter, its an array

743: unexpected token at '... in Ruby on Rails

I saved a file named array.json on my Dropbox folder and i access to it via Dropbox API. All works fine, but when i retrieve JSON content i cannot JSON.parse that string!!
session = DropboxSession.new(APP_KEY, APP_SECRET)
session.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
client = DropboxClient.new(session, ACCESS_TYPE)
json = client.get_file(DIRECTORY + '/array.json')
#json = JSON.parse json
Error:
743: unexpected token at '{"Nome" : "Mario Rossi",
"C.F." : "ABCDEFGHILMNOP",
"Booking Assistance" : "MARIO",
"Status of reservation" : "25/11/2011"}'
JSON string is valid!! if i copy this string and paste it (manually) as parameter in JSON.parse(), json is parsed correctly!! So i think is a encoding problem...but where i wrong?
We have abandoned the json parsing backend that is the default in Rails. The default backend is YAML based and imo a useless mess. After several gotchas parsing unicode, and dates in some cases, we discovered that the backend can be replaced via configuration.
You can substitute the parsing backend in an initializer
ActiveSupport::JSON.backend = "JSONGem"
There are several gems that can be used as the backend, we just use the json gem
gem 'json'

Resources