wartalker
wartalker

Reputation: 348

how to authorizate use google-api-ruby-client

i am using google api for ruby, but not know how to start, just give me an ABC example someone, thanks very much?

Upvotes: 6

Views: 2869

Answers (2)

Ivan Fragoff
Ivan Fragoff

Reputation: 126

If you are creating a Service Account application to access Google Analytics.

  1. Register it with Google through https://code.google.com/apis/console. On API Access tab, click Create client ID, choose Service Account. Store the key file Google will generate, and remember the password for that key.
  2. Here is some code to get you started

    require 'rubygems'
    require 'google/api_client'
    
    api_client = Google::APIClient.new
    path_to_key_file ="/path/to/key/file-privatekey.p12"
    passphrase = "google_generated_password"
    key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase)
    

Once a key is available, initialize the asserter with your client ID (email in APIs console) and authorization scopes.

asserter = Google::APIClient::JWTAsserter.new(
   'super_long_client_id_from_api_console@developer.gserviceaccount.com',
   'https://www.googleapis.com/auth/analytics.readonly',
   key)

# To request an access token, call authorize:
api_client.authorization = asserter.authorize()
puts api_client.authorization.access_token

http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts

Upvotes: 11

Ben
Ben

Reputation: 1213

I've answered something similar in a couple of other posts I found that were like this one... so incase its relevant, for ruby, using the google-api-client (for any of the google apis), there's a few ins and outs with authentication when using an api key as opposed to OAuth...

I've outlined this process (using an api key server side) at the code abode.

You have to explicitly set the authorzation param to nil when constructing the client, otherwise the gem tries to use OAuth to authenticate, so if calling from a server using an api key only, you will always get a 401 Unauthorized.

the code abode - google-api-client for ruby

Upvotes: 0

Related Questions