I am trying to use HTTParty in irb to test an API call, but I keep getting a 401. Attempts to do a get against the same URL with the same header info using the Postman Chrome add-on work fine -- any ideas?
irb> HTTParty.get("https://developer.fingercheck.com/api/v1/Employees/GetAllEmployees",
:headers => {"APIKEY" => "ABCD1234-1234-ABCD-EFGH-ABCD1234ABCD123",
"ClientSecretKey" => "ABCD1234-1234-ABCD-EFGH-ABCD1234ABCD123",
"Content-Type" => "application/json"})
=> <HTTParty::Response:0x8 parsed_response=nil, #response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>,
#headers={"cache-control"=>["no-cache"], "pragma"=>["no-cache"],
"expires"=>["-1"], "server"=>["Microsoft-IIS/7.5"], "x-aspnet-version"=>["4.0.30319"],
"x-powered-by"=>["ASP.NET"], "date"=>["Mon, 01 Dec 2014 21:04:32 GMT"],
"connection"=>["close"], "content-length"=>["0"]}>
I have also tried to do the get call with :query=>..., :query => {:header..., and :basic_auth =>..., but none change the results. Any ideas?
I know a fair number of HTTParty questions have been asked and answered, but I didn't see anything that spoke to this particular issue.
The documentation I know of for the API is at http://developer.fingercheck.com/api/help
The error turned out to be a problem with the API, not with the code -- our headers were being read as 'Apikey' and 'Clientsecretkey' and therefore failing some equality on their side. A fix was pushed to production by them, code now functional.
Add 'Accept' => 'application/json' to your request headers.
Related
Was any breaking change made by Google on GMail API on 11th April, 2020 ?
We have a ruby web application which also has a Chrome extension. (pretty old, ruby 2.1.0) which uses google-api-client version 0.6.4 and was working great so far, but then since April 11, the app stopped working in a way that all the call to GMail APIs are failing with 404 error.
To give a clue, we have a library from where we call google client to perform actions, something like this:
def thread_metadata(id)
#metadata ||= execute(gmail_api.users.threads.get,
{
'collection' => 'public',
'userId' => 'me',
'id' => id,
'format' => 'metadata',
'metadataHeaders' => 'Subject'
}
)
However, the response which we get from Google is 404 with a message something like this:
he requested URL /discovery/v1/apis/gmail/v1/gmail/v1/users/me/threads/16365500056684b0?collection=public&format=full was not found on this server. That’s all we know.
I don't have any clue what has gone wrong except that the 404 error which started coming in suddenly since April 11.
You'll need to update your google-api-client gem, as of v0.8.6 they changed where the baseUrl is to make requests. Presumably the path the old gems were still using remained unchanged until recently.
The method_base used to generate the URI returns something different pre-0.8.6:
irb(main):046:0> gmail_api.method_base
=> #<Addressable::URI:0x3ff4ff4e319c URI:https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest>
In 0.8.6+:
irb(main):009:0> gmail_api.method_base
=> #<Addressable::URI:0x3ff97faf4610 URI:https://www.googleapis.com/>
Hi I use gem Nokogiri to scrape the gem getails from ruby-toolbox
Nokogiri::HTML(open("https://www.ruby-toolbox.com/categories/by_name"))
but I get the error: "403 Forbidden"
Can anyone tell me why I am getting this error?
Thanks in advance
Try to change your user-agent:
Nokogiri::HTML(open("https://www.ruby-toolbox.com/categories/by_name", 'User-Agent' => 'firefox'))
www.ruby-toolbox.com doesn't seem to accept 'ruby' as an agent.
As mentioned, the user agent has to be changed. However, in addition to that you have to disable the SSL certificate verification since it would throw an error as well.
require 'nokogiri'
require 'open-uri'
require 'openssl'
url = 'https://www.ruby-toolbox.com/categories/by_name'
content = open(url, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE, 'User-Agent' => 'opera')
doc = Nokogiri::HTML(content)
doc.xpath('//div[#id="teaser"]//h2/text()').to_s
# "All Categories by name"
This seems to be an OpenURI issue. Try this:
Nokogiri::HTML(open("https://www.ruby-toolbox.com/categories/by_name", 'User-Agent' => 'ruby'))
I spent ~1 hour trying solutions for a 403 forbidden, including tinkering with the User-Agent argument to Nokogiri::HTML(open(www.something.com, User-Agent: "Safari")), looking into proxies, and other things.
But the whole time there was nothing wrong with my code, the website I had been automated browsing had subtly changed url, and the url it previously visited was fobidden.
I hope this may save someone else some time.
I'm trying to get an access token from Google API in my Ruby on Rails app, as part of an overall goal of setting up a raketask. I am able to get an Auth Code fine, but when I make a post request to get an access token, I am getting a 302 error. I'll describe my current code first, and afterward list how I've tried to solve the problem so far.
Current code:
#users_controller
def auth_access
client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_endpoint_uri => 'https://accounts.google.com/o/oauth2/token',
:client_id => ENV['OAUTH_CLIENT_ID'],
:client_secret => ENV['OAUTH_CLIENT_SECRET'],
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:redirect_uri => 'http://localhost:3000/google/auth_callback'
)
redirect_to client.authorization_uri.to_s
end
This part works fine so far. It redirects to the consent page, and when the user agrees it then redirects them to the page with the auth code in the url parameters. Next I take that auth code and try to make a POST request to API for an access token:
#users_controller
def auth_callback
http = Net::HTTP.new('accounts.google.com')
path = '/o/oauth2/token'
data = "code=#{params['code']}&client_id=#{ENV['OAUTH_CLIENT_ID']}&client_secret=#{ENV['OAUTH_CLIENT_SECRET']}&redirect_uri=http://localhost:3000/auth_final&grant_type=authorization_code"
response = http.post(path, data)
end
This when I run into a problem. The Google API returns a 302, and includes a message saying something akin to "we moved to 'https://accounts.google.com/o/oauth2/token'".
Here's how I've tried to fix the problem so far:
I assumed that the problem was that the http.post method is making a call to an http and not https.
I've tried including
http.use_ssl = true
http.ssl_version = :SSLv3
This returns the error "SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number".
I can take a guess at what this means, but I am still unsure of what the actual problem is and how to solve it. Googling the error message has not been a help.
In a similar vein, I tried using gems to make the https call for me, in particular HTTParty and Typheous, although I was not able to make any progress with them (and am still not even sure that it's an http/https problem).
I've tried using the Signet-Rails gem. This was the most productive method by far, making a successful API call and returning the information. However, it either wasn't saving the refresh token or I cannot find where it is being saved. As I need access to that token to run the rake tasks, I gave up on Signet-Rails.
I tried using Legato, and was constantly running into various problems. Overall, Legato left me with the impression that it did not integrate getting the auth code, consent and tokens into the app, instead requiring the developer to set those up in advance outside of the app's scope. I want to be able to set up the auth code as part of the app. If I am understanding Legato properly, then it is not the gem I need.
I've also tried other various odds and ends but to no avail. The above solutions were the tactics I kept coming back to. Primarily I'm looking for an answer to what is going wrong in my code, and what is the best avenue to fix it (and if I was going down the right track with any of my attempted solutions above, which one?)
Thanks for taking the time to read this and answer!
(on a complete sidenote, those last three list items should be 2, 3, 4, but the stackoverflow text editor thinks it knows better than me...)
Specify the port:
http = Net::HTTP.new('accounts.google.com', 443)
Source: SSL Error on HTTP POST (Unknown Protocol)
i am trying to upload a file to box.com with their v2 api.
i am able to successfully upload a file with curl, but cannot upload a file from my rails application. i am passing my upload function the correct folder id and file is a tempfile object created by a form upload in my app.
here is the successful curl command
curl https://upload.box.com/api/2.0/files/data -H "Authorization: BoxAuth api_key=API_KEY&auth_token=TOKEN" -F contract=#test.png -F folder_id=387656851 -ssl3
and here is my ruby code
class BoxApi
require 'httmultiparty'
include HTTMultiParty
ssl_version :SSLv3
def initialize
#key = API_KEY
#token = TOKEN
end
def upload_file(folder_id,file,filename,content_type)
File.open(file) do |open_file|
response = self.class.post('https://upload.box.com/2.0/files/data', :query => {
:file => open_file,
:folder_id => folder_id
}, :headers => {'Authorization' => "BoxAuth api_key=#{#key}&auth_token=#{#token}"})
p response
end
end
i get an html page back from box with this text
It appears that your firewall may be blocking Box or you are encountering an error.Please contact your IT administrator to configure your firewall to recognize all sub-domains of .box.com, .box.com and .boxcdn.net. The ports that should be opened for these domains are 80 and 443.If that does not resolve the issue, then please submit a support ticket at https://www.box.com/help.
any ideas why the curl command would be working but not the ruby code?
Despite from being late, this could be useful for people who came across this question.
There is a gem ruby-box to use with Box service at the 2.0 version of their API.
This works properly for me
require 'httmultiparty'
class SomeClient
include HTTMultiParty
base_uri 'https://api.box.com/2.0'
end
response = SomeClient.post('/files/data',
:headers => { 'authorization' => 'BoxAuth api_key={YOUR API KEY}&auth_token={YOUR TOKEN' },
:body => { :folder_id => '0', :somefile => File.new('large.jpeg')}
)
I would try to verify that
You can make non-upload API calls (i.e. GET /folders/0)
If not, check your firewall settings.
Sean already covered this in his answer but I'll highlight it explicitly. We had some issues using the https://upload.box.com URL which is no longer recommended by box. I'd recommend trying the https://api.box.com/2.0 URL and seeing if that it changes your results.
Worst case I'd try capturing my packets using a packet analyzer like wireshark and looking for differences between the two cases.
Can anyone explain me with an example, by using REST Client to do GET/POST/PUT operations in a Rest web service?
In POST/PUT, using REST Client, need to pass the whole xml body to do
POST/PUT operations.
For example, Using REST Client
I need to get the content of a service using,
RESTClient.get(url)
POST an xml to an url:
RESTClient.post(url,entirexml)
PUT an xml to an URL:
RESTClient.put(url,entirexml)
DELETE using REST CLIENT.
Can anyone help me with examples for all the REST Client HTTP METHODS with example?
I need to send the whole XML along with namespace to a rest service using PUT/POST operations of REST Client.
If anyone have examples on this, kindly post then please.
require 'rest-client'
RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}}
RestClient.get 'http://example.com/resource'
xml = '<xml><foo>bar</foo><bar>foo</bar></xml>'
RestClient.post 'http://example.com/resource', xml , {:content_type => :xml}
RestClient.put 'http://example.com/resource', xml , {:content_type => :xml}
RestClient.delete 'http://example.com/resource'
See more examples and documentation at https://github.com/rest-client/rest-client
The Readme file at the git site for the rest-client gem has a whole bunch of examples of how to do requests, include parameters, etc.
I'd start with that.
If there are specific things that are not working, then it generally helps to post the code you've tried that you think SHOULD be working, and then it's usually easier for people to tell where you are going wrong.