Is their a way to create Dummy Response with 500 code in HTTParty - ruby

Here my HTTParty code
response = HTTParty.post(api_url,body: form_data,timeout: 5)
rescue Timeout::Error
## create dummy response with 500 error code
response = HTTParty::Response.new()
ensure
response
all I'm trying to do is ensure If the HTTParty is unable to connect the given website create a dummy response body objec
But when I try to create a dummy Response object like this
## response = HTTParty::Response.new(Rack::Request.new(api_url),Rack::Response.new('TimeOut Error',500),'TimeOutError')
but this does not work because my response object does not respond_to to_hash
Can anyone suggest a better way to accomplish the same

In case anybody comes looking after 4 years, one could try the following:
httparty_req = HTTParty::Request.new Net::HTTP::Get, '/'
nethttp_resp = Net::HTTPInternalServerError.new('1.1', 500, 'Internal Server Error')
response = HTTParty::Response.new(httparty_req, nethttp_resp, lambda {''}, body: '')

Related

Parsing the response using REST vs. SOAP API in Ruby

I am trying to parse a response that I receive using Rest API calls, but get an error when I say, something like: response.body.first[1]. I am transferring Soap API calls to rest API calls. Is response.first something that can only be used in Soap, if so what is the equivalent in Rest? Here is the code snippet that I am having trouble with:
url = ##rest_base_url.to_s + "filters/#{id.to_s}/results"
resource = RestClient::Resource.new url, #username, #password
response = resource.get
data = JSON.parse(response.body)["data"]
if response.body.first[1][:return].nil?
requirements = nil
elsif response.body.first[1][:return].is_a?(Array)
# puts "|get_requirements| req is an array".blue
requirements = []
Thank you

Reading Withings API ruby

I have been trying for days to pull down activity data from the Withings API using the OAuth Ruby gem. Regardless of what method I try I consistently get back a 503 error response (not enough params) even though I copied the example URI from the documentation, having of course swapped out the userid. Has anybody had any luck with this in the past. I hope it is just something stupid I am doing.
class Withings
API_KEY = 'REMOVED'
API_SECRET = 'REMOVED'
CONFIGURATION = { site: 'https://oauth.withings.com', request_token_path: '/account/request_token',
access_token_path: '/account/access_token', authorize_path: '/account/authorize' }
before do
#consumer = OAuth::Consumer.new API_KEY, API_SECRET, CONFIGURATION
#base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}#{request.env['SCRIPT_NAME']}"
end
get '/' do
#request_token = #consumer.get_request_token oauth_callback: "#{#base_url}/access_token"
session[:token] = #request_token.token
session[:secret] = #request_token.secret
redirect #request_token.authorize_url
end
get '/access_token' do
#request_token = OAuth::RequestToken.new #consumer, session[:token], session[:secret]
#access_token = #request_token.get_access_token oauth_verifier: params[:oauth_verifier]
session[:token] = #access_token.token
session[:secret] = #access_token.secret
session[:userid] = params[:userid]
redirect "#{#base_url}/activity"
end
get '/activity' do
#access_token = OAuth::AccessToken.new #consumer, session[:token], session[:secret]
response = #access_token.get("http://wbsapi.withings.net/v2/measure?action=getactivity&userid=#{session[:userid]}&startdateymd=2014-01-01&enddateymd=2014-05-09")
JSON.parse(response.body)
end
end
For other API endpoints I get an error response of 247 - The userid provided is absent, or incorrect. This is really frustrating. Thanks
So I figured out the answer after copious amount of Googleing and grasping a better understanding of both the Withings API and the OAuth library I was using. Basically Withings uses query strings to pass in API parameters. I though I was going about passing these parameters correctly when I was making API calls, but apparently I needed to explicitly set the OAuth library to use the query string scheme, like so
http_method: :get, scheme: :query_string
This is appended to my OAuth consumer configuration and all worked fine immediately.

Reading the body of a 400 response?

