Google API Ruby Client

repository·main·Indexed 25 days ago

https://github.com/googleapis/google-api-ruby-client

A collection of automatically generated, simple REST client libraries for various Google APIs in Ruby. These libraries connect to HTTP/JSON REST endpoints and are officially supported on Ruby 3.2+. The repository provides guidance on authentication using API keys and OAuth 2.0 (via googleauth or signet), OpenTelemetry configuration for tracing, and implementation flows for web and installed applications.

Tokens
15.9K
Snippets
47
Records
98
Agent score
83%

What's inside google-api-ruby-client

  1. Understand OAuth 2.0 concepts for Google APIs

    main

    Google APIs use OAuth 2.0 for authorization. Key concepts include:

    • Scope: A set of operations permitted by an API (e.g., read-only vs. read-write). Your application must request specific scopes, and users must approve them.
    • Access Tokens: Used to authorize individual API calls. They are short-lived and expire.
    • Refresh Tokens: Used to acquire new access tokens once they expire. They do not expire like access tokens.
    • Client ID and Client Secret: Unique identifiers for your application created in the Google API Console.
      • Web application client IDs
      • Installed application client IDs
      • Service Account client IDs

    Warning: Keep your client_secret private to prevent unauthorized quota consumption and data access.

  2. Understand API access types: Simple vs. Authorized

    main

    Google APIs use two primary access types depending on the data being accessed:

    1. Simple API access (API keys): Used for calls that do not access private user data. The key identifies the application/project for accounting and quota purposes.
    2. Authorized API access (OAuth 2.0): Required for calls that access private user data. This requires the user to grant your application permission via OAuth 2.0 flows.

    Always check the specific API's method documentation to determine which access type is required for a particular method.

  3. Get Application Default Credentials (ADC)

    main

    For APIs that do not require per-user authorization, use Application Default Credentials.

    1. In Google hosting environments (GCE, App Engine, GKE, Cloud Run, Cloud Functions): The environment provides credentials automatically.
    2. Outside Google hosting: Create a service account, download the JSON key file, and set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the full path of that file.

    Load these credentials in Ruby using the googleauth gem:

    authorization = Google::Auth.get_application_default
    authorization = Google::Auth.get_application_default
  4. Access documentation for Google REST clients

    main

    For detailed information on using the client libraries, refer to the following guides:

    • Usage Guide: Covers making API calls, using data structures, media upload/download, error handling, retries, pagination, and logging.
    • Auth Guide: Covers authentication methods including API keys, OAuth 2.0, service accounts, and environment variables.
    • API Reference: For specific method and call details, consult the {Google::Apis class reference docs}.
  5. Configure OpenTelemetry for Tracing

    main

    OpenCensus support is deprecated. To enable tracing for HTTP and HttpClient and export data to Cloud Trace, configure OpenTelemetry with the following gems and setup:

    Required gems:

    • opentelemetry-sdk
    • opentelemetry-exporter-google_cloud_trace
    • opentelemetry-instrumentation-http
    • opentelemetry-instrumentation-http_client
    gem "opentelemetry-sdk"
     gem "opentelemetry-exporter-google_cloud_trace"
     gem "opentelemetry-instrumentation-http"
     gem "opentelemetry-instrumentation-http_client"
     
    require "opentelemetry-sdk"
    require "opentelemetry/instrumentation/http_client"
    require "opentelemetry/instrumentation/http"
    require "opentelemetry/exporter/google_cloud_trace"
    OpenTelemetry::SDK.configure do |c|
      c.service_name = "ServiceName"
      c.add_span_processor(
        OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
          OpenTelemetry::Exporter::GoogleCloudTrace::SpanExporter.new
        )
      )
      c.use "OpenTelemetry::Instrumentation::Http"
      c.use "OpenTelemetry::Instrumentation::HttpClient"
     end
  6. Choose between Simple REST clients and Modern clients

    main

    Google provides two types of Ruby client libraries:

    1. Simple REST clients (found in this repository): These connect to HTTP/JSON REST endpoints and are automatically generated. They support most API functionality but may have awkward class interfaces.
    2. Modern clients (found in google-cloud-ruby): These are often backed by high-performance gRPC endpoints. They are generally easier to use, more Ruby-like, and support advanced features like streaming and long-running operations.

    Recommendation: Use a modern client if one is available for your service. Use a simple client only if a modern client does not exist or if your infrastructure cannot support gRPC.

  7. Configure the OAuth 2.0 client object

    main

    To begin the OAuth 2.0 flow, configure a client object using your client_secrets.json file. You must specify the required scope and the redirect_uri where Google will send the response.

    For offline access (to obtain refresh tokens) and incremental authorization, use the additional_parameters option with access_type set to offline and include_granted_scopes set to true.

    require 'google/apis/drive_v2'
    require 'google/api_client/client_secrets'
    
    client_secrets = Google::APIClient::ClientSecrets.load
    auth_client = client_secrets.to_authorization
    auth_client.update!(
      :scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
      :redirect_uri => 'http://www.example.com/oauth2callback',
      :additional_parameters => {
        "access_type" => "offline",         # offline access
        "include_granted_scopes" => "true"  # incremental auth
      }
    )
  8. Authenticate using API keys for simple API access

    main

    For API calls that do not access private user data, you can use an API key to authenticate your application for accounting and quota purposes. To use an API key, set the key attribute on your service object.

    Warning: Keep your API key private to prevent unauthorized usage of your project's quota or incurring charges.

    require 'google/apis/translate_v2'
    
    translate = Google::Apis::TranslateV2::TranslateService.new
    translate.key = 'YOUR_API_KEY_HERE'
    result = translate.list_translations('Hello world!', 'es', source: 'en')
    puts result.translations.first.translated_text
  9. Set up Google Cloud credentials for web applications

    main

    To use the client in a server-side web environment (like the Sinatra sample provided), you must configure a Google Cloud project with OAuth 2.0 credentials:

    1. Create a project at https://console.developers.google.com.
    2. Enable the required APIs (e.g., Drive and Calendar) in the API Manager.
    3. Navigate to Credentials and create a new OAuth Client ID of type 'Web application'.
    4. Set the following values in your Google Cloud Console:
      • Redirect URL: http://localhost:4567/oauth2callback
      • JavaScript origin: http://localhost:4567
  10. Authenticate users and exchange authorization codes

    main

    To complete the OAuth 2.0 flow:

    1. Generate the Authorization URL: Use auth_client.authorization_uri.to_s to get the URL.
    2. Open the URL: Use a tool like Launchy to open the URL in the user's system browser.
    3. Exchange the Code: Once the user provides consent, capture the authorization code and use fetch_access_token! to exchange it for an access token.
    # 1. Get URI
    auth_uri = auth_client.authorization_uri.to_s
    
    # 2. Open in browser (requires 'launchy' gem)
    require 'launchy'
    Launchy.open(auth_uri)
    
    # 3. Exchange code for token
    auth_client.code = 'AUTHORIZATION_CODE_FROM_BROWSER'
    auth_client.fetch_access_token!