Skip to content
This repository has been archived by the owner on Jul 29, 2021. It is now read-only.

Commit

Permalink
Added support for appending Google API Key to requests
Browse files Browse the repository at this point in the history
  • Loading branch information
njh committed Nov 19, 2013
1 parent 3c94545 commit 4670648
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/freebase_api.rb
Expand Up @@ -6,6 +6,7 @@ module FreebaseApi
USER_AGENT = 'DbpediaLite/1'
MQLREAD_URI = URI.parse('https://www.googleapis.com/freebase/v1/mqlread')
RDF_BASE_URI = URI.parse('http://rdf.freebase.com/rdf/')
GOOGLE_API_KEY = ENV['GOOGLE_API_KEY']
HTTP_TIMEOUT = 2

class Exception < Exception
Expand All @@ -17,16 +18,20 @@ class NotFound < FreebaseApi::Exception
def self.mqlread(query)
uri = MQLREAD_URI.clone
uri.query = 'query='+CGI::escape(JSON.dump(query))


unless GOOGLE_API_KEY.nil?
uri.query += "&key=#{GOOGLE_API_KEY}"
end

http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = HTTP_TIMEOUT
http.read_timeout = HTTP_TIMEOUT

if uri.scheme == 'https'
http.use_ssl = true
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

res = http.get(uri.request_uri, {'User-Agent' => USER_AGENT})

# Throw an exception if HTTP request was unsuccessful
Expand Down
25 changes: 25 additions & 0 deletions spec/freebase_api_spec.rb
Expand Up @@ -69,6 +69,31 @@
@data['key']['value'].should == '645042'
end
end

context "making a request with a Google API key" do
before :each do
FreebaseApi.send(:remove_const, 'GOOGLE_API_KEY')
FreebaseApi.const_set('GOOGLE_API_KEY', 'mykey')
FakeWeb.register_uri(:get,
%r[https://www.googleapis.com/freebase/v1/mqlread],
:body => fixture_data('freebase-mqlread-en-new-york.json')
)
@data = FreebaseApi.lookup_by_id('/en/new_york')
end

after :each do
FreebaseApi.send(:remove_const, 'GOOGLE_API_KEY')
FreebaseApi.const_set('GOOGLE_API_KEY', nil)
end

it "should put the Google API key in the query string" do
FakeWeb.last_request.path.should match(/key=mykey/)
end

it "should return the name of the topic" do
@data['name'].should == 'New York City'
end
end

context "lookup up a Wikipedia pageid that doesn't exist in Freebase" do
before :each do
Expand Down

0 comments on commit 4670648

Please sign in to comment.