I am trying to read the body of a 400 response with the rest-client gem. The problem is that rest-client responds to 400 by throwing it as an error, so I can't figure out any way to get the body text.
Here's the motivating example. Consider this call to the facebook graph API:
JSON.parse(RestClient.get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=#{access_token}"))
If the access_token is expired or invalid, facebook does two things:
Returns a 400 Bad Request HTTP response
Returns JSON in the response body with more info, like this:
{
"error": {
"message": "The access token could not be decrypted",
"type": "OAuthException",
"code": 190
}
}
Because 400 response raises an Error, I can't figure out how to get the body of the response. That is, eg, if I run the GET request above in curl or in my browser, I can see the body, but I can't figure out how to access it in restclient. Here's an example:
begin
fb_response = JSON.parse(RestClient.get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=#{access_token}"))
rescue => e
# 400 response puts me here
# How can I get the body of the above response now, so I can get details on the error?
# eg, was it an expired token? A malformed token? Something else?
end
From rest-client documentation:
Exceptions
for other cases, a RestClient::Exception holding the Response will be raised; a specific exception class will be thrown for known error codes
begin
RestClient.get 'http://example.com/resource'
rescue => e
e.response
end
You can rewrite your code like:
body = begin
RestClient.get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=#{access_token}")
rescue => e
e.response.body
end
fb_response = JSON.parse(body)
Or just use RestClient::Exception#http_body to get the response body from the exception. (It's just a shortcut).

RestClient POST doesn't display status on header-only response

I have a Rails action which responds with head :ok, rather than rendering any content. I'm calling this action using RestClient, like so:
resp = RestClient.post("#{api_server_url}/action/path", {:param_1 => thing, :param_2 => other_thing}, :authorization => auth)
The Rails server log shows that this worked as expected:
Completed 200 OK in 78ms (ActiveRecord: 21.3ms)
However, the resulting value of resp is the string " ", rather than an object I can examine (to see what its status code is, for instance).
I tried changing the action to use head :created instead, just to see if it produced a different result, but it's the same: " ".
How can I get the status code of this response?
RestClient.post returns an instance of the class RestClient::Response that inherits from the String class.
You can still check the return code by calling the method code resp.code. Other methods are for example resp.headers and resp.cookies.

How to parse HTTP response using Ruby

I've written a short snippet which sends a GET request, performs auth and checks if there is a 200 OK response (when auth success). Now, one thing I saw with this specific GET request, is that the response is always 200 irrespective of whether auth success or not.
The diff is in the HTTP response. That is when auth fails, the first response is 200 OK, just the same as when auth success, and after this then there is a second step. The page gets redirected again to the login page.
I am just trying to make a quick script which can check my login user and pass on my web application and tell me which auth passed and which didn't.
How should I check this? The sample code is like this:
def funcA(u, p)
print_A("#{ip} - '#{u}' : '#{p}' - Pass")
end
def try_login(u, p)
path = '/index.php?uuser=#{u}&ppass=#{p}'
r = send_request_raw({
'URI' => 'path',
'method' => 'GET'
})
if (r and r.code.to_i == 200)
check = true
end
if check == true
funcA(u, p)
else
out = "#{ip} - '#{u} - Fail"
print_B(out)
end
return check, r
end
end
Update:
I also tried adding a new check for matching a 'Success/Fail' keyword coming in HTTP response. It didn't work either. But I now noticed that the response coming back seems to be in a different form. The Content-Type in response is text/html;charset=utf-8 though. And I am not doing any parsing so it is failing.
Success Response is in form of:
{"param1":1,"param2"="Auth Success","menu":0,"userdesc":"My User","user":"uuser","pass":"ppass","check":"success"}
Fail response is in form of:
{"param1":-1,"param2"="Auth Fail","check":"fail"}
So now I need some pointers on how to parse this response.
Many Thanks.
I do this with with "net/http"
require 'net/http'
uri = URI(url)
connection = Net::HTTP.start(uri.host, uri.port)
#response = Net::HTTP.get_response(URI(url))
#httpStatusCode = #response.code
connection.finish
If there's a redirect from a 200 then it must be a javascript or meta redirect. So just look for that in the response body.

Resources